form.is_valid()始终返回false

时间:2013-12-24 09:18:10

标签: python django django-forms

我已经尝试过在SO上给出的所有解决方案,但是无法解决这个问题

view.py

def signup(request):   
    form = SignupForm(request.GET)
    print("%s"%request.GET['hobby'])
    form.errors
    #h=SignupForm(request.POST)
    if form.is_valid():
        email = request.GET['email']
        location = request.GET['location']  users=User(username=username,email=email,password=request.GET['password'],location=location)
        user_profile = request.user.profile
        user_profile.location = location
        user_profile.save()        
        form.save()
        return HttpResponseRedirect('mtweet/')
    return render(request,'mtweet/signup.html',{'SignupForm':form})

form.py

class SignupForm(UserCreationForm):
    username=forms.CharField(label = " Username",required=True)
    email = forms.EmailField(label = "Email",required=True)
    password = forms.CharField(widget = forms.PasswordInput,required=True)
    location=forms.CharField(label="Location",required=False)
    class Meta:
        model = User
        fields = ("username", "email","location")

signup.html

<div id="register">
 <form method="post" action="{% url 'mtweet.views.signup' %}">
   {% csrf_token %}
   <table>
        {{ SignupForm.as_p}}
   </table>
   <input type="submit" value="Submit" />
 </form>
</div> 

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题;让我试着重写它:

class SignupForm(forms.Form):
    username=forms.CharField(label = " Username",required=True)
    email = forms.EmailField(label = "Email",required=True)
    password = forms.CharField(widget=forms.PasswordInput,required=True)
    location=forms.CharField(label="Location",required=False)

def signup(request):   
    form = SignupForm(request.POST, request.FILES)
    if form.is_valid():
        email = form.cleaned_data['email']
        location = form.cleaned_data['location']
        password = form.cleaned_data['password']
        username = form.cleaned_data['username']
        user = User.objects.create_user(username, email, password)
        user.save()
        user_profile = user.profile
        user_profile.location = location
        user_profile.save()        
        return HttpResponseRedirect('mtweet/')
    else:
        return render(request,'mtweet/signup.html',{'SignupForm':form})
    return render(request,'mtweet/signup.html',{'SignupForm':SignupForm()})