0

[app].models.py:

from django.db import models
from .custom_fields import HTTPURLField
from .function_validators import validate_md5


class Snapshot(models.Model):
    url = HTTPURLField(max_length=1999)
    content_hash = models.CharField(max_length=32, default='00000000000000000000000000000000',
                                    validators=[validate_md5])
    timestamp = models.DateTimeField(auto_now=True)

[app].forms.py:

from django import forms
from .models import Snapshot


class SnapshotModelForm(forms.ModelForm):
    class Meta:
        model = Snapshot
        fields = ('url', 'content_hash')

[app].views.py:

from .forms import SnapshotModelForm


def index(request):
    snapshot_form = SnapshotModelForm(data={'url': ' https://stackoverflow.com/ '}) # notice the spaces (which gets trimmed automatically during cleaning or where?)

    if snapshot_form.is_valid():
        model_instance = snapshot_form.save()

I want my SnapshotModelForm instance (snapshot_form) to be populated also with a 'content_hash' and its default value (given in Snapshot class definition's django.db.models.fields.CharField), when not fed via POST data or other kind (input) data used by ModelForm's constructor, i.e. avoid having to feed it somehow to the constructor. How can I achieve that?

In the code above is_valid() returns False, because the field 'content_hash' doesn't validate, most likely because it's not present.

I guess the class django.forms.fields.Field or its sub-classes (in this case django.forms.fields.CharField) might be involved in this matter!?

Please note the difference between django.forms.fields.CharField and django.db.models.fields.CharField.

I'm pretty convinced that I should use forms (ModelForm) to benefit from automatic validation and other stuff (e.g. white-space trimming).

chakmeshma
  • 246
  • 8
  • 27
  • What's an `HTTPURLField`? Please see how to write a [mre], one should be able to reproduce your problem without changing the code you share. Also "_notice the spaces (which gets trimmed automatically during cleaning or where?)_" I don't really think that actually happens... – Abdul Aziz Barkat Sep 21 '22 at 12:10

0 Answers0