[Answered ]-Django saving choices values

-1👍

This problem partial solved in django can’t save model choices selected values

2👍

Error is here:

date = MyModel.objects.order_by('date')[0]
name = MyModel.objects.order_by('name')[0]

MyModel.objects.order_by(‘date’) return a QuerySet, if queryset is empty, it has no index ‘[0]’. Try ‘first()’ instead [0]:

date = MyModel.objects.order_by('date').first()
name = MyModel.objects.order_by('name').first()

Case MyModel is empty, first return None
Docs:
https://docs.djangoproject.com/en/1.9/ref/models/querysets/#first

1👍

The issue is caused here:

def preview(request):
    form = MyModelForm()
    date = MyModel.objects.order_by('date')[0]
    name = MyModel.objects.order_by('name')[0]

You are querying objects, sorting and taking the first item. However, if there are no items it is not possible to do this. Instead use .first(), e.g.

    date = MyModel.objects.order_by('date').first()
    name = MyModel.objects.order_by('name').first()

This will return the first item, if there is one, or None if not. See the documentation for more info. There are also some other examples in this question for alternative ways to handle this.

However, I would recommend that you do not use this approach. When you save the new object (form01.save()) this returns the newly created object. You can then access this directly for your preview. For example:

preview_model = form01.save()

Using MyModel.objects.order_by('date').first() to get the ‘latest record’ opens you to a race condition when another user edits another object between the .save() and the select.

I’m not sure of the purpose of name = MyModel.objects.order_by('name').first() as this is going to return a completely different object to the previous bit (the first object sorted alphabetically) – and I cannot imagine why you would want that. Try something like the following in views.py:

def form1(request):
    form = MyModelForm()
    if request.method == 'POST':
        form01 = MyModelForm(request.POST, request.FILES)
        if form01.is_valid():
           preview = form01.save()
           date = preview.date
           return render(request, 'WebMamOffice/en/preview.html', {'form': form01, 'date': date, 'name': name})
    return render(request, 'WebMamOffice/en/form1.html', {'form': form})
👤mfitzp

0👍

your preview() view assumes at least one instance of MyModel exists: you’re accessing MyModel.objects.blah[0], which only works if there is something at [0].

👤dngrs

0👍

The best way to use ManyToManyField:

class Model2(models.Model):
    choice_field = models.ManyToManyField(to=Model1)

Leave a comment