如何在django中写一个表单 [英] How do I write a form in django

查看:71
本文介绍了如何在django中写一个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的最后一个项目写一个论坛应用程序,我正在尝试编写一个创建新线程的表单,基本上我需要做的是



用户名:文本框这里



线程名称:文本框这里



发布: / p>

我想在forms.py中执行此操作,而不是为其创建模板。

 code> url(r^(。+)/ new_thread / $,new_thread,name =thread_new_thread),

这是我的url线程

  def list_threads(request,forum_slug):
在一个论坛上列出线程
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(论坛)

class Meta:
unique_together = 'slug','forum',)

def save(self,* args,** kwargs):
self.slug = slugify(self.title)
super线程,自身).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_repl ies(self):
return self.post_set.count() - 1

def last_post(self):
如果self.post_set.count():
return self.post_set.order_by(created)[0]

这是我的线程模型

任何建议?

解决方案

阅读文档:



https://docs.djangoproject。 com / en / dev / topics / forms / modelforms /



我猜线程有一个模型。



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b $ (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' ,'创建者','论坛')

在您的意见中:

  def thread_add(self,forum_id):
data = None
如果request.method =='POST':
数据= request.POST
forum = Forum.objects.get(id = form_id)
form = ThreadForm(forum = forum,user = request.user,data = data)
如果form.is_valid ():
form.save()
.............
返回render_to_response .....

在您的模型中,留下一个字段以发布:文本框在这里


I am writing a forums app for my final project in class and I am trying to write a form for creating a new thread, Basically all I need it to do is

username: text box here

Name of thread: Text box here

Post: text box here

I want to do this in forms.py instead of making a template for it.

url(r"^(.+)/new_thread/$", new_thread, name="thread_new_thread"),

That's my url 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))

That is my list_threads view, I have a button that should link to the forms.py version of my new thread post

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]

This is my thread model

Any suggestions?

解决方案

Read the documentation:

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

I guess that the Thread has a model.

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') 

In your views:

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

In your model left a field to "Post: text box here"

这篇关于如何在django中写一个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆