Django表单不保存外键

时间:2014-07-08 19:10:35

标签: python django methods save modelform

我正在尝试做一个简单的评论应用程序,该应用程序由标题和该标题下的评论组成。我可以创建标题,我可以看到用于向此标题添加评论条目的表单。我输入并点击提交,它什么也没做。当我使用管理面板时,我可以毫无问题地添加条目。

这是我的模特:

class Baslik(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(max_length=50)
    slug = models.SlugField()
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)

    def __unicode__(self):
        return str(self.title)


    def get_absolute_url(self, ):
        return reverse('baslik', args=[self.slug])


class Entry(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    baslik = models.ForeignKey(Baslik, null=True, blank=True)
    icerik = models.TextField(max_length=50000)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return str(self.icerik)

这是我的观点'入口部分:

def tek(request, slug):
    baslik = Baslik.objects.get(slug=slug)
    entryler = baslik.entry_set.all()
    form2 = EntryForm(request.POST or None)
    if form2.is_valid():
        entry = form2.save(commit=False)
        entry.user = request.user
        entry.save()
        return HttpResponseRedirect('/baslik/%s'%(baslik.slug))


    return render_to_response("baslik/tek.html", locals(), context_instance=RequestContext(request))

这是我的forms.py:

class BaslikForm(ModelForm):
    class Meta:
        model = Baslik
        fields = ('title',)

class EntryForm(ModelForm):
    class Meta:
        model = Entry
        fields = ('icerik',)

这是我的admin.py:

class EntryInline(admin.TabularInline):
    model = Entry


class BaslikAdmin(admin.ModelAdmin):
    list_display = ('__unicode__','live_link')
    search_fields = ['title']
    list_filter = ['timestamp', 'updated']
    prepopulated_fields = {"slug": ('title',)}

    readonly_fields = ['live_link', 'timestamp', 'updated']
    inlines = [EntryInline]
    class Meta:
        model = Baslik


    def live_link(self,obj):
        link = "<a href='/baslik/" + str(obj.slug)+ "/'>" + obj.title + "<a/>"
        return link

    live_link.allow_tags = True

admin.site.register(Baslik, BaslikAdmin)

我该怎么做才能解决这个问题?请解释一下。我是Django的新手。 感谢。

0 个答案:

没有答案