Django:другая html-страница, если форма отправлена

Я хочу, чтобы моя html-страница больше не показывала форму после того, как она отправлена пользователем, а вместо этого я хотел бы показать страницу с сообщением о том, что форма уже была отправлена. Я думал использовать дату регистрации для определения того, отправлена форма или нет, но вот какую ошибку я получаю, когда форма не отправлена 'NoneType' object has no attribute 'registration_date', в то время как код работает, если форма уже отправлена. Я также не знаю, хорошо ли использовать наличие или отсутствие даты регистрации для определения того, отправлена ли форма, я добавил булево поле profile_submitted в файл модели, но я не могу установить его в true и использовать его

models.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)

view.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)

page.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 %}

Ваш код пытается получить "registration_date" для экземпляра UserProfile, и он получает этот экземпляр UserProfile, используя "request.user", то есть вошедшего пользователя. Если пользователь не вошел в систему, он вернет пустой QuerySet, а если вы возьмете первый элемент, он вернет None.

Вы не можете вызвать "registration_date" на None.

Может быть, проверить, вошли ли вы в систему? Или если это профиль, связанный с пользователем, проверьте, как расширить модель пользователя:

https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html

Вы можете проверить результат .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 %}
Вернуться на верх