I am making a dictionary, and one of the features is to detect any input that is similar in the Censorships model. The reason for that is to give a tag for vulgar words.

This is my Word model the tag is also in the same file, model.py. `class Word(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE)

# Attributes of the model
word = models.CharField(max_length=120)

# Tags for searching and label
tags = models.ManyToManyField('Tag', blank=True, related_name="word_tag")

class Tag(models.Model): name = models.CharField(max_length=50)`

My forms.py looks like this, it contains forms for both word and tag model. `class RawWordForm(forms.Form): word = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Enter a word"}))

tags = forms.ModelMultipleChoiceField(
    queryset=Tag.objects.all(),
    widget=forms.CheckboxSelectMultiple
    )

user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput)

class RawTagForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Enter a tag"}))`

Now the censorship occurs in the views.py where the word will be inputted. I made sure the word is saved first and then have the tags be set because the ModelMultipleChoiceField doesn't allow tags to be retrieved through cleaned_data. `from .forms import RawWordForm, RawTagForm from .models import Word, Tag from database.models import Censorship

def word_create(request): form = RawWordForm()

if request.method == "POST":
    form_data = {
        'word': request.POST.get('word'),
        'tags': request.POST.getlist('tags'),
        'user': request.user,
    }

    form = RawWordForm(form_data)
    if form.is_valid():        
        # Word save 
        w = Word(
            word = form.cleaned_data['word'],
            user = form.cleaned_data['user'],
        )

        w.save()
        tags = form.cleaned_data['tags'],
        w.tags.set(request.POST.getlist('tags'))
        
        wrd = w.cleaned_data['word']
        censored_words = Censorship.objects.values_list('name', flat=True)

        # Word censorship checks
        for cword in censored_words:
            if censor_word(wrd, cword):
                tag_selected = Tag.objects.get(name='Vulgar')
                form.cleaned_data['tags'].append(tag_selected)
                break
        return redirect('home')
    else:
        print(form.cleaned_data)
        print(form.errors)

context = {
    'form': form,
}
return render(request, "word/word_form.html", context)`

I tried using append to make sure the vulgar tag to the new inputs that is considered to be a vulgar word is to be selected. But all I am getting is an error that says "'QuerySet' object has no attribute 'append'"

TL;DR if the word is in censorship, then it will automatically select the vulgar tag along with what the user has selected.

0

There are 0 best solutions below