【问题标题】:how to pass the username to the member who fill a form?如何将用户名传递给填写表格的会员?
【发布时间】:2021-10-07 21:27:48
【问题描述】:

我有一个表单,我想将用户传递给它以查看哪个登录用户填写了它。 这是我的forms.py

from .models import UserInfo
from django import forms

class InfoForm(forms.ModelForm):
    class Meta:
        model = UserInfo
        fields = ('name', 'age', 'male', 'female', 'height', 'weight',
        'BMI', 'BFP', 'phone', 'r_g_weight', 'physical_ready', 'fitness',
        'workour_sports', 'others', 'goal_expression', 'body_change',
        'noob','low_pro','semi_pro','pro','motivation_level','goal_block',
        'change_time','past_sports','injury','work','work_time','wakeup_time',
        'work_start_time','sleep_time','daily','hard_to_wake','ready_to_work',
        'life_situation','weight_feel','daily_jobs','health_ready','workout_period',
        'what_sport','where_sport','home_sport','weekly_time','sport_dislike','daily_food',
        'food_quantity','hunger','vitamins','rejims','vegetables','goal_rec',
        'stop','rec','heart','chest','chest_month','dizzy','bones','blood','other_reason')

这是我的观点,我用 request.user 询问用户,但 db 中的字段对于用户名总是为空。

def userForm(request):

    
    if request.method == "POST":
        form = InfoForm(request.POST)
        if form.is_valid():
            form.user = request.user
            form.save()
            
            return redirect('profile')
    else:
        form = InfoForm()

    context = {
        'form':form
    }
    return render(request, 'fitness/user_form.html', context)

所以我的模型中有用户,我的帐户有外键

user = models.ForeignKey(Account,on_delete=models.CASCADE, null=True, blank=True)

这是我的模板:

<div class="container">
    <form action="{% url 'user-form' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}

        {{form.as_p}}

        <input type="submit" value="submit">
    </form>
</div>

【问题讨论】:

    标签: django django-models django-views django-forms


    【解决方案1】:

    问题在于您保存表单的方式。您在表单上设置用户属性,而不是实际的模型对象。以下应该可以解决您的问题

    def userForm(request):
    
        if request.method == "POST":
            form = InfoForm(request.POST)
            if form.is_valid():
                # dont commit the object to the database as we need to set the user
                object = form.save(commit=False)
                # set the user
                object.user = request.user
                # finally save the object now that the user has been set
                object.save()
            
                return redirect('profile')
        else:
            form = InfoForm()
    
        context = {
            'form':form
        }
        return render(request, 'fitness/user_form.html', context)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-07
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 2013-03-10
      相关资源
      最近更新 更多