Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create form using foreign keys and inlines
I am just trying to make an polling app and just want to have a simple HTML page where I can have poll_text and 3/4 choice_text fields. currently my models looks like following #models.py class Poll(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True ) poll_text = models.CharField((""), max_length=250) pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.poll_text class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, default = '') choice_text = models.CharField( max_length=200) no_of_votes = models.IntegerField(default = 0) def __str__(self): return self.choice_text and this is how my forms.py looks like. #forms.py from django.forms import ModelForm from .models import Poll, Choice class CreatePollForm(ModelForm): class Meta: model = Poll fields = ('poll_text',) and finally the admin.py, looks like this, this gives me correct presentation in localhost/admin, and that presentation I want in a HTML page. #admin.py from django.contrib import admin from .models import Poll, Choice from django.contrib.auth.models import User # Register your models here. class ChoiceInLine(admin.TabularInline): model = Choice extra = 5 class PollAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ('user','poll_text',)})] inlines = [ChoiceInLine] please guide me what changes needs to be made, also please suggest how can i tweak my model to have a record of that an user has voted this poll. -
How to call a function after ALL Django apps have started
I want to load a number of classes I've put in a module that's not part of the settings.INSTALLED_APPS list. (I want my customers to be able to write their own subclasses which can be dynamically loaded or reloaded.) I have a function called load_classes() to do so. The question is where to call it when my project initially starts. My first attempt at this was placing load_classes in the ready() function of AppConfig as per this question, but that apparently only is invoked after the particular app with the AppConfig is done loading, not all of them. Since these class definitions import models and functions from other apps in the project, I ended up with this error: File "/Users/dylan/.local/share/virtualenvs/pipeproj-oDyHbVBN/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Where can I place my importing code, so it's triggered once all of the Django apps have been loaded? -
Request failed with status code 401 for React Native Expo on IOS only but working everywhere else
I am working with a React Native with the Expo SDK. im having issues with IOS Simulator when Fetching ApI (GET Request) i Have tried PostMan and on Android it is working very fine but on IOS it just throws Running application on iPhone 11. Request failed with status code 401 - node_modules/axios/lib/core/createError.js:15:17 in createError - node_modules/axios/lib/core/settle.js:16:9 in settle - node_modules/axios/lib/adapters/xhr.js:52:6 in handleLoad - node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:567:4 in setReadyState - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse - node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0 - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue * [native code]:null in callFunctionReturnFlushedQueue below is my function for GET Request on const token = await AsyncStorage.getItem("userToken"); auth_token = 'Token ' + token axios .get("http://127.0.0.1:8001/api/user-info", { headers: { "Authorization": auth_token, } }) .then(function (response) { console.log(response) const groupData = {}; groupData["groupName"] = response.data.user.group; groupData["userName"] = response.data.user.username; groupData["jobTitle"] = response.data.user.job_title; console.log(groupData); groupName(groupData); }) .catch(function (error) { console.log(error) }); also i did debug request im getting on fetch , i somehow know that Authorization is not there in request.headers here's my request.headers, Authorization is not there {'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate', 'Host': '127.0.0.1:8001', 'Content-Type': 'application/json;charset=utf-8', 'Content-Length': '47', 'Connection': 'keep-alive', 'Accept-Language': 'en-us', 'User-Agent': 'Expo/2.16.0.108985 CFNetwork/1128.0.1 … -
Django-admin grant and revoke permissions
hey guys can i grant and revoke permissions of objects of models in django admin if so how can i do that? i have Profile model and in admin Groups i have admin and departmentHead groups the thing is i want the departmentHead to only have permission of his own department users. the model is the following. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) Male = 'M' Female = 'F' Gender = [ (Male, 'M'), (Female, 'F'), ] gender = models.CharField(max_length=1, choices=Gender, default="",) image = models.ImageField(default='default.jpg', upload_to='profile_pics', blank=True, null=True) department = models.ForeignKey(Departments, default="", on_delete=models.CASCADE, blank=True, null=True) classLevel = models.ForeignKey(ClassLevel, default="1", on_delete=models.CASCADE, blank=True, null=True) semester = models.ForeignKey(Semester, default="1", on_delete=models.SET_DEFAULT, blank=True, null=True) specialization = models.ForeignKey(Specialization, default="", on_delete=models.SET_DEFAULT, blank=True, null=True) date_registered = models.DateTimeField(default=timezone.now) is_online = models.BooleanField(default=False) def __str__(self): return self.user.username def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Meta: verbose_name_plural = "Profile" -
Form validation error not showing in the HTML page in Django
I am developing a simple sign up and sign in web application in Django. I am using Django form for the user inputs. I write the clean function in the forms.py file. If username already exist in the database it should display the error message in the HTML page but nothing display on the webpage, can someone find out the mistake in my code. Here is my code: view.py def RegistrationView(request): form=Registration_Form() if request.method=='POST': form=Registration_Form(request.POST) if form.is_valid(): form.save() return redirect('login_view') else: # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } def clean_username(self): user_name=self.cleaned_data['username'] if User_Registration.objects.filter(username=user_name).exists(): raise forms.ValidationError("Username Already Exist") registration.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <div class="form-group"> <br><br><br> <h2 style="padding-left: 480px;">Registration Form</h2> <br> <form method="POST" action=""> … -
How to filter the related many-to-many field in Django admin screen in a self referencing scenario of Django Models
I have written a Django Model called Job. I tried self referencing the Job Model and created a Many To Many field. A job can have other jobs as dependencies, But it cannot have dependency on itself. In the Django Admin page for Job, what I am expecting to see was a multi select field without the job which is currently in edit mode. Basically I cannot add the same object as its dependent. I am trying to somehow filter out the multi select field in Django Admin page to display only the other jobs and it should not include the same job which is under editing. If I allow it, it may create a circular dependency and my program wont work as expected. This problem occurs only when editing the object, when creating the object, this problem wont occur because the job was not yet created. Any help on filtering the related self referencing many to many field will be appreciated. Here is my Model code: class Job(models.Model): name = models.CharField(max_length=100,blank=False,null=False) job_category = models.ForeignKey(to=JobCategory,on_delete=models.CASCADE,null=False,blank=False) additional_arguments = models.CharField(max_length=100,blank=True) **dependencies = models.ManyToManyField(to="self",symmetrical=False,blank=True)** active = models.BooleanField(default=True,null=False) Admin Screen Screenshot for the Job Model -
How to Pass Data from Model into Chart JS - Django
I am attempting to pass user submitted data from a django model form into a Chart.js chart that renders on a detail view page. I am having trouble figuring out why I cannot call values from an instance of the model form submission in my views.py and subsequently pass that to the js which renders the chart. When I hardcode values into my class-based view defined variables for TAM and LTM_sales the chart renders. Please see code below: Models.py: class Strategy(models.Model): total_addressable_market = models.IntegerField(blank=True, null=True) last_twelve_months_sales = models.IntegerField(blank=True, null=True) Views.py def strategy_detail(request, id): strategy = get_object_or_404(Strategy, id=id) .... context ={ 'strategy': strategy, .... } return render(request,'hypo_app/strategy_detail.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, default=None): strategy = Strategy.objects.all() TAM = strategy.total_addressable_market LTM_sales = strategy.last_twelve_months_sales labels = ['TAM', 'LTM Revenue'] default_items = [TAM, LTM_sales] data = { "labels": labels, "default": default_items, } return Response(data) URL from django.urls import path from .views import UserExperimentListView, ChartData from . import views urlpatterns = [ .... path('chart_data/', ChartData.as_view(), name='chart_data'), ] JAVASCRIPT <script> {% block jquery %} var endpoint = '/chart_data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default … -
Django cookie banner: window.wpcc undefined
On my GitHub pages website, I have been using https://www.websitepolicies.com/ to create a simple cookie consent banner. Trying to use the same snipped in my new Django app does not work however. The HTML code for the banner goes into the HTML head and looks like <link rel="stylesheet" type="text/css" href="https://cdn.wpcc.io/lib/1.0.2/cookieconsent.min.css"/> <script src="https://cdn.wpcc.io/lib/1.0.2/cookieconsent.min.js" defer></script> <script>window.addEventListener("load", function(){window.wpcc.init({"border":"thin","corners":"small","colors":{"popup":{"background":"#f6f6f6","text":"#000000","border":"#555555"},"button":{"background":"#555555","text":"#ffffff"}},"position":"bottom","transparency":"10","content":{"href":"https://www.websitepolicies.com/policies/view/<hashcode_to_my_policy>"}})});</script> Adding this to the head of base.html inside my Django app doesn't work. No banner is displayed and instead, the console logs the error: Loading failed for the <script> with source “http://wpcc.io/lib/1.0.2/cookieconsent.min.js”. Uncaught TypeError: window.wpcc is undefined Why is the snipped working fine with my GitHub pages site but not with my Django app? Why can http://wpcc.io/lib/1.0.2/cookieconsent.min.js not be loaded? If I copy it into the address bar, it loads. -
webpush django with pywebpush
I wrote the following simple code to send web push messages to an Angular application: profile = Profile.objects.filter(user__id=1).first() subscription_info = { "endpoint": profile.notification_url, "keys": { "auth": profile.auth, "p256dh": profile.p256dh } } data = {"notification":{"title":"Notifications","body":"Test","icon":"https://www.shareicon.net/data/256x256/2015/10/02/110808_blog_512x512.png","vibrate":[100,50,100],"data":{"url":"https://x.com"}}} webpush(subscription_info, data,, vapid_private_key="valid_key", vapid_claims={"sub": "mailto: x@gmail.com"}) Upon executing this I get the following error back: content[i:i + chunk_size], TypeError: unhashable type: 'slice' Changing the 'data' variable to just a string like 'test' it is able to execute properly but then my Angular application in Google Chrome gives me the following error: ngsw-worker.js:2031 Uncaught SyntaxError: Unexpected token T in JSON at position 0 How can I send a web push notification to Angular (in Chrome) using pywebpush ? -
Nginx : How to serve index.html and static contents with a single internal directive
I want to display my documentation (a single-page application built with React) only after authentication with my backend. My configuration : Nginx acts as a reverse proxy for the backend (Django) and serves static files like single-page-applications. Django, the backend, identifies the user and makes a request to Nginx using X-Accel-Redirect. So I proceed as follows: 1) Authentication on Django views.py def get_doc(request): if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] == 'foo': response = HttpResponse() response['Content-Type'] = '' response['X-Accel-Redirect'] = '/docs-auth/' return response else: return HttpResponse("Wrong password") else: form = PasswordForm() return render(request, 'docs/form.html', {'form': form}) urls.py urlpatterns = [ path('docs/', views.get_doc, name='documentation'), ] 2) Nginx serves the single-page application upstream backend { server web:8000; } server { location = /favicon.ico {access_log off;log_not_found off;} ... location /docs { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://backend; } location /docs-auth/ { internal; alias /home/foo/docs/; index index.html; try_files $uri $uri/ /docs/index.html; } location / { alias /home/foo/landing_page/; error_page 404 /404.html; index index.html; try_files $uri $uri/ =404; } } My problem is that the index.html file is served to the user but then the browser requests to access CSS and Javascript files are blocked because the browser … -
Cannot resolve keyword 'user' into field
I give views.py file & error file picture.Help me to solve the problem. enter image description here -
How to show user posted blog in user profile page as a my post list section in Django 3?
I am a new Django learner. I have created a blog website with two apps blog and user. In the user app, I have created a user profile page with two section user basic information and my post list. When user login and visit his/her profile page, my post list section shows only this user published post else shows you have not published any post yet. Everything is working fine but my post list section shows all of the posts in the blog. I want to show only this user's post, not other users' posts. I think the queryset in the view section needs to be modified but I cannot understand what would be. Here is my code - #Blog App: Post Model class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title #User App: Profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) pic = models.ImageField(default='images/default.jpg', upload_to='images') about = models.TextField(blank=True) #User App: views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView from blog.models import Post class UserProfileView(LoginRequiredMixin, ListView): queryset = Post.objects.all() template_name = "profile.html" … -
Custom ModelAdmin filter on calculated field
Example I'm trying to emulate: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filtering_calculated_fields.html FieldError at /admin/gallery/galleryitem/ Cannot resolve keyword 'on_sale' into field. Choices are: content_type, content_type_id, depth, description, direct_sale, direct_sale_extra_description, direct_sale_price, draft_title, expire_at, expired, external_links, first_published_at, formsubmission, gallery_images, go_live_at, group_permissions, has_unpublished_changes, id, index_entries, last_published_at, latest_revision_created_at, live, live_revision, live_revision_id, locked, locked_at, locked_by, locked_by_id, numchild, owner, owner_id, page_ptr, page_ptr_id, path, redirect, revisions, search_description, seo_title, show_in_menus, sites_rooted_here, slug, stock, title, url_path, view_restrictions, workflow_states, workflowpage models.py class GalleryItem(Page): parent_page_types = ['InstallationPage'] description = models.CharField(blank=True, max_length=250) direct_sale = models.BooleanField("On Sale", default=False, help_text="Check this box to list this item for sale directly on your website.") direct_sale_price = models.DecimalField("Sale price, $", blank=True, null=True, max_digits=6, decimal_places=2, help_text="Add more info about this item for the store page only.") direct_sale_extra_description = models.CharField("Addtional sale description (optional)", blank=True, max_length=250, ) stock = models.IntegerField("Number in stock", blank=True, null=True,) def external_sale(self): return bool(self.external_links.count()) def on_sale(self, obj): return obj.external_sale or obj.direct_sale class ExternalLink(Orderable): gallery_item = ParentalKey(GalleryItem, on_delete=models.CASCADE, related_name='external_links', help_text="Add details about the listing, ex. dimensions, framing.") description = models.CharField(blank=True, max_length=250) external_sale_url = models.URLField(blank=True, help_text="Add an external link to sell this.") wagtail_hooks.py class OnSaleFilter(SimpleListFilter): title = 'On Sale' parameter_name = 'on_sale' def lookups(self, request, model_admin): return ( ('Yes', 'Yes'), ('No', 'No'), ) def queryset(self, request, queryset): value = self.value() if value == 'Yes': … -
How to exclude value that is equal to zero while using Django aggregate queries for average or minimum
I have a database table where some of the values in a column for sales are zero. So far my query returns the min of all the values. Sale.objects.all().aggregate(minimum=Min('sale')) I want to exclude the values that are equal to zero while calculating the minimum or the average. So my question is how is that query done? -
Django or Node.js or GoLang for backend developer career?
I'm new in software development and want to become FULL STACK DEVELOPER, what technology should i learn Django or Node.js or GoLang or Angular for backend development so that i can get stable job and career in this area ? -
aadsts50011: the reply url specified in the request does not match the reply urls configured for the application: 'App id'. localhost configuration
I Followed this document for setting up the Microsoft Auth system by stuck up with error aadsts50011 this the image of my App in Azure portal -
Reduce the number of products after customer payment
I have a problem with reducing the amount(number) of products after the end payment of the user. The program I wrote reduces the number of products when the shopping cart is created, but if the user cancels the payment, I will have a problem and the number of products will decrease even though the user has not paid. I am looking for a way to reduce the number of products after payment by the user code -
cant save django model object in database
I use request.POST content to save a model object after creating and authenticating a user. the problem is that my user is created and authed but the model which extends that very users information in database is not saved while no error given. here is my code: @api_view(['POST']) @permission_classes((permissions.AllowAny, )) def login_api(request): post = request.POST user = authenticate( request, username=request.POST['username'], password=request.POST['password'] ) if user: school = school_info.objects.create( school_user=request.user, school_name=post['school_name'], school_manager_name=post['school_manager_name'], school_manager_phone=post['school_manager_phone'], class_count=post['class_count'], students_per_class=post['students_per_class'], daytime_importance=post['daytime_importance'], ) school = school.save() login(request, user) return Response({}, status=200) else: return Response({}, status=401) I tried ModelForms and obj.create().save() too but both of them aren't working. any answer would be appreciated. -
How to structure django models
I'm creating a website where users can post briefs and submit their work for them. The user will submit their design from the corresponding brief page. So far I have Users and Briefs in their own respective tables. Would the best approach be to create a new table which stores the brief id and the users submitted design? My idea is to create a table with user id and brief id as foreign keys and then the work. How would I then filter the table to only show the designs for the brief page the user is viewing. Thanks -
View file after payment in Django
I want to create a file store with the Django framework, but I can not click to download a specific file after paying for it online -
Unable to add data to databse from models forms django
I am trying to send data from django forms to backend sqlite3. But I am unable to do so. I am not also getting any error or warning that help me to sort it out. Here is models.py file from django.db import models GENDER_CHOICES = [ ('Male', 'M'), ('Female', 'F')] class upload(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) phone = models.CharField(max_length=50,null=True) email= models.EmailField(max_length=50,null=True) file=models.FileField(upload_to='uploads/') def __str__(self): return self.name here is forms.py file from django.forms import ModelForm from .models import upload class uploadForm(ModelForm): class Meta: model = upload fields = ['name', 'gender', 'phone', 'email','file'] Here is view.py file from django.shortcuts import render from .forms import uploadForm from django.shortcuts import render def home(request): if request.method == 'POST': form = uploadForm() if form.is_valid(): form=form.save() return HttpResponseRedirect('/') else: form = uploadForm() return render(request,'home.html',{'print':form}) I am unable to understand where is the issue This is how template file look like <form method="post"> {% csrf_token %} {{ print.as_p }} <input type="submit" value="Submit"> </form> -
How to prevent authenticated users from making direct API request (Django rest framework)
When a Django Rest Framework Site is hosted, can authenticated users make direct request to the api .. or does CORS prevent them? -
Django + Discord.py
Hi I just quickly wanted to ask if there's any way I could make a bot panel on a website using discord.py and django, javascript or PHP. I know it might be easier with discord.js but I personally hate discord.js and node in general. -
Django model extra fields added by the user
The model will ask for personnels names and qualifications which are both text fields but the amount of personnel will vary from instance to instance. How can I let the user add a field to the model? Here's my model currently: class ShiftReport(models.Model): work = models.ForeignKey(Work, null=True, on_delete=models.CASCADE) work_description = models.TextField(max_length=500) handover = models.BooleanField(default=False) weather_conditions = models.TextField(max_length=100) start_time = models.DateTimeField() end_time = models.DateTimeField() noms_number = models.TextField(max_length=40) noms_phase_addition_number = models.TextField(max_length=5) personnel_name = models.TextField(max_length=100) personnel_qualifications = models.TextField(max_length=100) personnel_name_2 = models.TextField(max_length=100) personnel_qualifications_2 = models.TextField(max_length=100) I would like to be able to let the user add in as many personnel names and qualifications as they want to. class ShiftReport(models.Model): work = models.ForeignKey(Work, null=True, on_delete=models.CASCADE) work_description = models.TextField(max_length=500) handover = models.BooleanField(default=False) weather_conditions = models.TextField(max_length=100) start_time = models.DateTimeField() end_time = models.DateTimeField() noms_number = models.TextField(max_length=40) noms_phase_addition_number = models.TextField(max_length=5) personnel_name = models.TextField(max_length=100) personnel_qualifications = models.TextField(max_length=100) personnel_count = 1 def add_personnel(self): self.personnel_count += 1 ADDFIELD(personnel_name_{self.personnel_count}) ADDFIELD(personnel_qualifications_{self.personnel_count} Just not too sure on how to implement this. Help! -
how to populate user specific data in django
i have 2 models employee and leave ,where employee is the foreign key in leaves ..i want to display the the leave requests by a specific employee on a page when they log in. here is my code models.py class Employee(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1), MaxValueValidator(24)],default=24) def __str__(self): return self.user.username class Leave(models.Model): employee=models.ForeignKey(Employee,on_delete=models.CASCADE,default="") start_date=models.DateField(auto_now_add=False) end_date=models.DateField(auto_now_add=False) req_date=models.DateTimeField(default=datetime.datetime.now()) STATUS_OPTIONS=( ("Approve","Approve"), ("Pending","Pending"), ("Decline","Decline"), ) approved=models.CharField(max_length=10,choices=STATUS_OPTIONS,default='Pending') def __str__(self): return self.employee.user.username @property def date_diff(self): return (self.start_date - self.end_date).days views.py def home(request): user=request.user u=User.objects.get(username=user) e=Employee.objects.get(user=user.id) leave=Leave.objects.get_or_create(employee=e) print(leave) nofleaves=None if user.is_superuser: pass else: nofleaves=u.employee.no_of_leaves context={'nofleaves':nofleaves,'leave':leave,} return render(request,"leaveApp/home.html",context)