F
F
Fedor_PV2018-06-24 16:10:06
Django
Fedor_PV, 2018-06-24 16:10:06

Django-taggit tags submitted via form not saved to database, why??

Django 2.0, Python 3.6.5. I connected the django-taggit library, changed everything as it should, according to Dronov's book, but as always nothing works: the tags are not saved in the database. In the documentation, I read this phrase:
If, when saving a form, you use the commit=False option you'll need to call save_m2m() on the form after you save the object, just as you would for a form with normal many to many fields on it.
Great, I did it according to the documentation, added save_m2m() to the view, anyway, the tags when sending through the form are not saved in the database. The Tags line appears in the browser, I fill it in, click "send", a new object is created, with all the characteristics, except for the tags !! For some reason, the tags are not reaching the database! Do not save in it!
Through Shell, I check the entry I just made - there are NO tags. I have already experimented with another model (in the view of which there is no commit=False code, where it is just form.save() ) - all the same, the tags are not saved in the database. ALTHOUGH if you try to create a tag through the shell through the code object.tags.add ('') - everything works, the tag appears. The system works at a deep program level. But here through the form it is impossible to create a tag.
All database migrations have been successfully done long ago.
How can I store the tags submitted via a form in the database?
Model:

from taggit.managers import TaggableManager
...
class Cities(models.Model):
country=models.ForeignKey(Countries, on_delete=models.CASCADE)
city_name=models.CharField(max_length=100)
tags = TaggableManager(blank=True, verbose_name='Теги')
class Meta:
    verbose_name_plural = 'ГОРОДА'  
def __str__(self):
    return self.city_name

from taggit.forms import TagField
...
class CitiesForm(forms.ModelForm):
    class Meta:
        model = Cities
        fields = ['city_name']
        labels = {'city_name': 'Type name of city'}
    tags=TagField(label='Tags')

def new_city(request, countries_id):
country=Countries.objects.get(id=countries_id)
if request.method != 'POST':
    form=CitiesForm()
else:
    form=CitiesForm(data=request.POST)
    if form.is_valid():
        new_city=form.save(commit=False)
        new_city.country=country
        new_city.save()
        form.save_m2m()
        return HttpResponseRedirect(reverse('countries:cities', args=[country.id]))
context={'country': country, 'form': form}
return render(request, 'countries/new_city.html', context)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fedor_PV, 2018-06-25
@Fedor_PV

So, gentlemen, after several hours of dancing with a tambourine, a solution has been found! To force the tags to be stored in the database, at the view function level, use the for loop for form.cleaned_data['tags'] and bind the tags to the object via the obj.tags.add() code. Using the example of my view function, which is shown above, the working code is like this (it may be shit code, but it WORKS, and no one could offer a better solution in a day):

@login_required
def new_city(request, countries_id):
    country=Countries.objects.get(id=countries_id)
    if request.method != 'POST':
        form=CitiesForm()
    else:
        form=CitiesForm(data=request.POST)
        if form.is_valid():
            new_city=form.save(commit=False)
            new_city.country=country
            new_city.save()
            for tag in form.cleaned_data['tags']:
                new_city.tags.add(tag)
            ....

Then we insert a similar code into the template, as Dronov taught, and everything works fine - the tags are saved in the database through the submitted form, they are perfectly displayed, separated by commas, filtered, everything is fine, gentlemen!
{% with names=city.tags.names %}
      {% if names.count > 0 %}
         Tags: {% for name in names %}{% if not forloop.first %}, {% endif %} <a href="...?tag=..."> {{ name }} </a> {% endfor %}
      {% endif %}
    {% endwith %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question