Django cant access variable from form created with ModelForm
I am trying to create a simple form based on ModelForm class in Django. Unfortunately I keep getting UnboundLocalError error. I checked numerous advises on similar issues, however it seems I have all the recommendations implemented.
If I run the below code, I get following error: UnboundLocalError: cannot access local variable 'cook_prediction' where it is not associated with a value
My models.py:
from django.db import models
class RecipeModel(models.Model):
i_one = models.BigIntegerField(default=0)
v_one = models.FloatField(default=0)
My forms.py:
from django import forms
from .models import RecipeModel
class RecipeInputForm(forms.ModelForm):
class Meta:
model = RecipeModel
exclude = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['i_one'].initial = 0
self.fields['v_one'].initial = 0
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . import forms
@login_required
def index(request):
if request.method == 'POST':
recipe_form = forms.RecipeInputForm(request.POST)
else:
recipe_form = forms.RecipeInputForm()
print("Recipe form errors: ", recipe_form.errors)
if recipe_form.is_valid():
print("Recipe form errors: ", recipe_form.errors)
cook_prediction = recipe_form.cleaned_data
if not recipe_form.is_valid():
print("Recipe form errors: ", recipe_form.errors)
print("Recipe form is not valid!")
After running the code, except for the above mentioned error message, I also get the Recipe form is not valid! printout from the last line of views.py.
How to get rid of this error and successfully get variable from form based on ModelForm?
You should not try to validate form if the request method is not POST. You're doing it unconditionally at the moment. Try changing the code to this:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . import forms
@login_required
def index(request):
if request.method == 'POST':
recipe_form = forms.RecipeInputForm(request.POST)
if recipe_form.is_valid():
print("Recipe form errors: ", recipe_form.errors)
cook_prediction = recipe_form.cleaned_data
# Any further processing of `cook_prediction` should happen here
# as this variable is unbound outside this block
else:
print("Recipe form errors: ", recipe_form.errors)
print("Recipe form is not valid!")
else:
recipe_form = forms.RecipeInputForm()
# The following line also doesn't make sense as on GET won't have errors
# print("Recipe form errors: ", recipe_form.errors)