django中的表单发布后无法重定向到URL

时间:2015-06-25 11:41:20

标签: python django django-formwizard

我在django1.8中创建了一个用户注册系统。但是当我单击表单上的注册按钮时,它不会重定向到成功URL。我也不确定这是否是在数据库中保存用户信息的正确方法。如果有更好的方法在django中进行用户注册,请建议。

Models.py

from django.db import models
from django.contrib.auth.models import User  

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    age = models.IntegerField(blank=True)
    gender_choices = (('M', 'Male'), ('F', 'Female'))
    gender = models.CharField(max_length=1, choices=gender_choices, default='Male')

forms.py

from django import forms
from .models import UserProfile


class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        exclude = ['user']

Views.py

from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .forms import UserProfileForm


# Create your views here.


def registerView(request):

    if request.method == "POST":
        user_form = UserCreationForm(request.POST)
        user_profile_form = UserProfileForm(request.POST)

        if user_form.is_valid() and user_profile_form.is_valid():
            new_user = user_form.save()
            new_user_profile = user_profile_form.save()

            return redirect(reverse('success'))

        else:
            return render(request, 'register.html', {'user_form': user_form, 'user_profile_form': user_profile_form})

    else:
        user_form = UserCreationForm(request.POST)
        user_profile_form = UserProfileForm(request.POST)

        return render(request, 'register.html', {'user_form': user_form, 'user_profile_form': user_profile_form})


def successView(request):

    username = User.objects.get('username')
    return render(request, 'success.html', {'username': username})

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.registerView, name='register'),
    url(r'^success/$', views.successView, name='success')

]

register.html

<h1> Welcome </h1>
       <form method="POST" action="{% url 'success' %}">
           {% csrf_token %}
           {{ user_form.as_p }}
           {{ user_profile_form.as_p }}
           <input type="button" value="Register"/>
       </form>

success.html

<h4> Yo Mr...{{ username }}</h4>
<h1>Welcome</h1>

1 个答案:

答案 0 :(得分:1)

您需要进行以下更改:

<h1> Welcome </h1>
       <form method="POST" action="{% url 'register' %}">
           {% csrf_token %}
           {{ user_form.as_p }}
           {{ user_profile_form.as_p }}
           <input type="submit" value="Register"/>
       </form>