0
votes

I am making a twitter clone app in Django. I have a model, and a modelform as so:

Class Tweet(models.Model):
    content = models.TextField(blank=True, null=True)
    image = models.FileField(upload_to='images/', blank=True, null=True)

class TweetForm(forms.ModelForm):
    class Meta:
        model = Tweet
        fields = ['content',]

    def clean_content(self):
        content = self.cleaned_data.get('content')
        if len(content) > MAX_TWEET_LENGTH:
            raise forms.ValidationError('This tweet is too long')

I have a view for this:

def tweet_create_view(request, *args, **kwargs):
    if request.method == 'POST':
        form = TweetForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
    form = TweetForm()

    context = {
        'form': form
    }

    return render(request, 'components/form.html', context)

and the template:

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button class="btn btn-secondary" type="submit">Save</button>
</form>

When I submit the form data, in the database the value is shown as NULL, even if I pass in some text. What am I doing wrong??

1

1 Answers

1
votes

You are not returning the cleaned form data from the clean function, as your clean function doesn't return anything if it passes the validation, it saves None/Null to DB.

def clean_content(self):
    content = self.cleaned_data.get('content')
    if len(content) > MAX_TWEET_LENGTH:
        raise forms.ValidationError('This tweet is too long')
    return content