【问题标题】:Not able to redirect a Django form after submission提交后无法重定向 Django 表单
【发布时间】:2016-07-18 10:03:47
【问题描述】:

我是 Django 的新手,我创建的表单给我带来了一些麻烦。

我在 Django 中创建了一个用于用户身份验证和登录的表单。但是表单在点击提交后没有重定向到我指定的链接。我认为这是因为views.py 中的 authentication 函数将用户返回为 None。但这不应该发生,因为用户存在于数据库中。我已经通过 http://127.0.0.1:8000/admin/ 确认了这一点,这是 Django 的内部开发人员服务器。

我尝试将其重定向到的 URL 存在。那里没有问题。 与此相关的python文件有:

forms.py:

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


class UserForm(forms.ModelForm):


    class Meta:
        model = User
        fields = ['username', 'email', 'password']

views.py:

我省略了以下代码中的所有导入。没有问题。

class UserFormView(View):
    form_class = UserForm
    template_name = 'music/registration_form.html'

    def get(self, request):  # This function is executed if the server obtains a GET request.
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})
    '''
    The server gets a GET request every time a new user wants to register, i.e they want an empty form.
    That's why we pass None in the function above.
    It gets a POST request every time a filled form is submitted.
    '''

    def post(self, request): # This function is executed if the sever recevies a POST request.
        form = self.form_class(request.POST)

        if form.is_valid():
            user = form.save(commit=False) # This creates an object, but does not save it to the database.
            # Therefore, we can do some changes.

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            # Here, cleaned_data is converted data to suitable format. Like the date entered is converted to a
            # suitable format as its format is different all around the world.
            # Now you can change the username by user.username = 'some_name' or you can change the password by
            # user.set_password(new_password)

            user.save() # This line of code actually saves the code.

            user = authenticate(username=username, password=password)
            # This checks if the user actually exists in the database.

            if user is not None:
                if user.is_active: # This if the user is not banned or anything like that.
                    login(request, user) # This logs in the user.
                    return redirect('music:index')  # Redirects the user to index page.
            else:
                return render(request, self.template_name, {'form': form})

        else:
            form = self.form_class(None)
            return render(request, self.template_name, {'form': form})
    # This returns the filled form again if the the form is not valid.

注册表单模板为(html文件):

{% extends 'music/base.html' %}
{% block title%}Registration Form {% endblock %}

{% block body %}
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'music/index_style.css' %}" />

<div class="block">
    <form action="" method="post" >
         {% csrf_token %}
        <fieldset> <!-- Gives it a better look by putting a heading and background around the form -->
            <legend>Create a new account:</legend><!-- This the common heading for the form -->
            {% include 'music/form_template.html' %}
            <br>
            <input type="submit" value="Submit">
        </fieldset>
    </form>
</div>
{% endblock %}>

注册表单模板中包含的form_template.html是:

{{ form.non_field_errors }}
{{ form.errors }}
{{ form.as_p }}

另外,另一件不正常的事情是,每当我使用上述表单创建新用户时,该用户的密码显示为:

“无效的密码格式或未知的哈希算法。”

这可以在http://127.0.0.1:8000/admin/ 看到,我们可以在其中编辑当前用户。

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    这里有几个问题。

    您正确调用save 并使用commit=False,以允许您在正确保存之前设置散列密码(如cmets 状态),但您实际上从未这样做,因此使用未散列密码保存用户。这永远不会验证。

    同样,您从不设置用户的 is_active 属性,因此再往下检查总是会失败。

    user = form.save(commit=False)
    password = form.cleaned_data['password']
    user.set_password(password)
    user.is_active = True
    user.save()
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 2020-07-14
      • 2012-05-17
      • 2018-07-21
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多