Last active
December 16, 2015 03:49
-
-
Save allieus/5372702 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
from .models import IPAddr, SomeModel | |
class SomeForm(forms.ModelForm): | |
ip = forms.IPAddressField() | |
def save(self, commit=True): | |
ip = self.cleaned_data['ip'] | |
ip_addr, is_created = IPAddr.objects.get_or_create(ip=ip) | |
instance = super(SomeForm, self).save(commit=False) | |
instance.ip_addr = ip_addr | |
if commit: | |
instance.save() | |
return instance | |
class Meta: | |
model = SomeModel | |
fields = ('ip',) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from testapp.forms import SomeForm | |
from testapp.models import SomeModel | |
form = SomeForm({'ip':'1.2.3.4'}) | |
if form.is_valid(): | |
form.save() | |
else: | |
print form.errors |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class IPAddr(models.Model): | |
ip = models.CharField(max_length=15) | |
class SomeModel(models.Model): | |
ip_addr = models.ForeignKey(IPAddr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment