How do I write a form in django

2024/10/5 15:15:14

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.titledef num_posts(self):return self.post_set.count()def num_replies(self):return self.post_set.count() - 1def last_post(self):if self.post_set.count():return self.post_set.order_by("created")[0]

This is my thread model

Any suggestions?

Answer

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 = forumself.user = userdef save(self):thread = super(ThreadForm, self).save(commit=False)thread.forum = self.forumthread.creator = self.userthread.save()return threadclass Meta:model = Threadexclude = ('slug', 'created', 'creator', 'forum') 

In your views:

def thread_add(self, forum_id):data = Noneif request.method == 'POST':data = request.POSTforum = 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"

https://en.xdnf.cn/q/119199.html

Related Q&A

Whats the difference between namespaces and names?

Im assuming the namespace is the allotted place in memory in which the name is to be stored. Or are they the same thing?

Finding a string in python and writing it in another file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.Improv…

Python error TypeError: function takes exactly 1 argument (5 given)

Traceback (most recent call last):File "wdd.py", line 164, in <module>file.write("temperature is ", temperature, "wet is ", humidity, "%\n") TypeError: fun…

Django session not available on two seperate requests

Description: In the django session docs it says:You can read it and write to request.session at any point in your view.But I cant access the session when making a second request to the same view: views…

Counting how many times there are blank lists in a list of list [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Generating a list of random permutations of another list

So, Im trying to tackle the TSP with a Genetic Algorithm. To do that I need to create a population pool. What I want to accomplish is to create a list of random permutations that will represent a popul…

How to hide location of image in django?

models.py class UserInfo(models.Model):UID = models.CharField(max_length=50, primary_key=True, default=datetime.now().strftime("%d%y%H%S%m%M")) # default=fullname = models.CharField(max_leng…

Extracting data from multiple files with python

Im trying to extract data from a directory with 12 .txt files. Each file contains 3 columns of data (X,Y,Z) that i want to extract. I want to collect all the data in one df(InforDF), but so far i only …

Python: Checking if string follows wikipedia link format

If I have a string named link, how would I go about checking to see if it follows the same format as a wikipedia URL? To clarify, wikipedia URLs (in this case) always begin with en.wikipedia.org/wiki/…

Create dictionary comprehension from list with condition syntax

Id like to create a dictionary using dictionary comprehension syntax.Note that list l contains tuples of strings and tuples with 1st element always a time stamp.This works:d = {} for entry in l:if entr…