Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Date saving lesser than one hour of previous day instead of actual date in Django 3
here i am using Django 3 and python 3.7 Here i am giving start_date as 06/07/2022 end_date as 31/07/2022 but in my database it is saving as start_date end_date 2022-07-05 18:30:00 2022-07-30 18:30:00 As you can see its saving one day lesser here is my settings.py TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True And in my terminal when i run the command timedatectl Here is my views.py class AssignmentUpdateView(UpdateView): model = Assignments form_class = AssignmentForm context_object_name = "assignments" template_name = 'contract_worker/assignment_form.django.html' def get_context_data(self, **kwargs): # self.contact = self.request.GET.get('contact_id') context = super(AssignmentUpdateView, self).get_context_data(**kwargs) context["is_update_view"] = True return context def get_form_kwargs(self): kwargs = super(AssignmentUpdateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client kwargs["method"] = self.request.method return kwargs def get_queryset(self): self.client = self.request.user.client return self.model.objects.filter(client=self.client) def form_valid(self, form): self.object = form.save(commit=False) self.object.client = self.request.user.client try: self.object.save() messages.success(self.request, 'Assignment updated successfully.') except BaseException as e: logger.exception(e) messages.error(self.request, 'Failed to update the Assignment.') return redirect(self.get_success_url()) def get_success_url(self): return reverse('contract_worker:assignment_list') Here is my forms.py class AssignmentForm(forms.ModelForm): start_date = forms.DateField(widget=McamDateInput(format='%d/%m/%Y'), input_formats=['%d/%m/%Y'], required=False) end_date = forms.DateField(widget=McamDateInput(format='%d/%m/%Y'), input_formats=['%d/%m/%Y'], required=False) agency = forms.CharField(required=True) agency_id = forms.CharField(widget=forms.fields.HiddenInput()) customer = forms.CharField(required=True) customer_id = forms.CharField(widget=forms.fields.HiddenInput()) class Meta: model = Assignments fields = ['assignment_name', 'assignment_id', 'contact_worker', 'assignment_status', 'auto_generate', 'contract_type', 'worker_type', 'worker_status', 'job_title', 'start_date', … -
Admin panel django model
I have two models: Product and Rating. Product model is a foreign key in Rating. I want to do the following in the Django admin panel:On Clicking the Rating model, all the products should appear at first. And when I click on any product all the rating objects related to that product should arise. Here are the models: class Product(models.Model): product_name = models.CharField(null=True, blank=True, max_length=200) product_cost = models.BigIntegerField(null=True, blank=True) product_size = models.BigIntegerField(null=True, blank=True) class Rating(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) rating = models.IntegerField(null=True, blank=True) added_on = models.DateTimeField(null=True, blank=True) I am new to python Django please help me. -
How to attach a foreign key while saving a form into a model?
I have a model for a blog site which contains 4 fields -post_author,post_title,post_content and date_published. Also, I have a form to add a new post which has 2 fields post_title and post_content. But while I try to add a new post, it shows Error:NOT NULL constraint failed: blog_post.author_id My date field in the model is supposed to fill automatic but the User-id which is a foreign key isn't getting filled. How am I supposed to attach user_id while saving the form? post model: class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title form for new post: class newPost(forms.ModelForm): title = forms.CharField(required =True, max_length=30) class Meta: model = Post fields = ['title','content'] view function: @login_required def newpost(request): if request.method == 'POST': post = newPost(request.POST or None) if post.is_valid(): #how to add author of this post ?? post.save() messages.success(request,f'New blog post added. Add more if you want') return redirect('blog-newpost') else: post = newPost() context = {'title':'New Post','post': post} return render(request,'blog/newpost.html',context) -
How to add Custom fields in User model in django?
I am creating a website where I need extra information from the user when registering into the website , e.g.(he has a pc or not, subscribed to newsletter or not, email, phone number and password confirmation) note: is there a way that I can make in way that a react developer can use this model ? -
Error while editing data in CRUD operation using Serializer
I am writing a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to edit the data of sub Categories it throws the error "The view sub_categories.views.edit_sub_categories didn't return an HttpResponse object. It returned None instead." below are the models of categories and subcategories class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=10) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories, on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) below are the edit_sub_categories functions and its html def edit_sub_categories(request,id): if request.method == 'GET': editsubcategories = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(editsubcategories) return render(request,'polls/edit_sub_categories.html',{"SUBCategories":s.data}) editsubcategories = {} d = SUBCategories.objects.filter(id=id).first() if d: editsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') editsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') print(editsubcategories) form = SUBCategoriesSerializer(d,data=editsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('sub_categories:show_sub_categories') else: print(form.errors) HTML code <form method="POST" > {% csrf_token %} <table> <!--content-table--> <thead> <tr> <td>Sub Categories ID</td> <td><input type="text" name="id" value="{{SUBCategories.id}}" readonly></td> </tr> <tr> <td>Categories Name</td> <td><input type="text" name="category_name" value="{{SUBCategories.category_name}}"></td> </tr> <tr> <td>Sub Categories Name</td> <td><input type="text" name="sub_categories_name" value="{{SUBCategories.sub_categories_name}}"></td> </tr> <tr> <td>Sub Categories Description</td> <td><input type="text" name="sub_categories_description" value="{{SUBCategories.sub_categories_description}}"></td> </tr> <tr> <td> <!-- <input type="submit" value="update record"> --> <a href="{% url 'sub_categories:show_sub_categories' %}"> … -
Не знаю, как исправить ошибку, Error: Unknown option '--output'
совсем не понимаю, как исправить, если webpack --help пишу, то неизвестна команда webpack. (backend-T508Vxs4-py3.9) olesyakhurmuzakiy@MacBook-Air-Olesya backend % npm webpack --version 8.13.2 (backend-T508Vxs4-py3.9) olesyakhurmuzakiy@MacBook-Air-Olesya backend % npm run dev > backend@1.0.0 dev > webpack --mode development .frontend/src/index.js --output ./frontend/static/frontend/main.js [webpack-cli] Error: Unknown option '--output' [webpack-cli] Run 'webpack --help' to see available commands and options -
How to change a global variable on settings.py for a dynamic variables based on dropdown on Django?
I have the issue about how to replace a global variable (on settings.py) set on many places on Django project, instead, I want to use a variable that only change once on a dropdown at the beginning on the project, thanks in advance! What is the best practice to make it properly? -
How can I verify jwt using "djangorestframework-simplejwt"
I am beginner in drf (Django rest framework), and now I'm making authorization logic with JWT. I heard that djangorestframework-simplejwt is most famous library in drf. I saw docs, but there are no way to verify token. (exactly i cannot find it :( ) thank you. -
My website didn't show css and Django nor python didn't run
I use VPS hosting and yes I'm learning about hosting using Django and VPS. First I set this DEBUG = False ALLOWED_HOSTS = ['*'] I followed the instruction this forum and I think I succeeded because it shows I need to install as I do in VisualStudio but when reviewing my site it renders as a plan HTML This is my picture -
javascript is not working on the back-to-top button on the blog page only
I have my Back-to-top button every pages and all the html, css and javascript is on the base file in django. Bact-to-top button is working as expected in all the pages except the blog page when it is not showing up because javascript is not working on it. I don't know why. Please help if you can. below code is the base-footer file:- {% block footer %} {% load main %} {% load static %} <style> html { scroll-behavior: smooth; } footer .back-to-top .bttBtn { display: flex; align-items: center; justify-content: center; text-decoration: none; opacity: 0; z-index: 2; } footer .back-to-top .bttBtn.active { opacity: 1; } footer .back-to-top .bttBtn.active:hover { cursor: pointer; background: #fa6742; border-color: #fa6742; } </style> <footer class="footer mt-30" style="position: relative; margin-top: 200px; text-align: center" > <div class="container" style="text-align: right"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="item_f1"> <a href=" {% url 'main:aboutUs' %} ">About Us</a> <a href=" {% url 'media:ourBlog' %} ">Blog</a> <!--<a href=" {% url 'media:press' %} ">Press</a>--> </div> </div> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="item_f1"> <a href=" {% url 'main:help' %} ">Help</a> <a href=" {% url 'main:helpFAQ' %} ">FAQ</a> <a href=" {% url 'main:feedback' %} ">Feedback</a> </div> </div> <div class="col-lg-3 col-md-3 col-sm-3"> <div class="item_f1"> <a href=" … -
export admin data to sql or csv
In django admin, I visualize data from several models as seen in the below image: enter image description here Would it be possible to export this data to sql or json or csv? I tried to use the django import_export library but it exported only data belonging to one of the models and not all fields and foreign keys. -
Are there any packages in laravel like DjangoRestFramework in Django?
I am a Django developer. I am working with it for a year now. I use DRF for my APIs. I am planning to switch to laravel for a project. Is there anything like DRF in laravel that I can use to easily create the APIs? -
How I can fetch a sp of sql server in django with calling a parameter
I'm very amature in django. And Now I wanna fetch a sp of my database(sql server) with calling one its parameter? Help and guide me please... Tnx alot -
Django - Hide server name in css/js file response
Delete 'Server' response header in Django framework - V3.0.5 The solution given in the above link didn't work. If you click on img/css/js file and see the response header. The server name is visible there. -
Redis server starts behaving erratically and stops functioning properly. Causing other services to malfunction
I have a docker-compose file with 4 containers, one of which is Redis. The image builds up properly and runs properly initially but after some time (sometimes it happens within 10 minutes or sometimes after a few hours) the Redis start throwing errors and my container 'worker' fails. docker-compose.yml version: '3.7' services: web: build: context: . command: gunicorn EmotAPI.wsgi:application --bind 0.0.0.0:8000 ports: - "8000:8000" container_name: web_app depends_on: - redis worker: build: context: . command: python manage.py rqworker default depends_on: - web - redis nginx: build: ./nginx ports: - "80:80" depends_on: - web redis: image: "redis:latest" restart: always ports: - "6379:6379" command: redis-server --save 20 1 --loglevel warning volumes: - redis:/data volumes: redis: driver: local redis error log (after which functions start to fail) 1:S 06 Jul 2022 08:03:53.556 # Failed to read response from the server: Connection reset by peer 1:S 06 Jul 2022 08:03:53.556 # Master did not respond to command during SYNC handshake 1:S 06 Jul 2022 08:03:54.567 # Failed to read response from the server: Connection reset by peer 1:S 06 Jul 2022 08:03:54.567 # Master did not respond to command during SYNC handshake 1:S 06 Jul 2022 08:03:56.509 # Wrong signature trying to load DB from … -
Amazon Linux2 AMI deployment
` packages: yum: python3-devel: [] mariadb-devel: [] mesa-libGL: [] gcc: [] libcurl-devel: [] amazon-linux-extras: [] option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: eagle_eye.settings PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: eagle_eye.wsgi:application container_commands: 01_make_migrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true 03_createsuperuser: command: "source /var/app/venv/*/bin/activate && python3 manage.py create_user" leader_only: true 04_static: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput" leader_only: true 05_redis: command: "sudo amazon-linux-extras enable redis6 && sudo yum -y install redis" leader_only: true 06_metadata: command: "sudo yum clean metadata" leader_only: true 07_celery: command: "sudo systemctl start redis" leader_only: true ` I am deploying Django application that makes use of celery for queuing.How to install redis package via .ebextension file.In .ebextension file I am specifying amazon-linux-extras: [].Can anyone help me out. -
How to Store the Data in Database from dropdown in Djngo
Here is my code I am working on student management project and I am unable to get the branch for student as it is foreignkey of Course model to Student model and I want to get the selected option into student model in branch row models.py class Course(models.Model): id=models.AutoField(primary_key=True) course = models.CharField(max_length=50) course_code = models.BigIntegerField(null=True) def __str__(self): return self.course class Student(models.Model): id=models.AutoField(primary_key=True) user=models.OneToOneField(User,on_delete=models.CASCADE) branch=models.ForeignKey(Course,on_delete=models.CASCADE,null=True,blank=True) middle_name=models.CharField(max_length=50,null=True) roll_no=models.IntegerField() mobile_no=PhoneNumberField(default='') parents_mobile_no=PhoneNumberField(default='') division=models.CharField(max_length=10,null=True) batch=models.CharField(max_length=10,null=True) def __str__(self): return self.user.first_name + " " + self.user.last_name views.py def studentregister(request): if request.method == 'POST': first_name = request.POST['first_name'] middle_name = request.POST['middle_name'] last_name = request.POST['last_name'] email = request.POST['email'] branch= request.POST['branch'] division = request.POST['division'] roll_no = request.POST['roll_no'] mobile_no = request.POST['mobile_no'] parents_mobile_no = request.POST['parents_mobile_no'] pass1 = request.POST['password'] pass2 = request.POST['confirmpassword'] if pass1 == pass2 : if User.objects.filter(email=email).exists(): return HttpResponse('User already exsits') else: user = User.objects.create_user(email=email, password=pass1, first_name=first_name, last_name=last_name) user.save(); studentdetails = Student ( user=user, middle_name=middle_name,roll_no=roll_no,mobile_no=mobile_no,parents_mobile_no=parents_mobile_no, branch=branch,division=division) studentdetails.save(); return render (request, 'ms/homepage/index.html') else: return HttpResponse('password does not match') else: return HttpResponse('failed') def staffstudent(request): if request.user.is_authenticated and request.user.user_type==3: courses = Course.objects.all() return render(request, 'ms/staff/student.html',{'courses':courses}) else: return render(request,'ms/login/login.html') html file as student.py <form action="studentregister" method="POST" style = "background-color:#011B3C;"> {% csrf_token %} <div class="form-group" name="branch"> <select > <option selected disabled="true">Branch</option> {% for course in courses%} <option>{{course.course}}</option> … -
Problematic error : Didn't return an HttpResponse object. It returned None instead
I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage I also tried value = "{{c.category_name}}" as well in select dropdown as well below are the models class Categories(models.Model): category_name = models.CharField(max_length=10) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) functions of sub catgeories and categories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) #print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: print(form.errors) else: insertsubcategories = {} form = SUBCategoriesSerializer(data=insertsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} if form.is_valid(): print(form.errors) return render(request,'polls/insert_sub_categories.html',hm) html of show sub_categories and insert subcategories respectively <td>category name</td> <td> <select name="category_name" id=""> {% for c in context %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>sub categories Name</td> <td> <input type="text" name="sub_categories_name" placeholder="sub categories "> </td> </tr> <tr> <td>Sub categories … -
DJANGO - How to send a user from the admin site to a custom view?
I developed an application using the framework provided by Django. I developed CRUD functions using the admin site. However, I would like to redirect a user (if click on a link or button) to another view, a customized one. In my case, if a user is on the change_list template of the admin site and clicks on a button named import file, he will be redirected to a customized view. Change_list template with import file button To do that I developed the following code in the admin.py file concerning the MeasurePoint model. admin.py: @admin.register(MeasurePoint) class MeasurePointAdmin(admin.ModelAdmin): #ALL ATTRIBUTES OF THE CLASS change_list_template = "import/import.html" def get_urls(self): urls = super().get_urls() my_urls = [ path('importFile/', self.importFile), ] return my_urls + urls def importFileView(self, request): context = dict( self.admin_site.each_context(request) ) return TemplateResponse(request, "import/import.html", context) BASE_DIR/'templates/import/importFile.html {% extends 'admin/change_list.html' %} {% block object-tools %} <form action="importFile/" method="GET"> {% csrf_token %} <button type="submit">Import file</button> </form> {{ block.super }} {% endblock %} Nothing works I'm completely lost between the admin class, the customized view importFileView, and the customized template. I have plenty of different errors. I would like to understand more about how everything works and also find a solution to what I want to do. … -
Django - model.objects.all.exists() vs model.objects.exists()
Which one would be the faster and efficient way to check if any record exists in a table? We can use either model.objects.all.exists() or model.objects.exists(). But which one should be preferred? -
Create multiple unique Owl Carousels for each image object in model
I have a model of image data for a art gallery web app I am making. The homepage displays a grid of images each with its own specific data like image name, description, price etc. When you click on an image, a modal pops up and this is where I want to generate a unique Owl Carousel that will contain more images (front, back, left, right, different angles, etc.) of that painting that was clicked. As I currently have it, no matter which painting I initially click on, only one carousel is being created in the modal which contains every single image that I added in the admin page, which is not what I want. I want to have a separate specific carousel created for each picture object that grabs that object's pictures only. Any ideas? Thank you for the help. Here is my models.py: class Portrait(models.Model): name = models.CharField(max_length= 100) painting = models.ImageField(upload_to= 'paintings') long_description = models.TextField() price = models.IntegerField() short_description = models.TextField() # these are the images that will be displayed in the carousel painting_left = models.ImageField(upload_to= 'carousel_paintings') painting_right = models.ImageField(upload_to= 'carousel_paintings') painting_top = models.ImageField(upload_to= 'carousel_paintings') painting_bottom = models.ImageField(upload_to= 'carousel_paintings') painting_back = models.ImageField(upload_to= 'carousel_paintings') # name the objects … -
Select Multiple In Django Admin Form File Upload
I currently have 2 models: class Item(models.Model): title = Models.CharField(max_length=100) ... class Photo(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='photos') photo = models.ImageField() I want to be able to have one upload file field in the admin form for the item model, and be able to select multiple images at once, which are all then uploaded to the Photo model with the associated ForeignKey to the item object. In the admin.py file i tried using inline: class PhotoAdmin(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoAdmin] class Meta: model = Item But that just gave multiple fields, rather than one field where I can select multiple images and upload them all. -
Django models error, Now I want subtract from one charfiled other, but always equal to 0, like a default,. I'm beginner with working with django
models.py -- there i create leave_links 10g field and want calculate him like substract by_projects_10g with on_facts_10g class KT(models.Model): by_projects_10g = models.CharField(max_length=255) by_projects_100g = models.CharField(max_length=255)enter code here on_facts_10g = models.CharField(max_length=255) on_facts_100g = models.CharField(max_length=255) #now I want do like this, but an error comes out leave_links_10g = models.IntegerField(default=0) def calculate_leave_links(a,b): leave_links_10g = a -b return leave_links_10g def query_links(self): calculate_leave_links(self.by_projects_10g, self.on_facts_10g) #####views.py def index(request): KT_links = KT.objects.all().values() template = loader.get_template('index.html') context = { 'KT_links': KT_links, } return HttpResponse(template.render(context, request)) -
why one of my components does not work in my django-react app?
I'm new to react and for my project i need carousel which i used react-multi-carousel package for that.after that i connected my react app to my django app with using npm run build and now the problem is that this component (named it slider.js )dosen't work fine it just render the buttoms but not images and even styles of it i but it's work just fine in react didn't find solutions by my searches heres the project directory tree and heres the view of how my component looks like and django static in settings.py: STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, '../frontend/build/assets')] and in fronted/build/index.html: <!doctype html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"/> <link href="favicon.ico"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="theme-color" content="#000000"/> <meta name="description" content="Web site created using create-react-app"/> <link href="./logo192.png"/> <link href="./manifest.json"/> <link type="text/css" href="{%static 'styles.css' %}" rel="stylesheet" > <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" > <title>React App</title><script defer="defer" src="{% static 'js/main.891355db.js'%}"> </script> <link href="{% static 'css/main.450b181d.css'%}" > </head> <body style="padding:0;margin:0"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> </body> </html> -
request.user not available in Streamblocks subtemplate
In my main template I can call: {% load static wagtailuserbar wagtailcore_tags %} {% load navigation_tags %} {% if request.user.is_authenticated %} You're logged in {% endif %} but if I call this in my StreamBlock sub-template, it doesn't work. {% load wagtailcore_tags wagtailimages_tags %} {% if request.user.is_authenticated %} <div class="container"> ... </div> {% endif %} Any ideas?