0

I trying to to create a database panel for a restaurant app where a user can add, remove, view and create a menu for the restaurant. In this the user can add the name, cuisine, category(veg/non veg) and cost as details of the menu item.

Here is my Models.py:

class Cuisine(models.Model):
    cuisine = models.CharField(max_length=15)

    def __str__(self):
        return self.cuisine

    class Meta:
        verbose_name_plural = 'cuisines'


class Category(models.Model):
    category_type = models.CharField(max_length=9)

    def __str__(self):
        return self.category_type

    class Meta:
        verbose_name_plural = 'category type'


class Item(models.Model):
    name = models.CharField(max_length=50)
    cost = models.IntegerField()
    cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

Here is Forms.py:

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['name', 'cost']


class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['category_type']


class CuisineForm(forms.ModelForm):
    class Meta:
        model = Cuisine
        fields = ['cuisine']

And below is my Views.py:

@login_required()
def add_item(request):
    if request.method == 'POST':
        itemform = ItemForm(request.POST or None)
        catform = CategoryForm(request.POST or None)
        cuisineform = CuisineForm(request.POST or None)
        if itemform.is_valid():
            item = itemform.save(commit=False)
            ct = catform.save(commit=False)
            cui = cuisineform.save(commit=False)
            item.name = request.POST.get('name')
            cui.cuisine = request.POST.get('cuisine')
            ct.category = request.POST.get('category_type')
            item.cost = request.POST.get('cost')
            item.save()
            ct.save()
            cui.save()
            messages.success(request, 'Item added successfully!!')
        else:
            messages.warning(request, 'Unable to add the item.')
        return redirect('add_item')

    else:
        item_list = ItemList.objects.all()
        category = Category.objects.all()
        cuisine = Cuisine.objects.all()
        context = {
            'items': item_list,
            'category': category,
            'cuisine': cuisine
        }
        return render(request, 'add_item.html', context)

I am able to add add the menu item from the django admin panel but i am having a error while saving the data to database from the user side as i want to give user the authority to add the item. I am not able to save the form using .save() option.
I know the error is in my forms.py but i don't know what as i am new to Django. I am attaching the screenshot of the error as well as of my frontend page from where i am adding the data.

Here's the error :
enter image description here



Here's the frontend page :
enter image description here


Please note that i want to use Cuisine and Category as the dropdown list from the database.

1 Answers1

0

Actually you are trying to set...

ct.category = request.POST.get('category')

And as per your code ct assigned from catform.save(commit=False).

catform assigned from CategoryForm(request.POST or None)

And CategoryForm has model class Category, but Category model has no any attribute like category which is you are trying to set by as per below line...

ct.category = request.POST.get('category')

So, the form will be invalid and you can not save invalid form. Thus, your error came.

MK Patel
  • 1,354
  • 1
  • 7
  • 18
  • Thank you so much MK for the replying and checking for the error. I have edited my code and written ***category_type*** instead of **category** but still i am having the same issue. – Paritosh Chaudhary Mar 05 '20 at 10:59
  • you are edited `request.POST.get('category')` to `equest.POST.get('category_type')` but that is not my point. – MK Patel Mar 05 '20 at 11:02
  • 1
    you are trying to set `ct.category` and at there you have no any `category` field in `Category` model. Are you getting me properly? – MK Patel Mar 05 '20 at 11:03
  • Do you understood? – MK Patel Mar 05 '20 at 12:15
  • Thanks for explaining what i have written wrong. I am really sorry if i am not able to understand as i am new to this. Can please explain me more elaborately what i should have done so that my form is valid. What i am able to understand till now is that I have added the column to database by the name of **category_type** using model. Then to insert data to that column i am trying to use **forms**. Now as you are saying that there is no category field in the Category model this is what i am not understanding properly. – Paritosh Chaudhary Mar 05 '20 at 13:16
  • 1
    Its ok np, You have the `category_type` filed in your model. But you are trying to access `ct.category`, actually, there is no field name `category` in the `Category` model. – MK Patel Mar 05 '20 at 13:27
  • 1
    So, I am not sure but write `ct.category_type = request.POST.get('category_type')` instead of `ct.category = request.POST.get('category_type')`. – MK Patel Mar 05 '20 at 13:30
  • @ParitoshChaudhary understood or not? – MK Patel Mar 06 '20 at 06:03
  • Hey MK! Thanks for your guidance. I tried to do as you said above but the same error persists. Can you check if the process i am following is right or not like if i am calling the *Foreign Key* the way it is supposed to be called and function i am writing in the **views.py** is right or not? – Paritosh Chaudhary Mar 06 '20 at 07:06
  • 1
    Still on the same error ***The Category could not be created because the data didn't validate.*** – Paritosh Chaudhary Mar 06 '20 at 07:35
  • What are you get in `request.POST.get('category_type')` ? Mean just print this. – MK Patel Mar 06 '20 at 07:41
  • 1
    I am getting "None" when i print this, but on rest all i am getting the values only the 'category_type' is null. But when i change `request.POST.get('category_type')` to `request.POST.get('category')` i am able to get the value. But still the error is there on `ct = catform.save(commit=False)` line. here's the screenshot os error as well s the POST values[link](https://imgur.com/tbcsbxu) – Paritosh Chaudhary Mar 06 '20 at 08:00
  • 1
    Ok, so try to print `catform.errors` before this line `ct = catform.save(commit=False)`. Thus, you will get all error which is occurred in `catform` – MK Patel Mar 06 '20 at 08:52
  • 1
    I printed the error before `ct = catform.save(commit=False)` and i got this error `
    • category_type
      • This field is required.
    ` . Thus this error means that the code is not able to fetch the value ?
    – Paritosh Chaudhary Mar 06 '20 at 09:14
  • Yes, might be it is – MK Patel Mar 06 '20 at 09:16
  • `category_type` field is required and with the submission of `form`, this value might be empty or not submitted in `form`. I think this is the root cause of your error. – MK Patel Mar 06 '20 at 09:18
  • 1
    I just checked if i remove category and cuisine from the function the form is saving the data. The only problem is with the category and cuisine as these both are dropdowns in html template. But i am able to fetch the POST values as selected from the drop down. – Paritosh Chaudhary Mar 06 '20 at 10:19
  • 1
    Please refer this both link https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/ – MK Patel Mar 06 '20 at 10:33
  • Above both references are useful or not @ParitoshChaudhary ? – MK Patel Mar 06 '20 at 11:19
  • I will study both the links thoroughly and let you if i make any progress in this issue. Thanks for sharing the links and taking some time out for helping me. – Paritosh Chaudhary Mar 06 '20 at 16:26
  • Ok, sure. And If my answer and comments are useful for you then you can upvote my answer and accept it so, it will affect well on me too. – MK Patel Mar 09 '20 at 05:26
  • Happy coding :) – MK Patel Mar 09 '20 at 05:26