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

型号

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


表格

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>

最佳答案

您需要进行以下更改:

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

关于python - 在Django中发布表单后无法重定向到URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31049365/

10-12 16:37