Form not saving to database "through" intermediate tables - django

I have a custom form that is not saving to the database. I do not get any errors but the values do not save to the database. Any ideas?
views.py
def diseasestateoption(request, disease_id, state_id):
state = get_object_or_404(State, pk=state_id)
disease = get_object_or_404(Disease, pk=disease_id)
if request.method == "POST":
form = UpdateStateWithOptionsForm(request.POST, instance=state)
if form.is_valid():
for option_id in request.POST.getlist('options'):
state_option = StateOption.objects.create(partstate=state, partoption_id=int(option_id))
state_option.save()
return HttpResponseRedirect(reverse('success'))
else:
form = UpdateStateWithOptionsForm(instance=state)
models.py
class Option(models.Model):
relevantdisease = models.ForeignKey(Disease)
option = models.CharField(max_length=300)
class State(models.Model):
state = models.CharField(max_length=300, verbose_name='state')
relevantdisease = models.ForeignKey(Disease, verbose_name="disease")
relevantoption = models.ManyToManyField(Option, through='StateOption')
class StateOption(models.Model):
parttstate = models.ForeignKey(State)
partoption = models.ForeignKey(Option)
forms.py
class UpdateStateWithOptionsForm(forms.ModelForm):
class Meta:
model = State
exclude = ['state', 'relevantdisease']
def __init__(self, *args, **kwargs):
super(UpdateStateWithOptionsForm, self).__init__(*args, **kwargs)
self.fields['relevantoption']=forms.ModelMultipleChoiceField(queryset=Option.objects.all(),required=True, widget=forms.CheckboxSelectMultiple)

I think Problem is with getting option from POST, use-
request.POST.getlist('relevantoption')
in stead of
request.POST.getlist('options')
apart, why to use form here for single multiple choice field, even where you are modifying choices also and not using form.save too.

Related

Django - forms trying to clean unique together, CrispyError

I have a model with a unique together and I want to validate this condition in my modelform. The unique together includes a field that is passed to the form in an init method, the user, and a field that is in the form. I'm having problems with validating a unique together condition.
EDIT
I have modified the code to what you see below
model:
class Objective(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
objective_name = models.CharField(max_length=10)
description = models.CharField(max_length=300)
mode = models.CharField(max_length=2, default='LA')
class Meta:
unique_together = ['user', 'objective_name', 'course']
ordering = ['objective_name']
def __str__(self):
return self.objective_name
The view:
def addobjective(request, course_id):
this_course = get_object_or_404(Course, pk=course_id)
user = request.user
all_courses = Course.objects.filter(user=user)
objective_list = Objective.objects.filter(
course=this_course).order_by('objective_name')
context = {'objective_list': objective_list}
if request.method == 'POST':
form = ObjectiveForm(user, request.POST, my_course=this_course)
if form.is_valid():
obj = form.save(commit=False)
obj.course = this_course
obj.user = user
obj.save()
form = ObjectiveForm(user, my_course=this_course)
context['form'] = form
return redirect('gradebook:addobjective', course_id=this_course.id)
else:
form = ObjectiveForm(user, my_course=this_course)
context['form'] = form
context['this_course'] = this_course
context['all_courses'] = all_courses
return render(request, 'gradebook/objective-form.html', context)
forms.py:
class ObjectiveForm(ModelForm):
def __init__(self, user, *args, **kwargs):
self.request = kwargs.pop('request', None)
my_course = kwargs.pop('my_course')
self.objs = Objective.objects.filter(user=user, course=my_course)
super(ObjectiveForm, self).__init__(*args, **kwargs)
class Meta:
model = Objective
fields = ('objective_name', 'description', 'mode',)
def clean(self):
super(ObjectiveForm, self).clean()
objective_name = self.cleaned_data.get("objective_name")
description = self.cleaned_data.get("description")
mode = self.cleaned_data.get("mode")
if self.objs.filter(objective_name=objective_name).count() > 0:
print("error")
del self.cleaned_data["objective_name"]
del self.cleaned_data["description"]
del self.cleaned_data["mode"]
raise ValidationError(
"This course already has a learning objective with this name.")
return self.cleaned_data
EDIT
The error I know get is |as_crispy_field got passed an invalid or inexistent field. This occurs when I enter in a value for objective_name that is a duplicate. error is printed to the console and then I get the above error. I do not get the ValidationError.
The full traceback can be seen here.
Maybe with the form I do not need the unique together constraint in the model?
Yes, my_course field is not defined in Objective model , so maybe you need to change this line:
form = ObjectiveForm(request.POST, my_course=this_course)
To
form = ObjectiveForm(request.POST, course=this_course)
It turns out that the problem was caused by improper indentation of return redirect('gradebook:addobjective', course_id=this_course.id) after the if form.is_valid():. The return redirect has to be a part of the POST request.

filtering relational models inside django forms

i have a model which has a foreign key relation with two oder models one of them is 'level'.
the view knows in which level you are based on a session variable,
and then filter the lessons
this is the lesson model:
class Lesson(models.Model):
level = models.ForeignKey(Level,on_delete=models.CASCADE)
subject = models.ForeignKey(Subject,on_delete=models.CASCADE)
chapiter = models.CharField(max_length=200)
lesson = models.CharField(max_length=200)
skill = models.CharField(max_length=200)
vacations = models.IntegerField()
link = models.URLField(max_length=700,null=True,blank=True)
remarques = models.TextField(null=True,blank=True)
order = models.IntegerField()
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now=True)
state = models.BooleanField(default=False)
now this is my cbv to create a new lesson:
class GlobalLessonView(CreateView):
model = Lesson
form_class = GlobalLessonForm
success_url = reverse_lazy('globalform')
and this is the form:
class GlobalLessonForm(forms.ModelForm):
class Meta:
model = Lesson
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects
if 'level' in self.data:
try:
level_id = int(self.data.get('level'))
self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')'])
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['subject'].queryset = self.instance.level.subject_set
one of the main conditions is to filter level by a session variable
but the form does not accept request.session
so is there any way to change the levels that shows up at the form from the class based view,or there any way to pass request.session to form.py
Add this to GlobalLessonView:
def get_form_kwargs(self):
"""Pass request to form."""
kwargs = super().get_form_kwargs()
kwargs.update(request=self.request)
return kwargs
Then change the constructor definition in GlobalLessonForm to:
def __init__(self, request, *args, **kwargs):
Then you will be able to reference request.session in GlobalLessonForm.

Instantiate a modelForms MultiSelectCheckBox widget

I am using ModelForms with a ModelMultipleChoiceField widget. I have 2 questions:
My checkbox widget for Treatment Options from SelectOptionForStateForm renders existing selections from the stateoption table in my database. How does it know to look in that table for existing records? In my views.py I am only passing the disease and state objects which do not look at the stateoption table.
How do I instantiate my SelectOutcomeForOptionForm so that my Treatment Outcomes checkbox is also pre-selected from the stateoptionoutcome table in my database?
forms.py
class SelectOptionForStateForm(forms.ModelForm):
class Meta:
model = State
exclude = ['state', 'relevantdisease']
def __init__(self, *args, **kwargs):
disease=kwargs.pop('disease', None)
super(SelectOptionForStateForm, self).__init__(*args, **kwargs)
self.fields['relevantoption']=forms.ModelMultipleChoiceField(queryset=Option.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
self.fields['relevantoption'].label="Treatment Options"
class SelectOutcomeForOptionForm(forms.ModelForm):
class Meta:
model = StateOption
exclude = ['partstate', 'partoption']
def __init__(self, *args, **kwargs):
disease=kwargs.pop('disease', None)
super(SelectOutcomeForOptionForm, self).__init__(*args, **kwargs)
self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
self.fields['relevantoutcome'].label="Treatment Outcomes"
views.py
def stateoptionoutcome(request, disease_id, state_id):
state = get_object_or_404(State, pk=state_id)
disease = get_object_or_404(Disease, pk=disease_id)
if request.method == "POST":
optionForm = SelectOptionForStateForm(request.POST, disease=disease, instance=state)
outcomeForm = SelectOutcomeForOptionForm(request.POST, disease=disease, instance=state)
if optionForm.is_valid() and outcomeForm.is_valid():
#Deletes state objects so there are no duplicate options in the database
try:
state_option = StateOption.objects.filter(partstate=state).delete()
except StateOption.DoesNotExist:
state_option = None
#Saves user options to database
for option_id in request.POST.getlist('relevantoption'):
state_option = StateOption.objects.create(partstate=state, partoption_id=int(option_id))
#Deletes stateoption objects found in StateOptionOutcome
try:
state_option_outcome = StateOptionOutcome.objects.filter(stateoption=state_option).delete()
except StateOptionOutcome.DoesNotExist:
state_option_outcome = None
#Saves user outcomes to database
for outcome_id in request.POST.getlist('relevantoutcome'):
state_option_outcome = StateOptionOutcome.objects.create(stateoption=state_option, relevantoutcome_id=int(outcome_id))
return HttpResponseRedirect(reverse('diseasestateoptionlist', kwargs={'disease_id':disease_id, 'state_id':state_id}))
models.py
class State(models.Model):
state = models.CharField(max_length=255)
relevantdisease = models.ForeignKey(Disease)
relevantoption = models.ManyToManyField(Option, through='StateOption')
class StateOption(models.Model):
partstate = models.ForeignKey(State)
partoption = models.ForeignKey(Option)
relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')
class StateOptionOutcome(models.Model):
stateoption = models.ForeignKey(StateOption)
relevantoutcome = models.ForeignKey(Outcome)
outcomevalue = models.CharField(max_length=20)
I was able to solve #2 using this:
stateoptionlist = StateOption.objects.filter(partstate_id=state_id)
if not stateoptionlist:
stateoption = state
else:
stateoption = stateoptionlist[0]
I pass the state instance if the stateoptionlist returns an empty list (ie, there are no records in the StateOption table). Updating the views.py, for every SelectOutcomeForOptionForm, my instance is replaced with stateoption.
I'm interested to see if there's a more efficient way of solving #2.

Validating Unique Fields in Django

I don't know if I'm approaching the problem in the right way. The intended outcome is to have a form that displays only name and description. Once the user submits the form I want to add the current user as owner and check if there's already an entry that has the same name and user. If there is, I want to return the form with errors. If not, I want to save Status.
My model:
class Status(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
owner = models.ForeignKey(User)
active = models.BooleanField(default=True)
class Meta:
unique_together = ('name','owner')
My View:
def settings_status(request):
status_form = StatusForm()
if request.method == 'POST':
status_form = StatusForm(request.POST)
if status_form.is_valid():
new_status = Status()
new_status.name = status_form.cleaned_data['name']
new_status.description = status_form.cleaned_data['description']
new_status.owner = request.user
new_status.save()
return render_to_response('base/settings_status.html',{
'status_form' : status_form,
}, context_instance=RequestContext(request))
I have tried numerous things, but I keep running into the problem that if I add owner to the object separately then it isn't available to the model's clean function and therefore can't be used to check if name and owner are unique.
Several ways to do this:
for example, passing in the user (owner) to the form:
forms.py:
class StatusForm(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user','')
super(StatusForm, self).__init__(*args, **kwargs)
self.fields['name'] = forms.CharField(label='Name')
self.fields['description'] = CharField(label='Description', widget=forms.Textarea)
def clean(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get('name')
if Status.objects.filter(name=name, owner=self.user).exists():
self._errors['name'] self.error_class(['Status with this name exists'])
return cleaned_data
views.py:
def settings_status(request):
if request.method == 'POST':
status_form = StatusForm(request.POST, user=request.user)
if status_form.is_valid():
new_status = Status()
new_status.name = status_form.cleaned_data['name']
new_status.description = status_form.cleaned_data['description']
new_status.owner = request.user
new_status.save()
else:
status_form = StatusForm(user=request.user)
context = {'status_form':status_form,}
return render_to_response('base/settings_status.html', context,
context_instance=RequestContext(request))
Also look at setting initial data depending on your form setup and consider using a ModelForm.

Django how to save a custom formset

I've written the following custom formset, but for the life of me I don't know how to save the form. I've searched the Django docs and done extensive searches, but no one solution works. Lots of rabbit holes, but no meat ;-) Can someone point me in the right direction?
// views.py partial //
#login_required
def add_stats(request, group_slug, team_id, game_id, template_name = 'games/stats_add_form.html'):
if request.POST:
formset = AddStatsFormSet(group_slug=group_slug, team_id=team_id, game_id=game_id, data=request.POST)
if formset.is_valid():
formset.save()
return HttpResponseRedirect(reverse('games_game_list'))
else:
formset = TeamStatFormSet(group_slug=group_slug, team_id=team_id, game_id=game_id)
return render_to_response(template_name, {'formset': formset,})
// modles.py partial //
class PlayerStat(models.Model):
game = models.ForeignKey(Game, verbose_name=_(u'sport event'),)
player = models.ForeignKey(Player, verbose_name=_(u'player'),)
stat = models.ForeignKey(Stat, verbose_name=_(u'statistic'),)
total = models.CharField(_(u'total'), max_length=25, blank=True, null=True)
class Meta:
verbose_name = _('player stat')
verbose_name_plural = _('player stats')
db_table = 'dfusion_playerstats'
def __unicode__(self):
return u'%s' % self.player
// forms.py
class TeamStatForm(forms.Form):
total = forms.IntegerField()
class BaseTeamStatsFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
self.group_slug = kwargs['group_slug']
self.team_id = kwargs['team_id']
self.game_id = kwargs['game_id']
self.extra = len(Stat.objects.filter(group__slug=self.group_slug))
del kwargs['group_slug']
del kwargs['game_id']
del kwargs['team_id']
super(BaseTeamStatsFormSet, self).__init__(*args, **kwargs)
def add_fields(self, form, index):
super(BaseTeamStatsFormSet, self).add_fields(form, index)
form.fields["stat"] = forms.ModelChoiceField(queryset = Stat.objects.filter(group__slug=self.group_slug))
form.fields["game"] = forms.ModelChoiceField(queryset = Game.objects.all())
form.fields["team"] = forms.ModelChoiceField(queryset = Team.objects.all())
form.fields["game"].initial = self.game_id
form.fields["team"].initial = self.team_id
TeamStatFormSet = formset_factory(TeamStatForm, BaseTeamStatsFormSet)
In your custom forms, you'll need to add a save() method that stuffs the form data into your models as needed. All of the data entered in the form will be available in a hash called cleaned_data[].
For example:
def save(self):
teamStat = TeamStat(game_id=self.cleaned_data['game_id'],team_id=self.cleaned_data['team_id'])
teamStat.save()
return teamStat
Only model forms and formsets come with a save() method. Regular forms aren't attached to models, so you have to store the data yourself. How to save a formset? from the Django mailing list has an example of saving data from a regular formset.
Edit: You can always add a save() method to a regular form or formset as gbc suggests. They just don't have one built-in.
I don't see a TeamStat model in your code snippets, but if you had one, your forms.py should look something like this:
class TeamStatForm(forms.ModelForm):
total = forms.IntegerField()
class Meta:
model = TeamStat
class BaseTeamStatsFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
self.group_slug = kwargs['group_slug']
self.team_id = kwargs['team_id']
self.game_id = kwargs['game_id']
self.extra = len(Stat.objects.filter(group__slug=self.group_slug))
del kwargs['group_slug']
del kwargs['game_id']
del kwargs['team_id']
super(BaseTeamStatsFormSet, self).__init__(*args, **kwargs)
def add_fields(self, form, index):
super(BaseTeamStatsFormSet, self).add_fields(form, index)
form.fields["stat"] = forms.ModelChoiceField(queryset = Stat.objects.filter(group__slug=self.group_slug))
form.fields["game"] = forms.ModelChoiceField(queryset = Game.objects.all())
form.fields["team"] = forms.ModelChoiceField(queryset = Team.objects.all())
form.fields["game"].initial = self.game_id
form.fields["team"].initial = self.team_id
TeamStatFormSet = modelformset_factory(TeamStatForm, BaseTeamStatsFormSet)
See Creating forms from models from the Django docs