我尝试使用django中的模型表单来显示表单。一切看起来都设置得恰到好处,而且我没有收到任何错误。简单来说,虽然网址已更新,但表格未显示...
from rulz.models import Rulz
class rules_create(CreateView):
model = Rulz
fields=['title', 'content']
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Rulz(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
country = models.CharField(max_length=255,default='France')
city = models.CharField(max_length=255,default='Paris')
player_num = models.IntegerField(default=2)
complexity = models.IntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User,on_delete=models.CASCADE,default=1)
def get_absolute_url(self):
return reverse('rulz:rulz_detail',kwargs={'pk':self.pk})
app_name = 'rulz'
urlpatterns = [
#/rulz/
url(r'^', views.rules_index.as_view(), name='rulz_index'),
url(r'^index/$', views.rules_index.as_view(), name='rulz_index'),
# /rulz/details
url(r'^(?P<pk>[0-9]+)/$',views.rules_detail.as_view(),name='rulz_detail'),
#rulz/create
url(r'^create/',views.rules_create.as_view(),name='rulz_create'),
]
...
url(r'^rules/',include('rulz.urls')),
...
{% extends 'rulz/Rulz_base.html' %}
{% block body %}
{% load staticfiles %}
{% include 'rulz/form-template.html' %}
{% endblock %}
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<div class="validate-input m-b-26" >
<label class="label-input100">{{ field.label_tag }}</label>
<div class="input100">{{ field }}</div>
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.help_text }}</span>
</div>
</div>
</div>
最后是我页面中带有链接的按钮,用于访问表单:
<a href="{% url 'rulz:rulz_create' %}" class="button alt">Go create Rule</a>
我真的不知道自己错过了什么。当我点击此按钮时,网址会上传到http://127.0.0.1:8000/rules/create/,但显示的页面完全相同。
有任何线索吗?
由于
答案 0 :(得分:1)
在documentation中,您可以找到使用CreateView
正确呈现表单所需的属性列表。
因此,您需要修改基于类的视图,使其至少看起来像这样:
from rulz.models import Rulz
class rules_create(CreateView):
form_class = YOUR_FORM # The form that will be used with this class
model = Rulz
fields=['title', 'content']
success_url = 'YOUR_SUCCESS_URL' # If success redirect to this URL
答案 1 :(得分:1)
您需要终止索引正则表达式。目前它匹配每个字符串有一个开始,这当然意味着每个字符串。使用$:
url(r'^$', views.rules_index.as_view(), ...
(另外,你应该避免为同一个视图设置两种模式。)