0

How to use only form validation of ModelForm?

Please see my code!

models.py

from django.db import models

class IPAddr(models.Model):
    ip = models.GenericIPAddressField(unique=True,)

class myModel(models.Model):
    ip = models.ForeignKey(IPAddr)

forms.py

from django.forms import ModelForm
from django import forms
from app.models import *  # This is thing above models.py

class myModelForm(ModelForm):
    ip = forms.GenericIPAddressField()
    class Meta:
        model = myModel

I want below logic.

user input ip(to ip field) -> validation -> (form.is_valid is True) goodIP = IPAddr.objects.get_or_create(user_input_ip) -> myModel.objects.create(ip=goodIP)

But validation is always fail...

Because (for example) user input is '1.2.3.4'. As you know, '1.2.3.4' is valid IP Address.

But form.is_valid is False. Because of '1.2.3.4' is not IPAddr instance.

So I can't use logic that I want.

Let's see ModelForm document.

The first time you call is_valid() or access the errors attribute of a ModelForm triggers form validation as well as model validation.

I want validation about only form validation...

...

Do I must use Forms not ModelForm...?

While using ModelForm, can I use my logic that I want?

chobo
  • 4,830
  • 5
  • 23
  • 36

1 Answers1

0
class myModelForm(forms.ModelForm):
    ip = forms.GenericIPAddressField()

    class Meta:
        model = myModel

    def clean(self):
        cleaned_data = super(ContactForm, self).clean()
        ip = cleaned_data.get("ip")

        //do your login here

        return cleaned_data
catherine
  • 22,492
  • 12
  • 61
  • 85