1

I have this ModelForm

class ScheduleForm(forms.ModelForm):

    class Meta:
        model = Schedule
        fields = ['name', 'involved_people',]

    def __init__(self, user, *args, **kwargs):
        super(ScheduleForm, self).__init__(*args, **kwargs)
        self.fields['involved_people'].queryset = Profile.objects.exclude(user=user)

This is my view

def create_schedule(request):
    form = ScheduleForm(request.POST or None)
    schedules = Schedule.objects.all().order_by('deadline_date')

    if form.is_valid():
        schedule = form.save(commit=False)
        schedule.save()

        messages.success(request, "Schedule added successfully!")
        return render(request, 'schedule/index.html', {'schedules': schedules})

    context = {'form': form}

    return render(request, 'schedule/create_schedule.html', context)

How do you pass request.user in the view? How do you initialize the form with request.user in it?

JM Lontoc
  • 211
  • 4
  • 15

1 Answers1

5

You have added user to the __init__ method,

def __init__(self, user, *args, **kwargs):

so now you just pass the user as the first argument when you instantiate your form.

form = ScheduleForm(request.user, request.POST or None)
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Great answer but in generic views to pass request.user to form I did as below: ```def get_form_kwargs(self): kwargs = super(AccountSettingsView, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs``` and in form: `self.user = kwargs.get('user')` – Shaig Khaligli Apr 03 '19 at 21:24
  • 1
    @ShaigKhaligli Either the form should have `def __init__(self, user, *args, **kwargs)`, in which case you would do `self.user = user`, or the form has `def __init__(self, *args, **kwargs)`, in which case you use `self.user = kwargs.pop('user')` so that `user` is removed from `kwargs` before you call `super`. You can see examples of both approaches in [this question](https://stackoverflow.com/questions/32273135/how-to-override-form-field-in-createview) – Alasdair Apr 03 '19 at 21:50
  • yeah brilliant ! i did the same, thanks for helping ! – Shaig Khaligli Apr 03 '19 at 22:00