如何获取用户对象并将其传递给django中的表单字段

how to get user object and pass it to form field in django

是否有更好的方法从下面 forms.py 中的代码获取用户对象?

型号

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

forms.py

class FooForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("user")
        super(ExperienceStart, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.layout = Layout(InlineRadios('topics'),)

    hardcoded_username = "johndoe" # i want to find a way not to hardcode this

    current_user = User.objects.filter(username=hardcoded_username).first()

    profile = Profile.objects.filter(user=current_user).first()

    ...

    profile_values = list(zip(profile, profile))

    profile = forms.TypedChoiceField(
        label="Select a Profile",
        choices=profile_values,
        coerce=str,
        widget=forms.RadioSelect,
        initial=profile[0],
        required=True)

views.py

def foo(request):
    form = fooForm(request.POST, user=request.user)

    print(form.request) # i have already tried this but i want to get it in form not views

    if request.method == "POST":
        if form.is_valid():
            # do something
    else:
        form = fooForm(user=request.user)

    context = {"form": form}

我正在尝试找到一种方法,而不是在 forms.py 中对用户名进行硬编码并获取当前登录的用户。

不要将其包含在表单中。表单通常 请求未知 ,此外还用于处理来自 HTML 表单的输入。

您可以利用表单的initial=…参数来指定初始项。

在您的表单中,您可以使用 ModelChoiceField [Django-doc] 到 select Profile 项目:

class FooForm(forms.Form):

    profile = forms.<strong>ModelChoiceField(</strong>
        label='Select a Profile',
        <strong>queryset=Profile.objects.all()</strong>,
        widget=forms.RadioSelect,
        required=True
    <strong>)</strong>

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.layout = Layout(InlineRadios('topics'))

然后在视图中,您可以将用户的个人资料作为初始值传递:

from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required

@login_required
def foo(request):
    if request.method == 'POST':
        form = fooForm(request.POST<strong>, initial={'profile': request.user.profile}</strong>)
        if form.is_valid():
            # do something
            return <strong>redirect('<em>name-of-some-view</em>')</strong>
    else:
        form = fooForm(<strong>initial={'profile': request.user.profile}</strong>)
    context = {'form': form}
    return render(request, 'some_template.html', context)

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].


Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.