Omar Jandali
Omar Jandali

Reputation: 824

Valid form is not coming out as valid in django

I have a form in django that is valid but when I try to validate it before grabbin gthe cleaned_data, it is giving me an error and I dont know why it is happening. Can someone help me figure it out.. I have a feeling it is something small but I am getting coders block and can't see it..

here is view.py method:

def profile_setup(request):
    if 'username' not in request.session:
        return redirect('login')
    else:
        username = request.session['username']
        currentUser = User.objects.get(username = username)
        if request.method == 'POST':
            form = ProfileForm(request.POST)
            print(form)
            if form.is_valid():
                cd = form.cleaned_data
                age = cd['age']
                print(age)
                city = cd['city']
                print(city)
                phone = cd['phone']
                print(phone)
                privacy = cd['privacy']
                print(privacy)
                new_profile = Profile.objects.create(
                    user = currentUser,
                    age = age,
                    city = city,
                    phone = phone,
                    privacy = privacy,
                )
                return redirect('accounts')
        else:
            form = ProfileForm()
            message = 'fill out form below'
            parameters = {
                'form':form,
                'currentUser':currentUser,
                'message':message,
            }
        return render(request, 'tabs/profile_setup.html', parameters)

Here is the html:

{% extends "base.html" %}

{% block content %}
  <h1>Setup you profile: {{ currentUser.username }}</h1>
  {% if message %}
    {{ message }}
  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}

Here is what I am getting from the browser:

UnboundLocalError at /setup_profile/
local variable 'parameters' referenced before assignment
Request Method: POST
Request URL:    http://127.0.0.1:8000/setup_profile/
Django Version: 1.8.6
Exception Type: UnboundLocalError
Exception Value:    
local variable 'parameters' referenced before assignment
Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in profile_setup, line 153
Python Executable:  C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.1
Python Path:    
['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
Server time:    Wed, 26 Jul 2017 05:56:29 +0000
Traceback Switch to copy-and-paste view

C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py in get_response
                                response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in profile_setup
                    return render(request, 'tabs/profile_setup.html', parameters) ...
▶ Local vars
Request information

GET
No GET data
POST
Variable    Value
csrfmiddlewaretoken 
'EpPxClvN9jWbFQGqV3lhWnoIC53g0ny4'
age 
'22'
city    
'riverside'
phone   
'232414'
privacy 
'1'
submit  
'submit'

Everything is passing and is valid..

It is printing the form which is the first print statement, but nothing after that which means there is an error with the is_valid part, but i can't figure it out...

UPDATED

I figured out what was giving me the error. It was the choices section i had with the models.py file. What i did to fix it was I did not set the choices or options in teh models.py file, but rather added the options in the forms.py file and it was added to the form rather than the model... here is what my code looks like now...

models.py file

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)  # server
    age = models.IntegerField(default=0)
    city = models.CharField(max_length=45)  # user
    phone = models.BigIntegerField(default=0)  # user
    privacy = models.SmallIntegerField(default=1)  # user
    created = models.DateTimeField(auto_now_add=True)  # server

forms.py file:

class ProfileForm(forms.ModelForm):
    split_choices = (('1', 'public'),
                     ('2', 'private'))
    privacy = forms.TypedChoiceField(
        choices=split_choices, widget=forms.RadioSelect, coerce=int
    )
    class Meta:
        model = Profile
        fields = ['age', 'city', 'phone', 'privacy']

The views.py file:

def profile_setup(request):
    if 'username' not in request.session:
        return redirect('login')
    else:
        username = request.session['username']
        currentUser = User.objects.get(username = username)
        if request.method == 'POST':
            form = ProfileForm(request.POST)
            print(form)
            if form.is_valid():
                cd = form.cleaned_data
                age = cd['age']
                print(age)
                city = cd['city']
                print(city)
                phone = cd['phone']
                print(phone)
                privacy = cd['privacy']
                print(privacy)
                new_profile = Profile.objects.create(
                    user = currentUser,
                    age = age,
                    city = city,
                    phone = phone,
                    privacy = privacy,
                )
                return redirect('accounts')
        else:
            form = ProfileForm()
            message = 'fill out form below'
            parameters = {
                'form':form,
                'currentUser':currentUser,
                'message':message,
            }
            return render(request, 'tabs/profile_setup.html', parameters)

Upvotes: 0

Views: 72

Answers (1)

zaidfazil
zaidfazil

Reputation: 9245

You should move your parameters variable out of the else clause,

def profile_setup(request):
    if 'username' not in request.session:
        return redirect('login')
    else:
        username = request.session['username']
        currentUser = User.objects.get(username = username)
        message = None
        if request.method == 'POST':
            form = ProfileForm(request.POST)
            ......
        else:
            form = ProfileForm()
            message = 'fill out form below'
        #<==
        parameters = {
            'form':form,
            'currentUser':currentUser,
            'message':message,
        }
    return render(request, 'tabs/profile_setup.html', parameters)

When the request method is POST, the else clause is not executed, ie, the error is raised.

Upvotes: 2

Related Questions