在我的表单添加后,数据未在Django管理员中显示

时间:2017-09-01 10:35:11

标签: django python-3.x django-models django-forms django-admin

我是Django的初学者。 我想创建一个允许用户将数据存储到数据库的表单,但我遇到了一个问题。

如果我通过Django admin添加数据,数据将正确显示。但是,如果我通过我的表单添加数据。数据将成功存储到数据库中,但它们不会显示在我的Django管理员中。

注意:我使用的Django版本是1.11.2

The is my Django admin page. There are 8 data in the database but just show the one I added by the Django admin.

views.py

from django.shortcuts import render
from django.views.generic import CreateView

from .forms import ApplyFormCreateForm
from .models import ApplyForm

class ApplyFormCreateView(CreateView):
    form_class = ApplyFormCreateForm
    template_name = 'form.html'
    success_url = "/"

models.py

from django.db import models
from course.models import Semester

DEFAULT_SEMESTER_ID = 1 

class ApplyForm(models.Model):
    name          = models.CharField(max_length=15)
    school        = models.CharField(max_length=20)
    department    = models.CharField(max_length=20)
    email         = models.EmailField(max_length=100)
    is_beginner   = models.BooleanField(default=False)
    introduction  = models.TextField(max_length=2000)
    motivation    = models.TextField(max_length=2000)
    comments      = models.TextField(max_length=2000, blank=True)
    semester      = models.ForeignKey(Semester, default=DEFAULT_SEMESTER_ID)
    created_at    = models.DateTimeField(auto_now_add=True)
    update_at     = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.school + self.department + self.name

    def __str__(self):
        return self.school + self.department + self.name

form.html

{% extends "base.html" %}
{% block content %}
<form method='POST'> {% csrf_token %}
    {{form.as_p}}
    <button type='submit'>Save</button>
</form>
{% endblock content %}

form.py

from django import forms
from .models import ApplyForm

class ApplyFormCreateForm(forms.ModelForm):
    class Meta:
        model = ApplyForm
        fields = [
            'name',
            'school',
            'department',
            'email',
            'is_beginner',
            'introduction',
            'motivation',
            'comments',
        ]

url.py

from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

from myweb.views import HomeView
from course.views import CourseListView
from applyform.views import ApplyFormCreateView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomeView.as_view(), name='home'),
    url(r'^course/$', CourseListView.as_view(), name='course'),
    url(r'^apply/$', ApplyFormCreateView.as_view(), name='applyform'),
]

0 个答案:

没有答案