有效表单在django中不会有效

时间:2017-07-26 07:13:03

标签: django django-forms django-views

我在django中有一个有效的表单,但是当我尝试在grabbin gthe cleaning_data之前验证它时,它给了我一个错误,我不知道它为什么会发生。有人可以帮我解决这个问题吗...我有一种感觉它是小的但我得到编码器阻止而且看不到它..

这里是view.py方法:

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)

这是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 %}

以下是我从浏览器中获得的内容:

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'

一切都过去了,并且有效..

它正在打印第一个打印语句的表单,但之后没有任何内容,这意味着is_valid部分出错,但我无法弄清楚...

已更新

我弄清楚是什么给了我这个错误。这是我对models.py文件的选择部分。我做了什么修复它是我没有设置teh models.py文件中的选项或选项,而是添加了forms.py文件中的选项,它被添加到表单而不是模型...这里是什么我的代码现在看起来......

models.py文件

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文件:

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']

views.py文件:

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)

1 个答案:

答案 0 :(得分:2)

您应该将else变量移出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) 子句

request

POST方法为{{1}}时,不执行else子句,即引发错误。

相关问题