1

The slug will only work on HomeView if I add it to the HomeViews context, but I only want to add it one time, I don't want to add it to every view, but I want it to work on every view.

Is there anyway I can do this?

app2/models.py

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse


class Model1(models.Model):
    name = models.CharField(max_length=100)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, blank=False, null=False)

app1/views.py

from app2.models import Model1
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.views.generic.list import ListView


class HomeView(ListView):
    model = Model1
    ordering = ['-id']
    template_name = 'app1/home.html'
    boolean = False
    model1_slug = 'app2'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
            if Model1.objects.filter(user=self.request.user).exists():
                self.boolean = True
                user_model1 = Model1.objects.get(user=self.request.user)
                self.model1_slug = user_model1.slug
                
            else:
                self.model1_slug = 'app2'
                self.boolean = False
            context['model1_slug'] = self.model1_slug
            context['boolean'] = self.boolean
        return context

includes/navbar.html

            {% if boolean == False %}
              <li><a class="dropdown-item" href="{% url 'start-model1' %}">Start Model1</a></li>
            {% elif boolean == True  %}
              <li><a class="dropdown-item" href="{% url 'my-model1' model1_slug %}">My Model1</a></li>
              <li><a class="dropdown-item" href="{% url 'add-model2' %}">Add model2</a></li>
            {% endif %}

       

The navbar will give nothing if I'm not at the home page.

AnonymousUser
  • 690
  • 7
  • 26

0 Answers0