Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django sets a default value to model input

When I load the page, the value of the input is automaticly this:
Issue Screenshot

How is that possible?

views file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    if request.method == 'POST':
        form = FieldForm(request.POST, instance=Field(user=request.user))
        if form.is_valid():
            obj = form.save(commit=False)
            obj.creator_adress = get_client_ip(request)
            obj.save()
            return redirect('/dashboard')
    else:
        form = FieldForm(instance=Field)
    
    ......

forms file

class FieldForm(forms.ModelForm):
    class Meta:
        model = Field

        fields = (
            'title',
            'url'
        )

models file

class Field(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        default=None,
        null=True,
        on_delete=models.CASCADE,
    )
    title = models.CharField(max_length=255)
    url = models.CharField(max_length=255)
    creator_adress = models.GenericIPAddressField(null=True)

    def __str__(self):
        return str(self.user)

Here one input 😂
value= <django.db.models.query_utils.DeferredAttribute object at 0x000001E180304250>

>Solution :

In your view you are passing a reference to your Field model as the argument instance. Doing this places the representation of the model fields into your form fields when it is rendered. If what you are wanting is just a blank form when you load the page then just remove the instance argument and create your form in your else statment, like form = FieldForm(). The instance argument is only needed for a form if you are trying to pre-populate data into the form, for example if you made a view where you wanted to update information on an already created object you would pass an instance of your model to the instance argument.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading