I have these models
class Color(models.Model):
code = models.CharField(max_length=7, unique=True)
name = models.CharField(max_length=100)
class Tshirt(models.Model):
name = models.CharField(max_length=100)
color = models.ForeignKey(Color)
And I have this form
class TshirtForm(forms.ModelForm):
color_code = forms.CharField(min_length=7, max_length=7)
class Meta:
model = Tshirt
fields = ('name',)
How can I get the Color object from the color_code field and save that as the color of the new tshirt when the modelform is saved?
If you want your users to choose a color just extend the fields
class TshirtForm(forms.ModelForm):
class Meta:
model = Tshirt
fields = ('name', 'color')
This will give you a select field in your form. Just make sure you add some colors for your users to choose from.
But if you want your users to "create" new colors, you should use two forms, one for color and the other one for the Tshirt. It's way simpler, than trying to do all in one form.
UPDATE:
Ok, update your form like this:
class TshirtForm(forms.ModelForm):
color_code = forms.CharInput()
class Meta:
model = Tshirt
fields = ('name', 'color')
widget = {'color': forms.HiddenInput(required=False)}
def clean(self, *args, **kwargs):
# If users are typing the code, better do some validation
try:
color = Color.objects.get(
code=self.cleaned_data.get('color_code')
)
except (ObjectDoesNotExist, MultipleObjectsReturned):
raise forms.ValidationError('Something went wrong with your code!')
else:
# Update the actual field
self.cleaned_data['color'] = color.id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.