使用modelform时查看不显示

时间:2018-04-24 18:27:29

标签: django modelform

我尝试使用django中的模型表单来显示表单。一切看起来都设置得恰到好处,而且我没有收到任何错误。简单来说,虽然网址已更新,但表格未显示...

views.py

from rulz.models import Rulz

class rules_create(CreateView):
    model = Rulz
    fields=['title', 'content']

models.py

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

urls.py(在应用程序中)

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

urls.py(根文件夹)

...
url(r'^rules/',include('rulz.urls')),
...

应用程序/模板/应用程序/ rulz_form.html

{% extends 'rulz/Rulz_base.html' %}

{% block body %}

{% load staticfiles %}

{% include 'rulz/form-template.html' %}


{% endblock %}

应用程序/模板/应用程序/形状template.html

{% 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/,但显示的页面完全相同。

有任何线索吗?

由于

2 个答案:

答案 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(), ...

(另外,你应该避免为同一个视图设置两种模式。)