Initialize form with request.user in a ModelForm django

我是研究僧i 提交于 2019-12-13 03:03:53

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/47076529/initialize-form-with-request-user-in-a-modelform-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!