[Answer]-Save a django object getting another model instance as foreign key from a form

1👍

Something like this should work. A couple of things:

1) I changed the form field to a ModelChoiceField instead of multiple choice. You’ll want to use a ModelChoiceField to show the relationship. I changed this from MultipleChoice since, according to your model, you only want to save one choice. You can read more on ModelChoiceFields here: https://docs.djangoproject.com/en/dev/ref/forms/fields/

2) In your forms, I changed the choice query to customer = forms.ModelChoiceField(queryset=Customer.objects.filter(owner=request.user). This will filter for Customers of the specific user only.

forms.py

class AppointmentForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(AppointmentForm, self).__init__(*args, **kwargs)

    basedate = forms.DateField()
    start = forms.TimeField(widget=forms.Select())
    end = forms.IntegerField(widget=forms.Select())
    customer = forms.ModelChoiceField(queryset=Customer.objects.filter(owner=request.user))

views.py

def form_valid(self, form):
    if request.method=='POST':
        form = AppointmentForm(request.POST, request=request)
        if form.is_valid():
            appointment = Appointment()
            appointment.user = self.request.user
            basedate = form.cleaned_data['basedate']
            start = form.cleaned_data['start']
            duration = form.cleaned_data['end']
            appointment.customer = form.cleaned_data['customer']
            appointment.start = datetime.datetime.combine(basedate, start)
            appointment.end = appointment.start + datetime.timedelta(minutes=duration)       
            appointment.save()
            return super(AppointmentCreate, self).form_valid(form)
    else:
        form = AppointmentForm()

0👍

Finally I did it. The key was to override the get method of FormView class in views.py, rather than modifying the init in forms.py:

forms.py:

class AppointmentForm(forms.Form):
    basedate = forms.DateField()
    start = forms.TimeField(widget=forms.Select())
    end = forms.IntegerField(widget=forms.Select())
    customer = forms.ModelChoiceField(queryset=Customer.objects.all())
    ...

views.py:

    def get(self, request, *args, **kwargs):
        """
        Handles GET requests and instantiates a blank version of the form.
        """
        choices_start, choices_duration = self._get_choices()
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        form.fields['start'].widget=forms.Select(choices=choices_start)
        form.fields['end'].widget=forms.Select(choices=choices_duration)
        form.fields['customer'].queryset=Customer.objects.filter(owner=request.user)
        return self.render_to_response(self.get_context_data(form=form))

@Dan: Many thanks for your effort in helping me out.

Leave a comment