Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django cannot find module named XX when importing with absolute path
I have a django project with following structure project folder |- mysite |- mysite |- __init__.py |- settings.py |- ... |- myapp |- __init__.py |- abc.py |- ... |- __init__.py |- manage.py When i use relative imports, it all works fine. But when I change to absolute imports, it raise error "No module named 'mysite.myapp'. I started my script in project/mysite folder, so I thought it should search all subdirectories and found myapp module, but clearly it didn't. And I did add myapp/apps.py class into INSTALL_APPS in the settings files. So what's wrong with my codes and settings thanks -
gunicorn ImportError: No module named flask
I have an anaconda virtual environment and I have already install flask in the virtual environment using pip when I run my app using $ python app.py then it's working correctly, But when I run it with gunicorn I't showing that no module flask app.py from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello World" if __name__ == '__main__': app.run(debug=True) wsgi.py from app import app if __name__ == "__main__": app.run() $ gunicorn --bind 0.0.0.0:8000 wsgi [2019-07-23 12:39:24 +0000] [25612] [INFO] Starting gunicorn 19.9.0 [2019-07-23 12:39:24 +0000] [25612] [INFO] Listening at: http://0.0.0.0:8000 (25612) [2019-07-23 12:39:24 +0000] [25612] [INFO] Using worker: sync [2019-07-23 12:39:24 +0000] [25616] [INFO] Booting worker with pid: 25616 [2019-07-23 12:39:24 +0000] [25616] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/rahul/.local/lib/python2.7/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/rahul/test_folder/wsgi.py", line 1, in <module> from app import app File "/home/rahul/test_folder/app.py", line 1, in <module> from flask … -
Processing classes for each request vs one POST method for them?
I am migrating a project from PHP to Django. In my PHP app, the admin panel has a table, and in each row there are multiple options that it looks for and processes each one differently. So for each request in those rows, I have made a processing class for it which handles it and redirects back to the admin panel. For example, "Approve" button pressed by a user from "manager" group works differently than a user from "superadmin". Right now I have a TemplateView like this: class ProcessLeaveRequest(TemplateView): template_name = 'process_leave_request.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) My question is, should I make a POST method in this class for each request that will be coming from process_leave_request.html, or should I make a separate class for each of those requests? What is the best practice for handling multiple requests from a single page which all do different tasks? -
how to make update without updating all fields in the form
i have a django website where it include an update function that filter the data based on the selected ID and return all the related values of the requested record. where the user is allow to edit data. and fields can't be empty. the update is done only if all the fields are edited my question is how to done the update even if just one field is edit views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': first_name = request.POST['fname'] last_name = request.POST['lname'] fatherName = request.POST['fatherName'] motherName = request.POST['motherName'] gender = request.POST['gender'] content = request.POST['content'] dbEntry = suspect.objects.filter(pk = pk).first() if dbEntry: dbEntry.suspect_name = first_name dbEntry.suspect_last_name = last_name dbEntry.suspect_father_name = fatherName dbEntry.suspect_mother_name = motherName dbEntry.gender = gender dbEntry.content = content dbEntry.save() return redirect("list") print( "db entry after update: ",dbEntry) else: raise Http404('Id not found') return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' … -
How to convert Mongodb models to Django Models
I would like to know how I would represent this Mongodb model in Django. I have little familiarity with Nosql group.js const GroupSchema = mongoose.Schema({ name: String, address: String, amount: Number, admin: { type: Schema.Types.ObjectId, ref: 'User' }, scheduleType: String, ScheduleCount: Number, cycleStart: Date, code: String, members: [{ type: Schema.Types.ObjectId, ref: 'User' }], paymentSchedule : [{ recipient: {type: Schema.Types.ObjectId, ref: 'User'}, date: Date, details: [{ member: {type: Schema.Types.ObjectId, ref: 'User'}, paid: Boolean }] }] }, { timestamps: true }); user.js const UserSchema = mongoose.Schema({ firstName: String, lastName: String, phone: String, username: String, email: String, password: String, creditScore: Number, bvn: String, paid: Boolean }, { timestamps: true }); schedule.js const ScheduleSchema = mongoose.Schema({ recipient: { type: Schema.Types.ObjectId, ref: 'User' }, date: Date, }, { timestamps: true }); cycle.js const CycleSchema = mongoose.Schema({ member: { type: Schema.Types.ObjectId, ref: 'User' }, datePaid: Date, paid: Boolean }, { timestamps: true }); I would like to get representation in Django so as to be able to build my own model -
How to sum conditional expression with argument repeated in Django
I have a Queryset. How can I sum 'output' that have value jam=('16-17','17-18','18-19') develop_queryset = InputCutSew.objects.filter(publish='2019-07-30').exclude(cell_name__isnull=True).exclude(cell_name__exact='').order_by('cell_name', 'jam').values('cell_name','model','jam').annotate\ (total_output_ot=Sum(Case(When(jam='16-17', jam='17-18', jam='18-19', then='output')))).exclude(total_output_ot__isnull=True) result: SyntaxError: keyword argument repeated -
How to write api test case for generic class based views in django rest framework?
Here i am writing some api test case for some create,update views and i tried like this.But this is giving me error.What i might be doing wrong?Is there any solution for this? self.assertEqual(response.status_code,status.HTTP_200_OK) AssertionError: 403 != 200 ---------------------------------------------------------------------- Ran 2 tests in 0.031s FAILED (failures=2) Destroying test database for alias 'default'... urls.py app_name = 'product' urlpatterns = [ path('create/', ProductCreateAPIView.as_view(), name='create-product'), path('list/', ProductListAPIView.as_view(), name='list-product'), path('detail/<int:pk>/', ProductDetailAPIView.as_view(), name='detail-product'), ] views.py class ProductCreateAPIView(generics.CreateAPIView): serializer_class = ProductSerializer permission_classes = [IsAdminUser] class ProductListAPIView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAdminUser] filter_backends = [DjangoFilterBackend] filterset_fields = ['name', 'description', 'category'] class ProductDetailAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [IsAdminUser] tests.py CREATE_PRODUCT_URL = reverse('product:create-product') LIST_PRODUCT_URL = reverse('product:list-product') class CreateProductTest(APITestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.post(CREATE_PRODUCT_URL,format='json') print(response.status_code) self.assertEqual(response.status_code,status.HTTP_201_CREATED) class ListProductTest(APITestCase): def setUp(self): self.client = Client() def test_details(self): response = self.client.get(LIST_PRODUCT_URL,format='json') print(response.status_code) self.assertEqual(response.status_code,status.HTTP_200_OK) -
Calls to API Always Return “Authentication Credentials Were Not Provided” when accessed from Apple Shortcuts, but not from Postman
I’ve recently been developing a Django Application to auto-generate some schedules for me in TaskPaper form. I’ve been using django-rest-framework to automate a lot of the details of this but now I’ve come up against a problem I can’t fathom with authentication. I’m using django-rest-framework-simplejwt and the application is deployed on Heroku. When I test my app on my own machine I get the expected results, I can request the token and then using that I can request the data I want, all this is done using Postman. When I deploy the application to Heroku, and still use Postman again it all works as expected. However when I try and use Apple Shortcuts to request the data, getting the token is fine but when I try and GET the data using that token I get the error “Authentication Credentials Were Not Provided”. I looked through all the accepted answers and tried all the solutions there to no avail, so any help would be greatly appreciated and I can post any code snippets that might be required. -
Appending a col div with jQuery in a for loop only gives me results on the first row
I am retrieving an AJAX dump from a Django python Function. Then, I am trying to reflect the data on a bootstrap row + column table. However, when using append() in an array list, I only seem to get the first row of the dump. When I remove the 2nd for loop, the dump works fine, just does not give me the rows of the months that I need. I have more than one row worth of data, definitely. What could be causing this? //html code <div id="category_filtered_list"> <div class="row report_row mockup" id="category_mockup"> <div class="col-md-1 name"></div> <div class="col-md-1 code"></div> <div class="col-md-1 forecasted"></div> <div class="col-md-1 running_total"></div> <div class="monthsRows" id="monthsRows"></div> </div> </div> //Ajax JS function $.post( "", { "getcategories": true, 'date-from': date_from, 'date-to': date_to }, function(response) { $("#category_filtered_list .report_row.product").remove() data = JSON.parse(response); for (var i=0; i<data.length;i++){ obj = data[i] var mockup = $('#category_mockup') var temp_mockup = $(mockup).clone() $("#category_filtered_list").append(temp_mockup) $(mockup).attr('id',"temp_product"); var temp_prod = $("#temp_product") $(temp_prod).find('.name').html(obj.category_name) $(temp_prod).find('.code').html(obj.category_code) $(temp_prod).find('.minor').html(obj.category_minor) $(temp_prod).find('.parent').html(obj.category_parent) $(temp_prod).find('.forecasted').html(obj.category_forecasted) $(temp_prod).find('.running_total').html(obj.products_count) //this for loop is causing the issue ******* when removed, the rest of the code works fine. Please note that obj.prods_num_per_month is an array for (i=0; i<=obj.prods_num_per_month.length; i++){ $(temp_prod).find('.monthsRows').append( $('<div class="col-xs-1">').html(obj.prods_num_per_month[i]) ); } $(temp_prod).removeClass('mockup'); $(temp_prod).addClass('product'); $(temp_prod).attr('id','') } } ).done(function(){ $("#filtering .message_loading").html("Completed! <i class='far … -
How to send emails with Django for Password Reset?
I am trying to send password change link to an email address which a user will type. I typed my email but it is not sending me any link. How to resolve this issue? urls urlpatterns = [ path('password_reset/',auth_views.PasswordResetView.as_view (template_name='users/password_reset.html'), name='password_reset'), path('password_reset_done/',auth_views.PasswordResetDoneView.as_view (template_name='users/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/',auth_views.PasswordResetConfirmView.as_view (template_name='users/password_reset_confirm.html'), name='password_reset_confirm')] settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
why the update function return int where it must return string?
i have a django website where it include an update function where the user is allow to edit data. the update is done and the data in the database is changed but the problem is that the system crash. and when i tried to print the result of the query the system return int where it should return string and it display the error below : dbEntry.save() #to save into DB AttributeError: 'int' object has no attribute 'save' views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': first_name = request.POST['fname'] print("first_name : ", first_name) dbEntry = suspect.objects.filter(pk = pk).update(suspect_name = first_name) print( "db entry after update: ",dbEntry) dbEntry.save() #to save into DB return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> … -
How to use parameters defined in a triple quoted string(using eval()) outside the string in the method?
I am using triple quoted string, have if-else conditions inside the string, and defining the value of variable as per the conditions, and I am not able to use the variable outside the the string. I tried writing whole class inside of triple quoted string, and it works, I am able to use the variable outside the triple quoted string. It Works when whole class is inside the triple quote, it prints the variable 'a': import pystache codeBlock = ''' class GetData(): def foo(): a = 0 if({{c}} == 5): a = {{d}} * 5; elif({{c}} >= 5 and {{c}} < 10): a = {{d}} * 4; elif({{c}}<5): a = {{d}} * 10; return a ''' codeBlock1 = pystache.render(codeBlock, {'c': 3,'d':10}) compiledCodeBlock = compile(codeBlock1, '<string>', 'exec') eval(compiledCodeBlock) print(GetData.foo()) output: >python a.py runserver >100 And what I want is, the variable 'a' to be printed when the code block does not contain the whole class itself in the following case: (I am not sure if that's possible or not) import pystache class GetData(): def foo(): a = 0 codeBlock = ''' if({{c}} == 5): print('one'); a = {{d}} * 5; elif({{c}} >= 5 and {{c}} < 10): print('two'); a = {{d}} … -
How to implement autocomplete in django 2.2? I have tried existing one's but no support for django 2.2
I want to use autocomplete feature instead of select for my foreign key table value I have tried everything but its got compatibility issues. I need to display data in autocomplete field, rather than select field. I'm using django 2.2. -
show/hide django admin form field based on selection in another field
I am trying to have a Django admin form field to be hidden until I select a specific value from a drop-down I have tried everything including Jquery, the Jquery files load properly so my static root is pointing to the right file but when the admin site load and I change the values on the drop-down nothing happens. I am using the latest Django and python 3.7 also I am using Django-jet as a customize admin template models.py class Incident(models.Model): Incident_Type =models.ForeignKey(IncidentType,on_delete=models.DO_NOTHING, null=True, blank=False) DEM_REASON_CHOICES = (("Payments", "Payments"), ("Policies", "Policies"), ("Legal Issues", "Legal Issues"), ("Deactivation", "Deactivation")) demonstration_reason = models.CharField(max_length=200, choices=DEM_REASON_CHOICES, null=True, blank=True) admin.py @admin.register(IncidentType) class IncidentTypeAdmin(admin.ModelAdmin): @admin.register(Incident) class IncidentAdmin(admin.ModelAdmin): form = IncidentAdminForm forms.py from django import forms from .models import Incident class IncidentAdminForm(forms.ModelForm): class Meta: model = Incident widgets = { 'demonstration_reason': forms.SelectMultiple, } fields = "__all__" class Media: js = ('jet/showhide.js',) My Jquery script (function($) { $(function() { var selectField = $('#id_Incident_Type'), verified = $('#id_demonstration_reason'); function toggleVerified(value) { if (value === 'Demonstration') { verified.show(); } else { verified.hide(); } } // show/hide on load based on pervious value of selectField toggleVerified(selectField.val()); // show/hide on change selectField.change(function() { toggleVerified($(this).val()); }); }); })(django.jQuery); I am loading the script in my … -
Managing migrations with two Django apps connected to same database?
I have two servers / Django apps connected to my one MySql database, 1.example.com and 2.example.com. I want to make all the migrations on 1.example.com, and not have to update the migrations folder / models.py file in 2.example.com every time I want to make a database change. What's proper protocol here? Can I just delete models.py and migrations/ from my 2.example.com? Or is there a Django setting to be aware of. -
Error when attempting to render data to the form via HTTP request (GET)
I'm new to Django and building forms. I have several examples on how to complete a simple operations and will share the code below models.py form Django.db import models class Query(models.Model): query_name = models.CharField(max_length=40, null=True, blank=True) forms.py from django import forms from testUI.models import Query class QueryForm(forms.ModelForm): class Meta: model = Query fields = ['query_name'] views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .models import Query def queries(request): if request.method == "GET": query = Query.objects.all() return render(request, 'testUI/queries.html', {"form": query}) else: query_form = QueryForm(request.POST) if query_form.is_valid(): query_form.save() return render(request, 'testUI/queries.html', {"form": query_form}) else: return HttpResponse("Form is not valid) queries.html {% extends "testUI/base.html" %} {% block content %} <div class="page-header" style="..."> <button type="button" data-toggle="modal" data-target="#newQueryModal" class="btn btn-success" sytle="..."><i class="fas fa-plus"></i>New Query</button> </div> <div> <div class="modal-dialog modal-xl" role="document"> <table class="table"> <thead> <th>Query Name</th> </thead> <tbody> {% for query in form } <tr> <td>{{query.query_name}}</td> </tr> </tbody> </table> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }}<br> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-success">Save Query</button> </form> </div> </div> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('queries/', views.queries, name='queries') ] There is one record created using the shell. What … -
Django check files and add to DB
I would like to ask, what could be the best approach to realize something like: I will insert a pdf file to static folder in Django. After That I want Django to check if there is a new file in static folder and if is add file name to Django's sqlite. Whole process I'm trying to do: I have a calendar app in my Django site. I want to check a new pdf file in static folder and save it to that calendar app DB, so it will be as a pdf link in certain day in calendar app -
How to protect my Django code at the time of delivery to Client? [duplicate]
This question already has an answer here: How would I package and sell a Django app? 7 answers How do I protect Python code? 27 answers I have created one web application using Django framework,at the time of delivery i have to give my whole source code to client. If client have done any changes in my settings.py file my application may not work. so is there any way to hide that files? I have tried .pyc conversion of .py files but may be only for simple python files. -
How can I locally create nodes for Cassandra using Django Framework on PyCharm?
I decided to change my database to Cassandra because the website I am creating has very large dataset and currently postgres has extensive query times. From my reading, Cassandra would greatly improve scalability. However, I am not sure how to create a multinode cluster to run locally on my machine for my databases info in settings.py. I was wondering if anyone can give me directions on how to create "multiple hosts" for my settings.py file using Pycharm? Thanks -
Django: Timeout when uploading videos to AWS S3
What is the proper way to upload files to S3 from a DjangoApp hosted on Heroku? Video upload takes about 10 seconds and then I get the error. Heroku is telling me this: 2019-07-23T02:53:52.878879+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/predicas" host=el-comercio-editoriales.herokuapp.com request_id=22b60bf7-949b-4f47-bfad-dabc33df9192 fwd="47.156.66.69" dyno=web.1 connect=1ms service=30541ms status=503 bytes=0 protocol=https I suppose I need to make an upload by chunks or something. Any hint would be appreaciated. -
table row order are not updatin in the database after ajax call in django
I am using jquery UI .sortable to sort my table rows by drag and drop. I have declare a field map_order in the model as an order update. so the thing is when I am making ajax call to update the model order field. it didn't update it. but when I console log the sort variable it will show the assigning of index to the pk of model. I have tried to update the filed but it did,nt work HTML <tbody id="#layerTable"> {% for layer in layers %} <tr data-pk="{{ layer.id }}" class="ui-state-default"> <td><input type="checkbox" name="ids" value="{{ layer.id }}" /></td> <td> <a href="{% url 'mapport.maps.layers.one' map.id layer.id %}">{{ layer.name }}</a> </td> <td>{{ layer.heading }}</td> <td>{{ layer.class_group }}</td> <td> <span class="glyphicon glyphicon-resize-vertical"></span> {{ layer.map_order }}</td> <td>{{ layer.map_server }} </td> <td> {% if layer.sql_schema %}{{ layer.sql_schema }}.{{ layer.sql_table }}{% endif %} </td> </tr> JS <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $("tbody").sortable({ update: function(event, ui) { sort = {}; window.CSRF_TOKEN = "{{ csrf_token }}"; $("tbody").children().each(function(){ sort[$(this).data('pk')] = $(this).index(); }); {#var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();#} $.ajax({ url: "{% url "mapport.maps.layers.all" map.id %}sort/", type: "post", data:{sort, csrfmiddlewaretoken: window.CSRF_TOKEN, }, }); console.log(sort) }, }).disableSelection(); }); </script> views @csrf_exempt def sort(self): for index, … -
ModelChoiceField invalid literal for int() with base 10: ''
So I've spent the day trying to chase down a custom thing that I wanted to achieve using FormView. When I use FormView with HTML form method="POST", I am able to get the desired result, mostly. If a user clicks to submit a form and an empty field exists, they get an error message telling them the form is required. I'm aware that I can make the ModelChoiceField required on the form, but was trying to implement my own logic for this. I found through my searching that if I'm not updating anything via the form, form method="GET" may be more appropriate. So I switched to that, and basically got this method working, but my error logic still doesn't quite work the way I'd expect. Long story short, I can use the form method="GET", but when I try to do validation on the form, it doesn't work. Worse yet, if I try to include an empty label, that creates an invalid literal message, because based on this SO...In a Django template, how to specify a dictionary key which is itself an attribute? It doesn't seem possible to specify error logic/validation if the first field is essentially empty, which it is … -
How do I highlight a particular word from a column inside a text using django?
So let's say I have 3 columns. Text | Subject | connector Cancer is caused by windmills.| cancer, windmill| caused by These are all saved inside a postgreSQL database. How do I highlight the words, cancer and windmill (from subject) and caused by (from connector), inside the text and display it on the webpage? {% if db.cause and db.connector in db.text %} <td><mark>{{ db.text }}</mark></td> But this highlights the whole text instead of those 4 words cancer, windmill and caused by. -
How do I create a drop down menu in Django as shown below?
I'm following the instructions from the Django for Beginners book. I'm currently in chapter 13, trying to create my homepage to have a drop down nav bar in the top right and a loge with a create new article button in the top left. However, my code ends up putting the create new article button and the drop down bar both in the right. Moreover, the drop down bar does not show the expected options when I clicked on it. This is written using Django 2.x. Here's my code: <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <ul class="navbar-nav mr-auto"> <li class="nav-item"><a href="{% url 'article_new' %}">+ New</a></li> </ul> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}">Log out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary">Log in</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2 ">Sign up</a> </form> {% endif %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" … -
Django admin reuse header
I would like to reuse the header of the django admin page in my custom view so I can use the "view site, change password and logout" so I won't have to recode that part. Is it possible to extend only the header part?