Problem context:
Below is my Blogger model. I am using a one-to-one relation ship with inbuilt user
class Blogger(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
about = models.TextField(max_length=2000, null=True)
def __str__(self) -> str:
return f'{self.user.first_name} {self.user.last_name}'
Before logging in I get the the following Login page. ( I am using django.contrib.auth.urls
with custom login page that extends base_generic.html. HTML has link in the side bar About Yourself which would only show up after successful login only.
{% if user.is_authenticated %}
<li>User: {{ user.get_username }}</li>
<li><a href="{% url 'blogger-create' %}">About yourself!</a> </li>
When a user after sign up or login clicks on About yourself link then user is redirected to blogger create form where he will update his About information. User Registration creates an instance of user which would be mapped to a new instance of Blogger via About Yourself
Problem
I want to have two views UpdateView
and CreateView
that would ensure if a blogger instance is already mapped to user then the update view would be called. this would require conditions in the template of base_generic.html. if else conditions would use something like models.Blogger.objects.filter(user=self.request.user)
.
The trouble is as already stated I am using inbuilt accounts\login. How to achieve this logic when a user logs in successfully then based upon the condition show the links for create and update. Logic would be something like below:
linked_blogger = models.Blogger.objects.filter(user=self.request.user)
if linked_blogger is None:
<li><a href="{% url 'blogger-create' %}">About yourself!</a> </li>
else:
<li><a href="{% url 'blogger-update' blogger.id%}">About yourself!</a> </li>
I am not yet logged in so there is no authenticated user yet. After login once I get authenticated user I want to be able to use the if else logic.
I explored through a couple of options online but none of them appealed to me.
I am expecting to be able to send some context after redirect so that I can use that context in the page after redirection.
Give this a try, pass a context is_blogger to template from the view, then in the templates you can hide/show the links conditionally
from django.shortcuts import render
def your_view(request):
# this is a bare minimum filter,
# you might have to write filter query according to your use-case
is_blogger = Blogger.objects.filter(user=request.user).exist()
context = {'is_blogger': is_blogger}
return render(request, 'my_template.html', context)
and in you html template
{% if user.is_authenticated %}
<li>User: {{ user.get_username }}</li>
{% if is_blogger %}
<li><a href="{% url 'blogger-create' %}">About yourself!</a> </li>
{% else %}
<li><a href="{% url 'blogger-update' blogger.id%}">About yourself!</a> </li>
{% endif %}
{% endif %}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments