我正在为我在课堂上的最后一个项目编写一个论坛应用程序,我正在尝试编写一个用于创建新线程的表单,基本上我需要它做的就是
用户名:此处为文本框
线程名称:此处的文本框
发布:此处的文本框
我想在forms.py中执行此操作,而不是为其创建模板。
url(r"^(.+)/new_thread/$", new_thread, name="thread_new_thread"),
这是我的网址
def list_threads(request, forum_slug):
"""Listing of threads in a forum."""
threads = Thread.objects.filter(forum__slug=forum_slug).order_by("-created")
threads = mk_paginator(request, threads, 20)
template_data = {'threads': threads, 'forum_slug': forum_slug}
return render_to_response("forum/list_threads.html", template_data, context_instance=RequestContext(request))
这是我的list_threads视图,我有一个按钮,应该链接到我新帖子的forms.py版本
class Thread(models.Model):
title = models.CharField(max_length=60)
slug = models.SlugField(max_length=60)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
forum = models.ForeignKey(Forum)
class Meta:
unique_together = ('slug', 'forum', )
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Thread, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('forum_list_posts', args=[self.forum.slug, self.slug])
def __unicode__(self):
return unicode(self.creator) + " - " + self.title
def num_posts(self):
return self.post_set.count()
def num_replies(self):
return self.post_set.count() - 1
def last_post(self):
if self.post_set.count():
return self.post_set.order_by("created")[0]
这是我的主题模型
有什么建议吗?
答案 0 :(得分:1)
阅读文档:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
我猜线程有一个模型。
class ThreadForm(ModelForm):
def __init__(self, forum, user, *args, **kwargs):
super(ThreadForm, self).__init__(*args, **kwargs)
self.forum = forum
self.user = user
def save(self):
thread = super(ThreadForm, self).save(commit=False)
thread.forum = self.forum
thread.creator = self.user
thread.save()
return thread
class Meta:
model = Thread
exclude = ('slug', 'created', 'creator', 'forum')
在您的观点中:
def thread_add(self, forum_id):
data = None
if request.method == 'POST':
data = request.POST
forum = Forum.objects.get(id=form_id)
form = ThreadForm(forum=forum, user=request.user, data=data)
if form.is_valid():
form.save()
.............
return render_to_response .....
在你的模型中,将一个字段留给“Post:text box here”