我使用这个应用程序来注册我的网站https://github.com/egorsmkv/simple-django-login-and-register的用户。问题是,无论我做什么,我的形式是不可见的(他们是当我没有使用这个注册应用程序和代码工作得很好)。这是我的代码:
模型class UserBio(models.Model):
name = models.CharField(max_length=120)
age = models.CharField(max_length=2)
phone = models.CharField(max_length=10)
height = models.CharField(max_length=3)
weight = models.CharField(max_length=3)
形式class UserBio(forms.ModelForm):
class Meta:
model = UserBio
fields = (name', 'age', 'phone', 'height', 'weight')
观点
def add_bio(request):
submitted = False
if request.method == "POST":
info_form = UserBio(request.POST)
if info_form.is_valid():
info_form.save()
return HttpResponseRedirect('add_information?submitted=True')
else:
info_form = UserBio()
if 'submitted' in request.GET:
submitted = True
return render(request, 'accounts/profile/add_information.html', {'form': info_form, 'submitted':submitted})
url
urlpatterns = [
path('add/information', views.add_information, name='add_information'),
]
html
{% extends 'layouts/default/base.html' %}
{% block title %} Add info {% endblock %}
{% load i18n %}
{% block content %}
<h4>{% trans 'Add Info' %}</h4>
{% if submitted %}
Sumitted correctly
{% else %}
<form method="post">
{% csrf_token %}
{{ info_form.as_p }}
</form>
</div>
<br/>
</body>
{% endif %}
{% endblock %}
任何帮助将非常感激!
因为在您的视图def add_bio中更改url acc为您的函数视图
path('add/information', views.add_bio, name='add_information'),
和你的模板
{{ form.as_p }}
将info_form
变量传递给变量名为form
的模板。事实上:
# name of the variable for the template ↓
return render(request, 'accounts/profile/add_information.html', {'form': info_form, 'submitted':submitted})
这就意味着你可以用:
{{form.as_p }}
你还应该触发正确的视图:
urlpatterns = [
path('add/information/',views.add_bio, name='add_information'),
]
路径不指向模板:路径指向视图,视图可以(这不是必需的)呈现零、一个或多个模板来创建HTTP响应。