Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['blog/article/<int:pk>/']
I created a simple article/blog app. I am having problem in detail view. I created a list view of articles and also created a detail view if someone clicks on one of the acrticle , it takes the to detail view of article . But when i click on one of the articles , i am getting above error stated in the title. It is also pointing the error location to this code {% url "detail" post.id %} which u can see in 44th or 45th line in Error page i posted in the last. I tried lots of thing , none worked. I posted all my project files below. you can have look. I would be glad if you guys helps me. My code goes here : Views.py from django.shortcuts import render , redirect , get_object_or_404 from django.shortcuts import render , redirect , get_object_or_404 from .models import Article , members from django.views.generic import ListView , DetailView from .forms import create_form class article_view(ListView): model = Article template_name = "article.html" context_object_name = "articles" def post_creator(request): if request.method == "POST": form = create_form(request.POST) if form.is_valid(): form.save() return redirect("/blog/home/") else: form = create_form() return render(request , "post_create.html" , {"form":form}) def registration(request): if request.method … -
assert isinstance(address, (tuple, list, str)), "tuple or str expected" AssertionError: tuple or str expected
I am working on a django project in which I included django channels but I getting this error. I have tried to fix the bug but the problem is that I can not really find where my program has issues. #views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import View from django.http import HttpResponse, HttpResponseRedirect from Forecast.models import* from channels.layers import get_channel_layer from asgiref.sync import async_to_sync #this is to help us convert the asyncrounous request to a syncronous one class Home(View): def get(self, request): houses = House.objects.all() context={'houses':houses} layer = get_channel_layer() async_to_sync(layer.group_send)( 'visted', { 'type':'homepage.visted', 'event':'new visit', 'username':request.user.username }) return render(request,'accounts/base.html',context) Then this below is my consumer.py #consumer.py from channels.generic.websocket import AsyncWebsocketConsumer import asyncio class TestConsumer(AsyncWebsocketConsumer): async def connect(self): #this accepts the connection await self.accept() await self.channel_layer.group_add('visted', self.channel_name) await asyncio.sleep(4) await self.send(text_data='you have been connected') async def receive(self, test_data=None, byte_data=None): #this handles all received data await self.send(text_data= 'we got your message') await asyncio.sleep(4) await self.close() async def disconnect(self): await self.channel_layer.group_discard('visited', self.channel_name) async def hompage_visted(self, event): await self.send(text_data=event['message']) finally my routing.py, asgi routing file #routing.py from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from .consumer import TestConsumer application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path('testsocket/', TestConsumer) ]) … -
Django Model Initial Form Value based on DB values
I have two models: class ReceiptBook(models.Model): serial_no = models.IntegerField(unique=True) leaf_start = models.IntegerField() leaf_end = models.IntegerField() issued_person = models.ForeignKey(Person) issued_date = models.DateField() status = models.CharField(max_length=15,choices=st,default='IS') class ReceiptLeaf(models.Model): receipt_book = models.ForeignKey(ReceiptBook, limit_choices_to={'status': 'IS'}) receipt_no = models.IntegerField() receipt_date = models.DateField() received_from = models.CharField(max_length=150) kudumba_unit = models.CharField(max_length=20, choices=units) amount = models.DecimalField(max_digits=20, decimal_places=2) In my admin interface I am showing ReceiptLeaf model lnlined with ReceiptBook. Now I want to initialise the value of receipt_no field using the receipt_book field ie; using the value of leaf_start and leaf_end using receipt_book object. I have this function on admin.py: def get_receipt_no(self): receipt = ReceiptLeaf.objects.filter(receipt_book=?) #how to get receipt book object here no = receipt.receipt_no + 1 if not no: no = receipt.receipt_book.leaf_start return no which is used by the formfield_for_dbfield method: def formfield_for_dbfield(self, db_field, **kwargs): field = super(ReceiptLeafInline, self).formfield_for_dbfield(db_field, **kwargs) if db_field.name == 'receipt_no': field.initial = get_receipt_no(self) return field How can I pass receipt_book value to get_receipt_no() function? Since more than one ReceiptLeaf's are associated with one ReceiptBook, I need the receipt_book object to properly initialise the receipt_no field. -
SSL certificate for the ip adress [Nginix+django server]
I have nginix+django server on google cloud virtual machine which is running at a specific port(8080). I am able to access the service by http://external_ip:8080. But I'm not able to access it over "https". I dont have a domain name. For our application it is not necessary as it is just a rest api to perform some tasks. I am relatively new to these terms like ssl certificate, domain name, nginix ... etc. It would be great if someone can help me out. Thanks in advance. -
Merge two QuerySets such that every n-th element will be from the second one
I'm not sure if this can be done using only Django ORM or pure SQL. I have a model Fruit and I want to render a list of fruits such that every and only n-th fruit is of type="apple". So for 4 it would be: any fruit except apple any fruit except apple any fruit except apple apple any fruit except apple any fruit except apple ... I'm looking for a more efficient way to do that than having a huge list of fruits, preferably one QuerySet but not sure if it's even possible. fruits_except_apples = Fruit.objects.exclude(type='apple') apples = Fruit.objects.filter(type='apple') -
"'NoneType' object is not iterable" when adding new user on django custom user model
First of all, I am new to Django. Please tell me if my question is not clear and straightforward. I was trying to make custom user model for my app, everything seems fine until I found error when trying to add new user in the admin page. The error page was shown after I clicked Add User button on the top right of the page. *Note: I am using Django 1.10.8 I created it in the app named 'accounts' I am trying to get rid of username field (Django's default) and changed it to phone_number as the unique field. This is the error: Environment: Request Method: GET Request URL: http://localhost:8002/admin/accounts/user/add/ Django Version: 1.10.8 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 544. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/Users/user/Documents/adxasia/jani_backend/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 211. return view(request, *args, **kwargs) File … -
How to return image file in Django model (rest framework)?
Models.py File class Club(models.Model): club_name = models.CharField(max_length=256, blank=True, null=True) *some other flieds* class ClubRequirment(models.Model): *some other flieds* class ClubImage(models.Model): image = models.ImageField(upload_to='club_image/picture/', blank=True, null=True) club = models.ForeignKey(Club, null=True, on_delete=models.CASCADE, related_name='club_image') created_on = models.DateTimeField(auto_now_add=True) update_on = models.DateTimeField(auto_now=True) def __str__(self): return str(self.image) Serializer.py File class ClubImageSerializer(serializers.ModelSerializer): class Meta: model = ClubImage fields = "__all__" class ClubRequirmentSerializer(serializers.ModelSerializer): class Meta: model = ClubRequirment fields = "__all__" class ClubSerializer(serializers.ModelSerializer): club_requirment = serializers.SlugRelatedField(many=True,read_only=True,slug_field='text') club_image = serializers.StringRelatedField(many=True) class Meta: model = Club fields = ('id', 'club_name', 'club_image', 'club_requirment') Output of ClubSerializer [ { "id": 1, "club_name": "Test Club", "club_image": [ "club_image/picture/pexels-photo-247932_2gnEgrn.jpeg", "club_image/picture/FB_IMG_1525249792281.jpg" ], "club_requirment": [ "Hello Günter", "whats your name", "text" ] } ] above output only show image name I need to full path of image . if it possible to return in model or any solution -
Allow only admin to POST data: Django Rest Framework
I am using Django Rest Framework for my project and has started today only. But I have a minor doubt. Here anyone can POST data by opening the required URL. All I want is that only admin of the site can POST data and no one else. Here is the code: # views.py class PlayerViewSet(viewsets.ModelViewSet): queryset = Players.objects.all() serializer_class = PlayerSerializer # serializers.py from .models import Players from rest_framework import serializers class PlayerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Players fields = ('rank','name') -
Django shortcut get_object_or_404 inside Django Rest framework Class Based Views
The get_object_or_404 shortcut function in Django when encountering an exception gives a very nice error message in the following format: 'No %s matches the given query.' % queryset.model._meta.object_name) However, while using this inside a DRF 3.X Class based view, the final 404 response data has a very stripped down version, which is as follows: {"detail": "Not found."} As is evident, the DRF message is very generic with no information about the Model name.I am assuming that the DRF NotFound Exception class defined here strips down the message to its current bare minimum. How can I get the original nice error message that Django returns in-spite of using it within a DRF Class Based View ? -
Django app throws MigrationSchemaMissing when migrating to heroku MySQL ClearDB
So I have built a simple app using MySQL instead of SQlite and everything migrates nicely when I deploy on localhost, the localhost DB settings look like this: # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'news', # 'USER': 'myname', # 'PASSWORD': 'my_password', # 'HOST': 'localhost', # 'PORT': '', # # } # } But I change the settings to the following for deploying to heroku using the ClearDB addon: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'heroku_db_dbname', 'USER': 'heroku_db_username', 'PASSWORD': 'heroku_db_password', 'HOST': 'us-cdbr-iron-east-01.cleardb.net', 'PORT': '3306', } } With heroku_db_name, heroku_db_username and heroku_db_password being the actual values from heroku obviously. The app deploys just fine minus the DB and I can makemigrations with no issues but once I run python manage.py migrate I get a MigrationSchemaMissing exception, more specifically: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL)' at line 1")) I'm not sure how there can be a syntax error since all the SQL is generated by django and all of it works fine on my local … -
Django static files not loading, though the correct links show in view source
Static files located at top level of project not loading correctly in Django 2.1.3. When I do a view source of the page the path is correct and i can click on the link, showing me that, indeed, the content is there. Inspecting the page, however, shows no stylesheets are loaded. Its a standard dev setup. The only factors that could be contributing are that i had to reinstall django and just straight replaced the basic new project folder with a copy of my project. The admin page seems to work ok along with the rest of the code, so the entire world didnt break. The only other change was installing SASS and trying to integrate Bootstrap 4 at a local level (not messing with the standard folder layout). Wont work with the compiled SASS css (Interestingly, when i viewed the link in the source the changes were present) or any other simple hand written css. Static JS is also broken. The links and code seem ok in source, just not loading. -
how to auto populate Django Rest Framework Model fields
Trying to auto populate model attributes using Django rest framework Intro: I have 2 models Patient and Embryo There is only 1 user who is the superuser. All patients belong to the superuser. One patient can have many embryos but an embryo can have only one patient. What I want to achieve The Embryo model has a field called karyotes which is a Charfield. when the user inputs the karyotes the sex of the embryo is auto-populated. The same with down-syndrome (see models below example) Example (This is not code, just explanation ) if karyotype == "46,XX" #The embryo is a Female if karyotype == "46,XY" #The embryo is a Male if karyotype == "47,XY,+21" #The embryo is a Male and has Down Syndrome if karyotype == "47,XX,+21" #The embryo is a Female and has Down Syndrome else sex == blank and down syndrome == blank Below are my models class PatientsApiView(viewsets.ModelViewSet): """ Handles Creating, reading and updating Patients """ class Embryo(models.Model): """ A ForeignKey model to the patient """ patient = models.ForeignKey(Patient, related_name="embryos", on_delete=models.CASCADE) code_name = models.CharField(max_length=100) karyotype = models.CharField(max_length=100) down_syndrome = models.BooleanField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) GENDER_CHOICES = ( ("M", "Male"), ("F", "Female"), ) sex … -
django channels ImproperlyConfigured: Cannot find 'app' in ASGI_APPLICATION module
I've looked at similar questions regarding this error setting up channels messaging with django. I am worried that this is a redis problem as the tutorial I am following states that "This tutorial also uses Docker to install and run Redis. We use Redis as the backing store for the channel layer, which is an optional component of the Channels library" but nowhere in the tutorial https://channels.readthedocs.io/en/latest/tutorial/part_1.html from parts 1-4 state where redis is required. I may be way off track but am wondering if anyone has new information regarding this error configuring channels with Django. "Cannot find %r in ASGI_APPLICATION module %s" % (name, path) django.core.exceptions.ImproperlyConfigured: Cannot find 'app' in ASGI_APPLICATION module .routing thanks -
How does django jwt sign the jwt token?
When using https://github.com/GetBlimp/django-rest-framework-jwt, how is the JWT request signed? Does it use the django secret-key in the settings.py file or how specifically does it sign the requests? Is there a way to provide a provide a private key file for this, or what are the requirements for singing the jwt request? -
Caching a DB connection for later view usage
I am saving a user's database connection. On the first time they enter in their credentials, I do something like the following: self.conn = MySQLdb.connect ( host = 'aaa', user = 'bbb', passwd = 'ccc', db = 'ddd', charset='utf8' ) cursor = self.conn.cursor() cursor.execute("SET NAMES utf8") cursor.execute('SET CHARACTER SET utf8;') cursor.execute('SET character_set_connection=utf8;') I then have the conn ready to go for all the user's queries. However, I don't want to re-connect every time the view is loaded. How would I store this "open connection" so I can just do something like the following in the view: def do_queries(request, sql): user = request.user conn = request.session['conn'] cursor = request.session['cursor'] cursor.execute(sql) Would there be a way to save the conn and cursor in some sort of format so that I can call them later and use them in a successive view call? Would doing request.session['conn'] = conn work? Or do I need to serialize this in a special way? -
Django/DRF: ListCreateAPIView POST with an annotated field that's in serializer not model
I'm building a simple budgeting app to work on learning Django & React. I've used DRF to build an API to create and get transactions from the database. I'm currently calculating the total running balance on the fly when I do my GET. This has been working well, but when I do a POST I get an error that my dynamic balance field is required since that field is in my serializer. How can I get around this? views.py class CreateView(generics.ListCreateAPIView): """This class defines the GET & POST behavior of the rest api.""" queryset = Transaction.objects.all() # This is the balance that's calculated on the fly queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'), order_by=F('created_time').asc())).all().order_by('-created_time') serializer_class = TransactionSerializer def perform_create(self, serializer): """Save the post data when creating a new transaction.""" serializer.save() def get_queryset(self): return self.queryset_with_balance serializers.py class TransactionSerializer(serializers.ModelSerializer): balance = serializers.DecimalField(decimal_places=2, max_digits=19) class Meta: """Meta class to map serializer's fields with the model fields.""" model = Transaction fields = ('id', 'date', 'payee', 'category', 'amount', 'balance', 'created_time', 'modified_time') models.py class Transaction(models.Model): date = models.DateField() payee = models.CharField(max_length=256) category = models.CharField(max_length=256) amount = MoneyField(max_digits=19, decimal_places=2, default_currency='USD') created_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) -
django format of url import
I am importing some views to the urls.py file, here is what I have from views.home import HomeView from views.list_player import PlayerList from views.list_game import GameList from views.create_player import PlayerCreate from views.create_game import GameCreate from views.detail_player import PlayerDetail from views.detail_game import GameDetail from views.update_player import PlayerUpdate from views.update_game import GameUpdate from views.delete_player import PlayerDelete from views.delete_game import GameDelete However, is there a way to import them like this? from .views import( Home, GameList, PlayerList, PlayerDetail, GameDetail, PlayerCreate, GameCreate, PlayerUpdate, PlayerDelete, GameUpdate, GameDelete ) which looks much more cleaner. -
Django Error Styling with Twitter Bootstrap
I am trying to style errors using twitter bootstrap in my Django project. Right now, I have a simple form that asks for a person's email address, has them press a button, and then submits it to the database. It also has validation checking to see if the email is unique in the database. If it is not unique, it raises an error saying "This email is already registered". However, when the error is raised, for a duplicate email, it brings an ugly bullet point list next to the input field with the text This email is already registered. I'm trying to style it to where it has a little dialog show under the input text with a yellow i icon like it does when the input does not include an @ sign, i.e. it isn't an email. The ugly bullet point also appears when a valid domain isn't included in the email, e.g. there isn't a .com appended. I think the problem lies with the way my form html is set up, or how the view handles the form's errors. Maybe, because the form field is an EmailField, the is_valid indicator doesn't validate and therefore shows the twitter bootstrap … -
Django Forms - ModelChoiceField remains ----- on Bound form
So, here's my situation: I have an existing database, and a model for an item. The item has a integer primary key and then a name as a string. When I prepopulate my form corresponding to this, all other fields contain data properly. This one shows its available list of options, but the initial value is not set to the ID I passed in. I know the ID exists, as it's presently a very simple database. Can I get some help? The field doesn't throw an error like if I intentionally pass a bad value, so I know that it's "accepting" the prepopulated value in some way but I cannot get the form itself to show this as its default selection. I would think this easy to do, but I have searched for several hours now and nobody touches on it? -
Django 2.1 Filtering Blog Posts by Publish Date
I just built a model manager to handle adjust filter my queryset to exclude future published posts (publish > timezone.now.date) and posts where Post.draft=True. class PostManager(models.Manager): def active(self, *args, **kwargs): return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now().date()) I am able to handle for the draft boolean field in my views and my templates. I.e., if a superuser is viewing the post app index page (list of posts), I can see a header tag indicating it is a draft: template for post list page: <div class="card-body"> {% if post.draft %}<h3>Staff Only: Draft</h3>{% endif %} {% if instance.publish > today %}<h3>Staff Only: Future Post</h3>{% endif %} Here is my view.py for my function based list view --- you'll see "today" (from above) as a context variable: def post_view(request): template_name = 'posts/index.html' today = timezone.now().date() queryset_list = Post.objects.active() if request.user.is_staff or request.user.is_superuser: queryset_list = Post.objects.all() paginator = Paginator(queryset_list, 5) page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'post_list': queryset, 'today': today, } return render(request, template_name, context) I am curious as to why I am able to handle for(exclude from public view) posts where draft is set to True, but not for posts where publish > timezone.now().date() with the code I have. Here is my publish modelfield … -
Why is my jquery in Django app not working?
I am implemening a dependent-dropdown form with JQuery and Django. However, I still have no idea why this jquery does not work. My template: {% block style %} <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" media="screen" href="{% static 'css/style.css' %}"/> {% endblock %} {% block script %} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type='text/javascript' src="{% static 'js/ajax_load_rooms.js' %}"></script> {% endblock %} {% block content %} <div class="container-"> <div class="wrapper"> <form id='selectForm' method="post" data-rooms-url="{% url 'ajax_load_rooms' %}"> {% csrf_token %} <div class="building"> <label for="building">Nhà học</label> {{ form.building }} </div> <div class="room"> <label for="room">Phòng học</label> {{ form.room }} </div> <button class="show-list btn btn-primary" >Thoi gian bieu</button> </form> </div> </div> {% endblock %} My jquery: $("#id_building").change(function () { var url = $("#selectForm").attr("data-rooms-url"); var buildingId = $(this).val(); $.ajax({ url: url, data: { 'building': buildingId, }, success: function (data) { $("#id_room").html(data); } }); }); My view: def load_rooms(request): building = request.GET.get('building') room_list = Room.objects.filter(building__bid=building, availability=True) return render(request, 'dropdown-room-list.html', {'rooms': room_list}) Note that my javascript static path is right, the template is rendered nicely and I can see the javascript path to the right code. But the dependent-dropdown functionlity is seems to be not working. -
Django Rest Framework + Angular 2
I new to the web development. Right now, I am using Angular 2 as front-end and Django-Rest-framework as back-end. While browsing the tutorials online, people often build the angular2 app (ng build) and then place those built files under the django project. But my question is, doesn't this approach defeat the purpose of decoupling? Can you provide me the pros and cons of these two approaches? Ask Django to host the built angular project, and deploy it as one instance. Separate both frontend and backend, and deploy them as two instances. Thanks in advance. -
How to search for values in Redis with redis for python
I'm currently trying to search for entries inside my Redis that match a specific value through an HTTP API the same way you'd do with a regular DB (eg: http://localhost:8000/api?name=John&age=20) with the redis python library (https://pypi.org/project/redis/). The code I have thus far returns the whole hash, converts each entry into a JSON and adds it to a list import json import redis import os r = redis.StrictRedis(host=os.environ['redis_url'], port=os.environ['redis_port'], password=os.environ['redis_pass'], ssl=True) result = r.hgetall('Directory') dic_list = [] for key in result.keys(): dic_list.append(json.loads(result[key].decode('utf-8'))) return dic_list I know that I can get the value of a specific key with r.hget('Directory', 'key_I_want') However inside each key there is a whole JSON full with information, so for example this would be a key, value example inside of the Directory hash "1": { "name": "James", "age": "22", "favorite_color":"Green" }, "2":{ "name":"John", "age": "20", "favorite_color": "red" }, "3":{ "name":"Jim", "age": "30", "favorite_color": "yellow" } So I know r.hget('Directory', '1') would return { "name": "James", "age": "22", "favorite_color":"Green" } But what I really want is to look for every JSON that has specific values, not just to get the values of each key inside the hash, is there any way to actually do that? -
ImportError: No module named models after split views.py into several files
I am doing the same thing as the following question. the top answer is what I did. Split views.py in several files However, when I go to import my models from .models import MyModel I get this error: ImportError: No module named models -
Check if text exists in Django template context variable
This may not be the best way of doing this (open to suggestions). But I want to display a button on my home page depending on the value of a Boolean in the custom user model. I am passing the value of this boolean via context in the view. But I can't seem to get the template logic to work. Models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): isAdmin = models.BooleanField(default = False,) #more models... views.py from django.views.generic import TemplateView from django.contrib.auth import get_user_model from accounts.models import CustomUser class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: adminStatus = CustomUser.objects.get(id=self.request.user.id) print(adminStatus.isAdmin) context['adminStatus'] = str(adminStatus.isAdmin) return context home page template.html {% extends 'base.html' %} {% block body %} {% if user.is_authenticated %} <h4>Hi {{ user.username }}!</h4> <a class="btn btn-primary btn-lg" href="{% url 'dashboard' %}" role="button"> Go to Dashboard</a> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> </div> {% if adminStatus == "True" %} <h1>test</h1> <div class = "adminPanel"> <a class="btn btn-primary btn-lg" href="{% url 'newEquipment' %}" role="button"> add new equipment</a> </div> {% endif %} {% endif %} {% endblock %} I can't see the "newEquipment" button even though the adminStatus context is …