Within my project, I have two interconnected models named Task
and Batch
, linked through a Foreign Key field. My goal is to verify the existence of a Batch Object
in the database before creating a new Task Object
. The Batch object represents the current date and allows tasks to be grouped accordingly. If a Batch object does not exist, one should be created and assigned to the Task being generated.
However, during the save process, I encounter an error:
(index):328 POST http://localhost:8000/api/task-create/ 500 (Internal Server Error)
Here's the relevant code snippets:
@api_view(['POST'])
def taskCreate(request):
batch = Batch.objects.filter(batch = datetime.date.today()).first()
serializer = TaskSerializer(data=request.data)
if serializer.is_valid():
serializer.save(commit=False)
if batch is None :
batch = Batch.objects.create(batch = datetime.date.today())
serializer.batch = batch
serializer.save()
return Response(serializer.data)
models.py
class Batch(models.Model):
batch = models.DateField(auto_now_add=True)
class Meta:
ordering = ['-batch']
verbose_name = 'Batch'
verbose_name_plural = 'Batches'
def __str__(self):
return self.batch.strftime("%B %d, %Y %A")
class Task(models.Model):
title = models.CharField(
max_length = 256,
)
completed = models.BooleanField(
default = False,
)
batch = models.ForeignKey(Batch, on_delete=models.CASCADE)
def __str__(self):
return self.title
serializers.py
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'
depth = 1
This snippet demonstrates how I handle form submission on the frontend:
var form = document.getElementById("form")
form.addEventListener('submit', function(e){
e.preventDefault()
var url = "{% url 'api:task-create' %}"
if(activeItem != null ){
url = `http://localhost:8000/api/task-update/${activeItem.id}/`
activeItem = null
}
var title = document.getElementById('title').value
fetch(url, {
method: 'POST',
headers:{
'Content-type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({'title':title})
}).then(function(response){
renderList()
document.getElementById('form').reset()
})
})