Manually Set Model Fields In Modelform
I have a model with a foreign key and a unique constraint as follows: class Menu(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) name =
Solution 1:
You should simply instantiate the form with an unsaved instance of Menu
so your view should be like:
defadd_menu(request, tournament_slug):
tournament = get_object_or_404(Tournament, slug=tournament_slug)
if request.method == 'POST':
form = MenuForm(request.POST, instance=Menu(tournament=tournament))
if form.is_valid():
menu_id = form.save()
return HttpResponseRedirect(reverse('admin'))
else:
form = MenuForm(instance=Menu(tournament=tournament))
return render(request, "view.html", {'form': form, "tournament": tournament})
Also the form calls _get_validation_exclusions()
and excludes fields not present in the form from validation. You can try to override validate_unique
to overcome this:
classMenuForm(forms.ModelForm):
date_menu = forms.DateField(initial=datetime.datetime.now())
classMeta:
model = Menu
exclude = ['tournament']
defvalidate_unique(self):
exclude = self._get_validation_exclusions()
if'tournament'in exclude:
exclude.remove('tournament') # Make sure `tournament` gets validatedtry:
self.instance.validate_unique(exclude=exclude)
except ValidationError as e:
self._update_errors(e)
Note: I changed your view structure to avoid using
MenuForm(request.POST or None)
which is an antipattern. (Forms can be valid even if nothing is sent in the POST data, with the way you write such forms would be considered invalid).
Edit: As discussed in the comments perhaps the option of a hidden and disabled field is much better than overriding the forms validate_unique
method:
classMenuForm(forms.ModelForm):
tournament = forms.ModelChoiceField(
queryset=Tournament.objects.all(),
widget=forms.HiddenInput(),
disabled=True
)
date_menu = forms.DateField(initial=datetime.datetime.now())
classMeta:
model = Menu
fields = ['tournament', 'name', 'date_menu']
Post a Comment for "Manually Set Model Fields In Modelform"