[Answered ]-Tags will not store in database in django

0👍

Use model form

In html use id of forms like this

HTML

<form action="{% url 'addquery' %}" method="post">
{% csrf_token %}
<div class="psrelative">
<input id="id_question" name="question" type="text" maxlength="300" tabindex="100" placeholder="e.g. Is there an R function for finding the index of an element in a vector?" class="s-input js-post-title-field" value="" data-min-length="15" data-max-length="150" autocomplete="off" required>
</div>
<textarea name="que_body" id="id_que_body" class="textarea-body"></textarea required>
<div class="psrelative">
<input id="id_tags" name="tags" type="text" maxlength="300" tabindex="100"
placeholder="e.g. (ruby-on-rails vba spring)" class="s-input js-post-title-field" value="" data-min-length="15" data-max-length="150" autocomplete="off" required>
</div>
<button class="review-question-btn" type="submit" tabindex="120"> Submit your question
</button>
</form>

Forms.py

from django import forms
from .models import Question

class Addqueform(forms.ModelForm):
    class Meta:
        model = Question
        fields = ['question','que_body','tags']

Views.py

from .forms import Addqueform

def addque(request):
    queform = Addqueform(request.POST)
    if request.method == "POST":
        user = request.user
        if user.is_anonymous:
            return redirect('addquery')

        if user.is_active:
            if queform.is_valid():
                aquuid = request.user.aquuid
                question = queform.cleaned_data['question']
                body = queform.cleaned_data['que_body']
                tags = queform.cleaned_data['tags']
                addquery = Question(question=question, user_id=aquuid, que_body=body)
                for tag in tags:
                    addquery.tags.add(tag)
                addquery.save()
                return redirect('addquery')
            else:
                queform = Addqueform()
                return render(request, 'question/ask.html', {'form': queform})
    else:
        return render(request, 'question/ask.html', {'form': queform})

I think It will Work

1👍

Tags are Many-to-Many objects and you can’t add those to an object until the object has been saved. The documentation shows that you need to use .add() to add tags to a model instance. Your code should be:

    addquery = Question(question=question, user_id=aquuid, que_body=body)
    addquery.save()
    addquery.tags.add(tags)

As an aside, you might be better served by a ModelForm which can handle the tags and all of this stuff that you’re doing:

    question = request.POST['question']
    body = request.POST['body']
    tags = request.POST['tags']

https://django-taggit.readthedocs.io/en/latest/forms.html

👤0sVoid

Leave a comment