Django表单没有出现

时间:2017-10-08 17:25:35

标签: python html django forms post

我正在开展一些项目并最终遇到了一些问题。 所以我的表单在我的模板中根本不显示。 但是之前我已经创建了另一个表单,它可以正常工作!

所以我的代码:

models.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

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

views.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

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

的index.html

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

2 个答案:

答案 0 :(得分:3)

问题出在您的模板中,您将上下文变量称为 form_p ,同时将其作为“form”传递:

<强>的index.html

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

答案 1 :(得分:0)

您是否已将表单导入到views.py中? 将其放入您的views.py

from .forms import ProjectForm