Home > Software engineering >  Why isn't a django database object created?
Why isn't a django database object created?

Time:06-01

I'm trying to create a drink database app in django. I have created a drinkRecipe model with ManyToManyField relation to Ingredients model. I can successfully add Ingredients to database via app UI, but for some reason when creating a drink, I get no errors nor do I add the drink to database, instead of going back to the index page only the URL of current page changes. What am I missing?

models.py:

class DrinkRecipe(models.Model):
drinkName = models.CharField(max_length=100)
ingredients = models.ManyToManyField(Ingredients)
utensil = models.IntegerField(choices=requiredUtensil, default=0)
preparation = models.CharField(max_length=1000)

def __str__(self):
    return self.drinkName

forms.py:

class DrinkForm(forms.Form):
name = forms.CharField(max_length=100, label="Name:")
utensil = forms.ChoiceField(choices=requiredUtensil, label="Required utensil:")
ingredients = forms.ModelChoiceField(queryset=Ingredients.objects.all(), widget=forms.CheckboxSelectMultiple())
preparation = forms.CharField(widget=forms.Textarea)

views.py:

class AddDrinkView(View):

def get(self, request):
    form_drinks = DrinkForm()
    drinks_list = DrinkRecipe.objects.all()
    context = {
        'form_drinks': form_drinks,
        'drinks_list': drinks_list,
    }
    return render(request, 'shakerApp/add_drink.html', context)

def post(self, request):
    form_drinks = DrinkForm(request.POST)

    if form_drinks.is_valid():

        DrinkRecipe.objects.create(
            name=form_drinks.cleaned_data['name'],
            utensil=form_drinks.cleaned_data['utensil'],
            ingredients=form_drinks.cleaned_data['ingredients'],
            preparation=form_drinks.cleaned_data['preparation']
        )
    else:
        messages.error(request, "Drink form is invalid.")

    return HttpResponseRedirect(reverse('shakerApp:index'))

*edited to change brackets per @Bono suggestion

**EDIT: So, I'm a moron and didn't add method='post' to in the template. That solved the part that I stayed in the add_drink view after hitting submit, but, the database still is not updated.

CodePudding user response:

instead of going back to the index page only the URL of current page changes. What am I missing?

Probable causes:

  1. The form is not valid but that is not handled properly
  2. The DrinkRecipe.objects.create calls fails and is caught by Django
  3. The post fails somewhere and is caught by Django

You can debug this by adding some print() statement or even a try/except around part you suspect.

CodePudding user response:

So, there was actually a problem with form. The DrinkRecipe model consists of ManyToManyField, and was not properly used in the corresponding form. Basically, ModelChoiceField couldn't work with widget=forms.CheckboxSelectMultiple(). Thank you to @ThePjot for pointing me in the right direction. Corrected below.

forms.py:

class DrinkForm(forms.Form):
    name = forms.CharField(max_length=100, label="Name:")
    utensil = forms.ChoiceField(choices=requiredUtensil, label="Required utensil:")
    ingredients = forms.ModelMultipleChoiceField(
        queryset=Ingredients.objects.all(),
        widget=forms.CheckboxSelectMultiple()
    )
    preparation = forms.CharField(widget=forms.Textarea)
  • Related