Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - How do I write a form in django

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...