O
O
Ozrae2020-06-05 11:41:15
Django
Ozrae, 2020-06-05 11:41:15

Adding a tag to a post through the form does not work, only through the admin panel, how to fix it?

models.py:

from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    thumb = models.ImageField(default='default-3.jpg', blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    tags = models.ManyToManyField('Tag', blank=True)    #поле с тегом, привязано к классу Tag

    def __str__(self):
        return self.title

    def snippet(self):
        return self.body[:50] + '...'

class Tag(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    
    def __str__(self):
        return self.title


forms.py:
from django import forms
from . import models

class CreateArticle(forms.ModelForm):
    class Meta:
        model = models.Article
        fields = ['title', 'body', 'slug', 'tags', 'thumb']

    widgets = {
        'title': forms.TextInput(attrs={'class': 'form-control'}),
        'slug': forms.TextInput(attrs={'class': 'form-control'}),
        'body': forms.Textarea(attrs={'class': 'form-control'}),
        'tags': forms.SelectMultiple(attrs={'class':'forms-control'})
    }


view.py:
@login_required(login_url='/accounts/login/')
def article_create(request):
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('article:list')
    else:
        form = forms.CreateArticle
    return render(request, 'app/article_create.html', {'form': form})


html:
{% block content %}
<div class='login-container'>
<div class='login-border'>
    <div>
        <h2>Create New Article</h2>
        <form class='site-create' action="{% url 'article:create' %}" method='post' enctype='multipart/form-data'>
            {% csrf_token %}
            {{ form }}
            <input class='login-button' type="submit" value='Create'>
        </form>
    </div>
    <script src='/static/slugify.js'></script>
</div>
</div>
{% endblock %}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-06-11
@Ozrae

Saving the form occurs without regard to related objects. You need to manually implement saving tags
Something like this, I can’t exactly know what cleaned_data['tags'] returns, if Tag returns then this, if just id returns, then you need to iterate over cleaned_data['tags'] and get Tag yourself.

if form.is_valid():
    instance.tags.set(form.cleaned_data['tags'])

There is a special template tag for this{{ article.body|truncatewords:50 }}
def snippet(self):
    return self.body[:50] + '...'

D
Dr. Bacon, 2020-06-05
@bacon

https://docs.djangoproject.com/en/3.0/topics/forms...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question