简体   繁体   English

Django 表格不显示

[英]Django form doesn't show up

I'm working on some project and ended up with some issues.我正在做一些项目并最终遇到了一些问题。 So my form doesn't display itself at all in my template.所以我的表单根本不会在我的模板中显示出来。 But I've created another form before and it works as it should!但我之前创建了另一种形式,它应该可以正常工作!

So my code:所以我的代码:

models.py模型.py

class Project(models.Model):
    class Meta:
        db_table = "project"

    COLORS = (
        ('R', 'Red'),
        ('B', 'Blue'),
        ('G', 'Green'),
        ('Y', 'Yellow')
     )
    project_title = models.CharField(max_length=200)
    project_color = models.CharField(max_length=1, choices=COLORS)

    def __str__(self):
        return self.project_title

forms.py forms.py

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ['project_title', 'project_color']

views.py视图.py

def addproject(request):
    if request.POST:
        form_p = ProjectForm(request.POST)
        if form_p.is_valid():
            form_p.save(commit=False)
            return HttpResponseRedirect('/')
   else:
        form_p = ProjectForm()
    context = {
        'projects': Project.objects.all(),
        "form": form_p,
        'username': auth.get_user(request).username,
    }
    context.update(csrf(request))
    return render(request, 'index.html', context)

urls.py网址.py

urlpatterns = [
    url(r'^addproject/$', views.addproject, name='addproject'),]

index.html索引.html

<form action="/addproject/" method="post">
    {% csrf_token %}
    {{ form_p.as_table }}
    <button type="submit" class="btn btn-primary">Add Project</button>
</form>

The problem is within your template, you are calling your context variable as form_p while passing it as "form" : 问题出在模板内,您将上下文变量称为form_p,同时将其传递为“ form”

index.html index.html

<form action="/addproject/" method="post">
    {% csrf_token %}
    {{ form.as_table }}
    <button type="submit" class="btn btn-primary">Add Project</button>
</form>

Have you imported the form in to the views.py? 您是否已将表单导入到views.py中? place this in to your views.py 将此放入您的views.py

from .forms import ProjectForm

Make sure you are using "ModelForm" instead "Form"确保您使用的是“ModelForm”而不是“Form”

class NewAccountForm(forms.ModelForm):
    class Meta:
        model = NewAccount
        fields = ('name',)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM