djangodjango-rest-frameworktagsdjango-taggitdjango-tagging

How to save tag in django to my model using django-taggit


I dont know how to save tag to my model ,can you plz guide me to do this

This is my model

class publish(models.Model):
    Userid=models.ForeignKey(Userdata,on_delete=models.CASCADE)
    tittle=models.CharField(max_length=20)
    contend=models.TextField(max_length=20000)
    select_cat=models.CharField(max_length=30,default='Horror')
    tags=TaggableManager()
    def __str__(self):
        return self.tittle

And this is my form

class DisplayformNew(forms.ModelForm):
    CHOICES=(('Horror','Horror'),('Education','Education'),('Sports','Sports'),('Story','Story'),('Comic','Comic'))
    title=forms.CharField(label='Title',max_length=30)
    text= forms.CharField(widget=forms.Textarea(attrs={"rows":15, "cols":50}))
    sel_cat=forms.ChoiceField(choices=CHOICES,label='Select Catagoriy')
    class Meta:
        model=publish
        fields=['title','text','sel_cat','tags']

And this is my views

def add_new(request):
    form=DisplayformNew(request.POST)
    if form.is_valid():
        new_todo=publish(Userid=Userdata.objects.get(Email=request.user.email),tittle=request.POST['title'],contend=request.POST['text'],select_cat=request.POST['sel_cat'],tags=request.POST['tags'])
        new_todo.save()
        #form.save_m2m()
    context={'form':form}
    return render(request,'newpost.html',context)

I cant save Tag to my model ,can anyone help me to solve this ...... I can save it from admin view but how to save from user interface


Solution

  • In your view.py

    def add_new(request):
        form=DisplayformNew(request.POST)
        if form.is_valid():
            new_todo=publish(Userid=Userdata.objects.get(Email=request.user.email),tittle=request.POST['title'],contend=request.POST['text'],select_cat=request.POST['sel_cat'],tags=request.POST['tags'])
            new_todo.save(commit=false)
            form.save_m2m()
        context={'form':form}
        return render(request,'newpost.html',context)
    

    Change it accordingly to what I did here