【问题标题】:Django from is not being past into html templateDjango from 没有进入 html 模板
【发布时间】:2020-10-31 03:53:15
【问题描述】:

正如问题标题"{{form}}" from is not being loaded into html template 我在以前的项目中检查过的一样,我有几乎相同的代码,不同之处在于必填字段、命名等。机制是相同的。 在这些项目中,注册功能在这里完美运行,它甚至没有抛出错误,只是不显示任何内容。 难怪这里可能有什么问题。

forms.py

    from django import forms
    from django.contrib.auth.forms import UserCreationForm    
    from .models import Profile 
    
    class RegistrationForm(UserCreationForm):
        email = forms.EmailField(max_length=60, help_text="Required field")    
    
        class Meta:
            model = Profile
            fields = ["email", "username", "password", "password2", "calories_plan", "diet_type"]

views.py

    def registration_view(request):
        context = {}
        if request.POST:
            form = RegistrationForm(request.POST)
            if form.is_valid():
                email = form.cleaned_data.get("email")
                password = form.cleaned_data.get("password")
                new_account = authenticate(email=email, password=password)
                login(request, new_account)
            else:
                context["registration_form"] = form
        else:
            form = RegistrationForm()
            context["registration_form"] = form
        return render(request, "Account/registration.html", context)

html模板

    {% extends 'main.html' %}
    {% load crispy_forms_tags %}
    
    {% block content %}
    
        <div class="content-section">
            <form method="post">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class=border-bottom mb-4>Join today                     
                        {{ form }}
                    </legend>
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info" type="submit">Sign Up</button>
                </div>          
            </form>
    
            <div class="border-top pt-3">
                <small class="text-muted">
                    Already have an account?
                    <a href="#" class="ml-2">
                        Log In
                    </a>
                </small>
            </div>
        </div>
    
    {% endblock %}

以及它在浏览器中的外观。

【问题讨论】:

    标签: html python-3.x django forms


    【解决方案1】:

    您将'registration_form' 传递给上下文,但在模板中您调用的是{{ form }}

    替换: {{ form }} 和: {{ registration_form }}

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 2021-03-10
      • 2020-08-22
      • 2011-04-03
      • 2022-01-17
      • 2020-09-12
      • 2016-09-28
      • 2018-08-10
      • 2013-10-11
      相关资源
      最近更新 更多