0

Lets say I have this model.py:

class Order(models.Model):
    delivery = models.BooleanField()

I have this form.py:

class OrderForm(ModelForm):
    class Meta:
        model = Order
        fields = ["delivery"]

And I have this views.py:

def get_order(request):
    if request.method == "POST":
        form = OrderForm(request.POST)
        if form.is_valid():
            order_instance = Order(form.cleaned_data["delivery"])
            order_instance.save()
            return HttpResponseRedirect("/end")
    else:
        form = OrderForm()
    return render(request, "forms/test.html", {"form": form})

And the HTML page show form page.

With this code my program will tell me that he is not happy because I am giving "null" to "delivery" field because Django automatically create a "id" field for each model so he want me to give him the "id" and the "delivery" fields.

The "id" field is supposed to auto increment though. It is my primary key. But with form it doesn't seem to work. Is there a way to only specify the delivery and let the auto increment do the job for the id ?

Titouan
  • 15
  • 5

3 Answers3

0

If you want the form on django template then add a context dictionary.

context = {
'form':form,
}
return render(request, 'appname/template-name.html', context)

Add this after the else statement.

zabop
  • 6,750
  • 3
  • 39
  • 84
apollos
  • 341
  • 1
  • 10
  • I dont have any problem with my form display. My question regard the "id" field. I dont want the user to have anything to do with this field. He is supposed to auto increment but its not working. – Titouan Aug 27 '21 at 13:02
0

The auto increment of an id field doesn't work because you don't save the object retreived from the form. Try to use order_instance.save(). Also see the documentation.

  • Just saw I did some error in the code I posted. Its not the problem though because its not my true code. I will edit my post. – Titouan Aug 27 '21 at 14:52
0

Have you registered the Model in the admin.py file? if not then go your app folder and locate the admin.py and do this:

from .models import modelnamehere
admin.site.register(modelnamehere)

Do this and let me know if your problem was solved. Ordinarily django adds the id field to your models automatically.

apollos
  • 341
  • 1
  • 10