Home > Enterprise >  In django-taggit tag is not save along with question post
In django-taggit tag is not save along with question post

Time:08-26

when I created djanog question models all the fields are created but tag is not created with question model but separately tags are created in django admin taggit

model.py

class Question(models.Model):
 id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False)
nameuser = models.ForeignKey(Profile,on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
content = RichTextUploadingField()
tag = TaggableManager()
def __str__(self):
  return self.content
class Meta:
  ordering = ['-timestamp']

view.py

def createQue(request):
User = request.user.profile
form=QuestionForm()
if request.method =='POST':
    form=QuestionForm(request.POST,request.FILES)
    if form.is_valid():
        content = form.cleaned_data["content"]
        tag = form.cleaned_data["tag"]
        print(tag)
        blog = form.save(commit=False)
        blog.nameuser=User
        blog.content = content
        blog.tag=tag
        blog.save()
 
        return redirect('home')
context={'form':form}
return render(request,'blog_form.html',context)

forms.py

class QuestionForm(forms.ModelForm):
class Meta:
    model = Question
    fields = ['content','tag']
   
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['content'].widget.attrs.update({'class':'form-control ','placeholder':'Enter your question'})
    self.fields['tag'].widget.attrs.update({'class':'tag_inputbar','placeholder':'Enter Tags here'})

CodePudding user response:

A TaggableManager is a ManyToManyField with some extra logic. You thus should save it as such, or just let the form do its work properly, so:

def createQue(request):
    form=QuestionForm()
    if request.method =='POST':
        form = QuestionForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.nameuser = request.user.profile
            form.save()
            return redirect('home')

    context={'form':form}
    return render(request, 'blog_form.html', context)

CodePudding user response:

For many2many you need to use save_m2m() along with form if you use commit=False

def createQue(request):
    User = request.user.profile
    form=QuestionForm()
    if request.method =='POST':
        form=QuestionForm(request.POST,request.FILES)
        if form.is_valid():
            content = form.cleaned_data["content"]            
            blog = form.save(commit=False)
            blog.nameuser=User
            blog.content = content
            blog.save()
            form.save_m2m()
    
            return redirect('home')
    context={'form':form}
    return render(request,'blog_form.html',context)
  • Related