![](/img/trans.png)
[英]How can I assign the logged in (authenticated) user to the form data they submit?
[英]How can i submit a form with logged in user as default?
注冊后,系統會提示您進入登錄頁面,登錄后,您將被重定向到另一個頁面,該頁面包含用於收集有關新用戶的其他信息的表單。 問題是如果我沒有在 html 文件中指定 {{form.user}} 實例,則表單不會提交。 可能是因為默認情況下無法識別 user_id。 當我指定它時,該表單讓我從現有用戶中進行選擇,我希望它默認為登錄用戶 go。
楷模
class AdditionalInfoModel(models.Model):
objects = None
skill_choices = (('Beginner', 'BEGINNER'),
('Intermediate', 'INTERMEDIATE'),
('Expert', 'EXPERT'))
user = models.OneToOneField(User, on_delete=models.CASCADE)
location = models.CharField(max_length=30, blank=True)
assumed_technical_ski_level = models.CharField(max_length=30, choices=skill_choices)
years_of_experience = models.PositiveIntegerField(blank=True)
money_to_spend = models.PositiveIntegerField(blank=True)
def __str__(self):
return self.user.username
觀點
class CreateInfoView(LoginRequiredMixin, CreateView):
model = AdditionalInfoModel
form_class = AdditionallnfoModelForm
template_name = "user_ski_experience/additional_info.html"
def get_form_kwargs(self):
variable_to_send = super(CreateInfoView,
self).get_form_kwargs()
variable_to_send.update({'pk': None})
return variable_to_send
def get_success_url(self):
return reverse('aplicatie2:home')
forms
class AdditionallnfoModelForm(forms.ModelForm):
class Meta:
model = AdditionalInfoModel
fields = '__all__'
def __init__(self, pk, *args, **kwargs):
super(AdditionallnfoModelForm, self).__init__(*args,
**kwargs)
self.pk = pk
def clean(self):
return self.cleaned_data
html
{% load crispy_forms_tags %}
{% block content %}
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{% csrf_token %}
<h1> Let's get started with some questions ! </h1>
<h2> This will help us get to know your ski experience
</h2>
<li> Your user name is: {{form.user|as_crispy_field}}</li>
<li> Where do you live ?
{{form.location|as_crispy_field}} </li>
<li> How would you rank yourself as a skier ?
{{form.assumed_technical_ski_level|as_crispy_field}}
</li>
<li> How many years of ski experience do you have ?
{{form.years_of_experience|as_crispy_field}} </li>
<li> How much ar you willing to spend ?
{{form.money_to_spend|as_crispy_field}} </li>
<button type="submit" onclick = "{% url 'aplicatie2:home'
%}">Submit</button>
</form>
</body>
{% endblock %}
登錄和注冊是使用標准 django 模型完成的
我建議使用禁用字段並通過表單的初始化方法設置用戶的初始值。 禁用字段在 POST 請求中被完全忽略,因此用戶將無法更改您通過該字段設置的默認用戶。
Django 關於禁用屬性的文檔: https://docs.djangoproject.com/en/4.0/ref/forms/fields/#disabled
視圖.py
class CreateInfoView(LoginRequiredMixin, CreateView):
model = AdditionalInfoModel
form_class = AdditionallnfoModelForm
template_name = "user_ski_experience/additional_info.html"
def get_form_kwargs(self):
variable_to_send = super(CreateInfoView,
self).get_form_kwargs()
variable_to_send.update({'pk': None})
variable_to_send.update({'pk_user': self.request.user.pk})
return variable_to_send
def get_success_url(self):
return reverse('aplicatie2:home')
forms.py
class AdditionallnfoModelForm(forms.ModelForm):
class Meta:
model = AdditionalInfoModel
fields = '__all__'
def __init__(self, pk, *args, **kwargs):
pk_user = kwargs.pop('pk_user')
super(AdditionallnfoModelForm, self).__init__(*args,
**kwargs)
self.pk = pk
# Make the user field readonly
self.fields['user'].disabled = True
self.fields['user'].initial = pk_user
def clean(self):
return self.cleaned_data
編輯:還在您的 HTML 中發現了問題。表單不會提交,因為您的 HTML 不適合提交表單。 像下面這樣的東西應該有效:
{% load crispy_forms_tags %}
{% block content %}
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- Place the POST endpoint URL in the action attribute of the 'form' tag -->
<form method="post" action="{% url 'aplicatie2:home' %}">
{% csrf_token %}
<h1> Let's get started with some questions ! </h1>
<h2> This will help us get to know your ski experience
</h2>
<li> Your user name is: {{form.user|as_crispy_field}}</li>
<li> Where do you live ?
{{form.location|as_crispy_field}} </li>
<li> How would you rank yourself as a skier ?
{{form.assumed_technical_ski_level|as_crispy_field}}
</li>
<li> How many years of ski experience do you have ?
{{form.years_of_experience|as_crispy_field}} </li>
<li> How much ar you willing to spend ?
{{form.money_to_spend|as_crispy_field}} </li>
<!-- You can't use <button> element for submitting a form without special JS -->
<input type="submit">Submit</button>
</form>
</body>
{% endblock %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.