简体   繁体   中英

Django how to change forms or views.py?

i create simple page where i can add article (title, text and category). When i do it on 'site administration everything is ok', but when i add it on page i can't choose category.

http://i.stack.imgur.com/4Nxzb.jpg

I choose category, for example like on this screen but my article do not have this category after i save it (article is uncategorized).

I created forms.py file and i done it like this:

class PostForm(forms.ModelForm):

class Meta:
    model = Post
    fields = ('title', 'text', 'categories')

How must i change 'categories' here to make it usable?

models.py:

from django.db import models
from django.utils import timezone

class Category(models.Model):
    name = models.CharField('Nazwa Kategorii', max_length=100)
    slug = models.SlugField('Odnośnik', max_length=100)
    icon = models.ImageField('Ikonka Kategorii', upload_to='icons',
                              blank=True)

    class Meta:
        verbose_name = "Kategoria"
        verbose_name_plural = "Kategorie"

    def __unicode__(self):
        return self.name

class Post(models.Model):
    author = models.CharField(max_length=25, blank=True, null=True)
    title = models.CharField(max_length=200)
    slug = models.SlugField('Odnośnik', max_length=255)
    text = models.TextField()
    published_date = models.DateTimeField(
            default=timezone.now)
    categories = models.ManyToManyField(Category, verbose_name='Kategorie')

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __unicode__(self):
        return self.title

And from views.py my view

def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('blog.views.post_detail', pk=post.pk)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

When you save a form using commit=False you should call the save_m2m() method of the form:

post = form.save(commit=False)
post.author = request.user
post.save()
form.save_m2m()

Another, more elegant, solution is to pass the instance with preset field to the form's constructor. Is this case you don't need to use the commit=False argument:

form = PostForm(request.POST, instance=Post(author=request.user))
if form.is_valid():
    post = form.save()
    return redirect('blog.views.post_detail', pk=post.pk)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM