我希望我的 html 頁面在我的用戶提交后不再顯示該表單,而是我想顯示一個頁面,其中顯示一條訊息,表明該表單已提交。我想使用注冊日期來確定提交與否的任何表單,但這是我在未提交表單'NoneType' object has no attribute 'registration_date'而代碼作業時遇到的錯誤, 如果已經提交了表單。我也不知道使用沒有注冊日期的存在來確定是否提交了表單是否好,我已經profile_submitted在我的模型檔案中添加了BooleanField 但我無法將其切換為 true 和用它。
模型.py
class UserProfile(models.Model):
user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE)
gender = models.CharField(max_length=120, choices=gender_choice)
birthdate = models.DateField()
age = models.CharField(max_length=2)
phone = models.CharField(max_length=10)
email = models.EmailField()
registration_date = models.DateField(default=datetime.today(), blank=True)
profile_submitted = models.BooleanField(default=False)
查看.py
def view_profile(request):
profile_is_submitted = UserProfile.objects.filter(user=request.user).first().registration_date is not None
context = {'profile_is_submitted': profile_is_submitted }
return render(request, 'page.html', context)
頁面.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1> Title </h1>
{% if profile_is_submitted %}
You have already submitted the form
{% else %}
<h1> Title </h1>
<div class="container">
<div cass="form-group">
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary">Post</button>
</div>
</div>
</body>
{% endblock %}
uj5u.com熱心網友回復:
您的代碼嘗試在該 UserProfile 實體上獲取“registration_date”,并使用“request.user”(即登錄用戶)獲取該 UserProfile 實體。如果用戶未登錄,將回傳一個空的 QuerySet,如果您采用第一個元素,它將回傳 None。
您不能在 None 上呼叫“registration_date”。
也許檢查您是否已登錄?或者,如果它是鏈接到用戶的組態檔,請查看如何擴展用戶模型:
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
uj5u.com熱心網友回復:
您可以檢查結果.first()并相應地傳遞模板中 registration_date 的值。
def view_profile(request):
profile_is_submitted = False
userprofile = UserProfile.objects.filter(user=request.user).first()
if userprofile:
profile_is_submitted = userprofile.registration_date
context = {'profile_is_submitted': profile_is_submitted }
return render(request, 'page.html', context)
您不需要這些附加欄位,您可以將 userProfile 物件傳遞到模板中并檢查組態檔是否存在,如下所示:-
def view_profile(request):
context = {'user_profile': UserProfile.objects.filter(user=request.user).first() }
return render(request, 'page.html', context)
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1> Title </h1>
{% if user_profile %}
You have already submitted the form
{% else %}
<div cass="form-group">
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary">Post</button>
</form>
</div>
{% endif %}
</div>
{% endblock %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/330722.html
