southernegro
southernegro

Reputation: 394

Django unable to save form trying to set user in a field

What I want to make, is to create a record of this class:

class Order(models.Model):
    OPTIONS = [
        ('1', 'Option 1'),
        ('2', 'Option 2'),
        ('3', 'Option 3'),
        ('4', 'Option 4'),
    ]
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    choice = models.CharField(choices=OPTIONS, max_length=60)
    custom = models.CharField(max_length=60)
    date = models.DateField(default=localdate)

Using this form:

<form method="POST" action="" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="input-group mb-3">
              <div class="input-group-append">
                <span class="input-group-text"><i class="fa fa-cutlery"></i></span>
              </div>
              {{form.choice}}
            </div>
            <div class="input-group mb-3">
              <div class="input-group-append">
                <span class="input-group-text"><i class="fa fa-comment"></i></span>
              </div>
              {{form.custom}}
            </div>
              <div class="d-flex justify-content-center mt-3">
                <input class="btn btn-success" type="submit" value="Confirm">
              </div>
          </form>

The form is defined in this way:

class orderForm(ModelForm):
    class Meta:
        model = Order
        fields = '__all__'

The template is rendered by this view:

@login_required
def createOrder(request):
    date = localdate()
    form = None

    item = Menu.objects.filter(date=date)
    if item.exists():
        instance = Order.objects.filter(user=request.user,date=date)
        if instance.exists():
            return render(request,'requestMenu.html',{'note': 'We\'re preparing your meal'})
        else:
            user = Order(user=request.user)
            form = orderForm()
            if request.method == 'POST':
                form = orderForm(request.POST)
                if form.is_valid():
                    form.save(commit=False)
                    form.user = request.user
                    form.save()
                    return render(request,'requestMenu.html',{'note': 'You\'re order has been saved. We\'re preparing it for you. Be patient.'})
            else:
                return render(request,'requestMenu.html',{'note': 'Choose your meal'})

So... it supossed that Date field will come by default (already checked it, that's working good) and User will be assigned with actual logged user, after the form is completed. But then, when I go to check the records of this table, there's nothing on it. So, what could be bad in my code? I think the problem is on the view.

Upvotes: 0

Views: 47

Answers (2)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

In your form you write fields = '__all__' this means that the form will create fields for all of your models fields. Hence this also means that the form will validate all of these fields regardless that you set these values manually or they have a default. But you are only rendering two fields namely choice and custom in the form and hence form.is_valid() returns False, therefore you should specify the fields that the form should use instead of setting it to __all__:

class orderForm(ModelForm):
    class Meta:
        model = Order
        fields = ['choice', 'custom']

Furthermore form.user = request.user would not do what you want instead change that part like so and directly modify the instance wrapped by the form:

if form.is_valid():
    form.instance.user = request.user
    form.save()

Note: A class name should ideally be in PascalCase not camelCase, hence use OrderForm instead of orderForm. Also function names should be in snake_case hence use create_order instead of createOrder. See PEP 8 -- Style Guide for Python Code

Upvotes: 1

Ashraful Islam
Ashraful Islam

Reputation: 571

            if form.is_valid():
                my_form = form.save(commit=False)
                my_form.user = request.user
                my_form.save()

Try now.

Upvotes: 0

Related Questions