Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Response on Popover Bootstrap 4 after submit POST on Django
I have this part of the view: class Perguntas(FormView): form_class = QuestaoForm template_name = 'certificacoes/pergunta.html' template_name_result = 'certificacoes/finalizado.html' def dispatch(self, request, *args, **kwargs): self.certificado = get_object_or_404(Certificado, slug=self.kwargs['slug_certificado']) try: self.user_logado = self.request.user.is_authenticated() except TypeError: self.user_logado = self.request.user.is_authenticated if self.user_logado: self.sessao = Sessao.objects.usuario_sessao(request.user, self.certificado) return super(Perguntas, self).dispatch(request, *args, **kwargs) def get_form(self, *args, **kwargs): if self.user_logado: self.questao = self.sessao.pegar_primeira_questao() form_class = self.form_class return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): kwargs = super(Perguntas, self).get_form_kwargs() return dict(kwargs, questao=self.questao) def form_valid(self, form): if self.user_logado: self.form_valid_usuario(form) if self.sessao.pegar_primeira_questao() is False: return self.resultado_final_usuario() self.request.POST = {} return super(Perguntas, self).get(self, self.request) def form_valid_usuario(self, form): hipotese = form.cleaned_data['respostas'] is_correta = self.questao.checar_correta(hipotese) if is_correta is True: pass else: self.sessao.add_incorreta(self.questao) self.sessao.add_usuario_resposta(self.questao, hipotese) self.sessao.remover_primeira_questao() def get_context_data(self, **kwargs): context = super(Perguntas, self).get_context_data(**kwargs) context['questao'] = self.questao context['certificado'] = self.certificado return context def resultado_final_usuario(self): resultado = { 'certificado': self.certificado, 'sessao': self.sessao, } self.sessao.marcar_certificado_completo() self.sessao.delete() return render(self.request, self.template_name_result, resultado) After one question is correct, I would like to send the correct answer to the same page where the questions are. And then continue the steps that occur after this check. if is_correta is True: pass else: self.sessao.add_incorreta(self.questao) self.sessao.add_usuario_resposta(self.questao, hipotese) self.sessao.remover_primeira_questao() My template looks like this: {% extends "core/base.html" %} {% load static %} {% block content %} {% if questao … -
How to return return object(s) that gives me document as well as reports details
I have multiple documents and each document has multiple supporting reports. How do i return object(s) that provides me information of both document and the report One solution is to return all the document objects and iterate over reports for each object (slow). What I am currently doing is returning document object and I have a separate page which loads onclick and returns the corresponding reports models.py looks like this: class Document(models.Model): code = models.CharField(max_length = 50) path = models.CharField(max_length = 500) date_of_submission = models.CharField(max_length = 50) type = models.CharField(max_length = 50) title = models.CharField(max_length = 200) department = models.CharField(max_length = 50) subject = models.CharField(max_length = 100) class Report(models.Model): document_code = models.ForeignKey(Document, on_delete = models.CASCADE) title = models.CharField(max_length = 200) path = models.CharField(max_length = 500) type = models.CharField(max_length = 50) Expected: object(s) that has information for both report objects and document object. -
Why cant i add the value in this variable to my table?
I'm trying to add a variable (key) to a string(table_data) and use it in the creation of a table, my problem is that when I try to concatenate it into a string it gives me the variable name and not the value. when I print the variable on its own I get the value. when I try open the page with this table I get the error "Could not parse the remainder: '\'webapp-graphv2\' '+key+' from '\'webapp-graphv2\' '+key+'". I'm really struggling to figure this out and would appreciate some help. function populateTable(){ $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) $("#stats tr").remove(); var table_data =''; for (var key in data){ table_data += '<td><a href = "{% url \'webapp-graphv2\' '+key+'%}">Link</a></td>'; table_data += '<td>' +key+ '</td>' table_data += '<td>' +data[key].EUR.PRICE+ '</td>'; table_data += '<td>' +data[key].EUR.HIGHDAY+ '</td>'; table_data += '<td>' +data[key].EUR.LOWDAY+ '</td>'; table_data += '<td>' +data[key].EUR.MKTCAP+ '</td>'; if (data[key].EUR.CHANGEPCT24HOUR[0] == '-') { table_data += '<td style = "color:red">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>'; } else { table_data += '<td style = "color:green">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>'; } table_data += '</tr>'; } $('#stats').append(table_data); }, }) setTimeout(populateTable,1000); } -
TypeError when calling Profile.object.create in django/python
I am getting the following error when I try to create a new profile. Got a `TypeError` when calling `Profile.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Profile.objects.create()`. You may need to make the field read-only, or override the ProfileSerializer.create() method to handle this correctly. Original exception was: I am not sure why i am getting this error. I have a model and serializer and views and urls. I am not even sure where the error is coming from in the process. models.py class Profile(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) synapse = models.CharField(max_length=25, null=True) bio = models.TextField(null=True) profile_pic = models.ImageField(upload_to='./profile_pics/', height_field=500, width_field=500, max_length=150) facebook = models.URLField(max_length=150) twitter = models.URLField(max_length=150) updated = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username + self.synapse profileViews.py from users.models import Profile from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView from rest_framework.generics import DestroyAPIView, UpdateAPIView from users.api.serializers import ProfileSerializer class ProfileListView(ListAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileRetrieveView(RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileCreateView(CreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileDestroyView(DestroyAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileUpdateView(UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer urls.py from django.urls import path from users.api.views.profileViews import … -
Creating Dropdown from Model in Django
I am looking to create a dropdown in a template where the values of the dropdown come from a field (reference) within my Orders model in models.py. I understand creating a dropdown where the values are set statically, but since I am looking to populate with values stored in the DB, I'm unsure of where to start. I've created the model and attempted playing around with views.py, forms.py, and templates. I am able to get each of the order numbers to display but not in a dropdown and I am struggling with how to write my template. MODELS.PY from django.db import models class Orders(models.Model): reference = models.CharField(max_length=50, blank=False) ultimate_consignee = models.CharField(max_length=500) ship_to = models.CharField(max_length=500) def _str_(self): return self.reference FORMS.PY from django import forms from .models import * def references(): list_of_references = [] querySet = Orders.objects.all() for orders in querySet: list_of_references.append(orders.reference) return list_of_references class DropDownMenuReferences(forms.Form): reference = forms.ChoiceField(choices=[(x) for x in references()]) VIEWS.PY def reference_view(request): if request.method == "POST": form = references(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = references() return render(request, 'proforma_select.html', {'form': form}) PROFORMA_SELECT.HTML {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST"> <br> {% for field in form %} <div class="form-group row"> <label for="id_{{ … -
Django template response middleware
I'm writing some middleware for my Django application, and am stuck when trying to write the process_template_response function. I'm familiar with templates and rendering, but am puzzled as to how to pass dictionary values to the template based on some if/else statements I wrote in the process_request function. My middleware's purpose is to issue redirects based on auth status, and I need to pass a message saying 'Not authorised' when someone requests a page they are not supposed to see. Here's the middleware: import re from django.conf import settings from django.utils.deprecation import MiddlewareMixin from django.http import HttpResponsePermanentRedirect class CustomMiddleware(MiddlewareMixin): def __init__(self, get_response = None): self.get_response = get_response self.permittedPages = settings.PERMITTED_PAGES self.noLoginRequired = setting.NO_LOGIN_PAGES def process_request(self, request): request_path = request.path.lstrip('/') if request_path not in noLoginRequired and request_path in permittedPages and request.user.is_authenticated == False: HttpResponseRedirect(settings.LOGIN_URL) elif request_path not in permittedPages and request.user.is_authenticated: #if the page isn't accessible but the user is logged in not_found_message = 'This page isn\'t available, redirecting to the home page....' return HttpResponseRedirect('/home/'), not_found_message else: #if the page isn't accessible and the user isn't logged in return HttpResponseRedirect(settings.LOGIN_URL) def process_template_response(self, request): -
object of type 'method' has no len()
I am adding pagination on django, it is giving error object of type 'method' has no len() allCategoryValue = category.objects.all paginators = Paginator(allCategoryValue, 3) pages = request.GET.get('abc') try: allCategory = paginators.page(pages) except PageNotAnInteger: allCategory = paginators.page(1) except EmptyPage: allCategory = paginators.page(paginator.num_pages) context = {'allCategory':allCategory} return render(request,'addCategory.html',context) -
How to call super class dictionary and update it - Python
How to call parent class in Python and join two dictionaries Many thanks in advance. class Base(View): title = 'abc' slug = 'abc-12' def get_context(self, request): return {'title': self.title, 'slug': self.slug } class Logbook(Base) mode = 'read' def get_context(self, request) # call super class return super().add('mode': self.mode) # i want {'title': 'abc', 'slug': 'abc-12', mode: 'read' } def get(self, request) context = self.get_context(request) -
How to display foreign key objects in admin page?
For background, this is my first Django app. The basis of this assignment revolves around exploring a database. There are Areas, and within these areas are Locations. These locations reference what area they belong to via foreign key. I need to display all locations belonging to an area when on that area's "change" page. This(https://i.postimg.cc/mhfmG21C/assign07-one-area-listing.png) is what it is supposed to look like. Here is my code and what it currently looks like. I know there are methods for accessing objects related via foreign key (ModelAdmin.formfield_for_foreignkey), but I don't know how to use them. class AreaInLine(admin.StackedInline): model = Location extra = 1 class AreaAdmin(admin.ModelAdmin): #fieldsets = [(None,{'fields': ['id','name','latitude','longitude']}), # ('Locations', {'fields': ['id','name']})] inlines = [AreaInLine] This(https://i.postimg.cc/sxZT8Zx3/Capture.png) Is what it currently looks like. -
Import class from a file in an upper directory withing python / django
I have a django project and I need to import models into another folder which is in a sub directory which is in the same folder as the file I am trying to import to... I am trying to import classes from models into profileViews.py This is what I have right now: from .models import Profile here isthe directory setup -
How to make Django DateTimeField to store Pacific time with UTC format
After reading many doc, I am confused by UTC, UTC timezone and how it's used in Django. Is UTC format and UTC timezone same thing? Can UTC format store Pacific timezone date+time? I have a django project with database and UI. class FunModel(models.Model): fun_time = models.DateTimeField() What I am expecting: 1) Page 1. click a button in a browser in Pacific timezone. Server to create/store (on server side, not client to create time) 'fun_time' as Pacific time zone date + time (not UTC zone, but format is UTC format) 2) Page 2. When page 2 is loaded. it retrieves time as Pacific date + time (Not UTC zone) 3) In database, I expect to see time stored is Pacific date+time. 4) As far as my understanding, FunModel class will store time as Pacific time with UTC format. The timezone is configured in settings. ----Settings.py # Tried 'US/Pacific' as well. No difference. Date+time stored in db is the same. Really confused! TIME_ZONE = 'UTC' # Only for retrieving date from db to be Pacific by calling active(USER_TIME_ZONE)? USER_TIME_ZONE = 'US/Pacific' # With above 2 settings, date stored/retrieved will be Pacific zone automatically. Not really! USE_I18N = True USE_L10N = True USE_TZ … -
see all console log Nginx gunicorn
I run a app in django in local host and for testing my code I can see result by python manage.py runserver and see every detail in that terminal, for example in views.py I write a basic code print("****") and see the result that my codes works or not, now I moved to production from local host and I used Ngnix and Gunicorn, I want to test same thing for testing my codes, but I don't find where I should check to find the result of print("****") in views.py -
Why cant I get the value of key into my string, it keeps taking the value +key+
I'm trying to create a html table using javascript. I'm trying to add data to the table and some of the data are URL links. I'm trying to concatenate the links with variables but instead of the variable value in the String I,m getting a +key+ value. Could someone please advise me on what I'm doing wrong please javascript below function populateTable(){ $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) $("#stats tr").remove(); var table_data =''; for (var key in data){ table_data += '<tr>'; table_data += '<td><a href = "{% url 'webapp-graphv2' '+key+'%}">Link</a></td>'; table_data += '<td>' +key+ '</td>' table_data += '<td>' +data[key].EUR.PRICE+ '</td>'; table_data += '<td>' +data[key].EUR.HIGHDAY+ '</td>'; table_data += '<td>' +data[key].EUR.LOWDAY+ '</td>'; table_data += '<td>' +data[key].EUR.MKTCAP+ '</td>'; if (data[key].EUR.CHANGEPCT24HOUR[0] == '-') { table_data += '<td style = "color:red">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>'; } else { table_data += '<td style = "color:green">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>'; } table_data += '</tr>'; } $('#stats').append(table_data); }, }) setTimeout(populateTable,1000); } Where I think the error is below table_data += '<td><a href = "{% url 'webapp-graphv2' '+key+'%}">Link</a></td>'; -
I cant find my certificate when i am running ' python manage.py runserver_plus --cert /etc/ssl/cert '
i am getting filenotfound error when i am trying to access my ssl certificate because i want my local host run on https python manage.py runserver_plus --cert /etc/ssl/cert Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "E:\final3\venv\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "E:\final3\venv\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\final3\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "E:\final3\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "E:\final3\venv\lib\site-packages\django_extensions\management\utils.py", line 59, in inner ret = func(self, *args, **kwargs) File "E:\final3\venv\lib\site-packages\django_extensions\management\commands\runserver_plus.py", line 260, in handle self.inner_run(options) File "E:\final3\venv\lib\site-packages\django_extensions\management\commands\runserver_plus.py", line 337, in inner_run ssl_context = make_ssl_devcert(os.path.join(dir_path, root), host='localhost') File "E:\final3\venv\lib\site-packages\werkzeug\serving.py", line 524, in make_ssl_devcert with open(cert_file, "wb") as f: FileNotFoundError: [Errno 2] No such file or directory: '/etc/ssl\cert. -
Error while running Django Server -The empty path didn't match any of these
I am using Django to develop a web app. When I run server, I get the below error message. Error: Page not found (404) Using the URLconf defined in Mywebsite_Website.urls, Django tried these URL patterns, in this order: ^$ [name='index'] ^admin/ The empty path didn't match any of these. Any suggestions? -
How to fix 'str' object is not a mapping error
I will start saying its't a duplicated question. My problem is a little different in an url with Django 2.2. An view triggers 'str' object is not a mapping error when return HttpResponseRedirect to another view in same application. I really don't know what's wrong. I use same method in other application in same project and it works. Project urls.py urlpatterns = [ url(r'^$', Home.as_view()), path('dashboard/', include('dashboard.urls')), path('main/', include('main.urls')) ] Application urls.py urlpatterns = [ path('', views.Section.as_view(), name='main-form') ] Application views.py class Home(View): def get(self, request): return render(request, 'index.html', context={}) def post(self, request): return HttpResponseRedirect(reverse('main-form')) class Section(View): def get(self, request): return HttpResponse("Test Ok") After post home form it should redirect to main-form view (Section view class) but I get error. It triggers same error if I use the url in a template url {% url 'main-form' %} If I navigate manually to view from address bar, view renders fine. Whats wrong? -
Use Javascript to insert text into a Summernote Widget rendered using {{form.comment}}
Im using a Summernote widget for a Comment Box on my Django Form. In the HTML I'm rendering the Comment Box using {{form.comment}}. I've added a table to the page and when the user clicks a row I'd like to insert some text into the Comment Box using javascript. Does anyone know how to do this? I've not managed to find any examples using a Django Form instance and all of them use a Javascript instantiated version. I'd really appreciate the help -
How to add a subtract option to a table in Django
I am making my first application with Django. The goal is to have a table that displays the current inventory of laboratory reagents. Once a reagent is taken out of storage a user will be able to hit a subtract button to subtract from the current inventory. Currently I have a table that displays the reagent name and quantity. I would like to add a column to the table that has a subtract button that will subtract one from the corresponding reagents current inventory. Can anyone please give me some suggestions on how to implement a subtract button? Any help would be much appreciated. models.py class Reagentquant(models.Model): Name_Of_Reagent= models.TextField() Reagent_Quantity= models.TextField() tables.py class ReagentquantTable(tables.Table): class Meta: model = Reagentquant template_name = 'django_tables2/bootstrap4.html' views.py def reagentquant(request): table = ReagentquantTable(Reagentquant.objects.all()) RequestConfig(request).configure(table) return render(request, 'inventory/quant.html', {'table': table}) template {% load render_table from django_tables2 %} <!doctype html> <html> <head> <title>Inventory Tracker</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> </head> <body> {% render_table table %} </body> </html> -
Django: send error messages when the user do not POST
I am trying to send error messages when the user decides to submit the "Buy Tickets" button without POST. I am not sure if using select and option value conflicts. When I submit without POST, it sends a MultiValueDictKeyError Exception Value:'venue'. models.py class User(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email=models.CharField(max_length=100) password=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField() price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) views.py def add(request): if not 'user_id' in request.session: return redirect('/chrisgrafil') if request.method!='POST': return redirect ('/dashboard') error=False if len(request.POST['venue'])<1: messages.error(request, "Please select venue") error=True if len(request.POST['quantity'])<1: messages.error(request, "Please select quantity") error=True if len(request.POST['loop'])<1: messages.error(request, "Please select loop") error=True else: Ticket.objects.create(venue=request.POST['venue'], quantity=request.POST['quantity'], loop=request.POST['loop'], purchaser=User.objects.get(id=request.session['user_id'])) return redirect ('/confirmation') dashboard.html <form action="/add" method="POST"> {% csrf_token %} <div class="text-center"> {% if messages %} {% for message in messages %} <div class="alert alert-danger p-2 pb-3"> <a class="close font-weight-normal initialism" data-dismiss="alert" href="#"><samp>×</samp></a> {{message}} </div> {% endfor %} {% endif %} <label><strong>Location of Venue:</strong></label> <select class="form-control" name="venue"> <option value="" selected disabled>Please select</option> <option value="San Bernardino">San Bernardino</option> <option value="Los Angeles">Los Angeles</option> <option value="Riverside">Riverside</option> </select> <div class="form-group"> <label><strong>Quantity of tickets:</strong></label> <select class="form-control" name="quantity"> <option value="" selected disabled>Please select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select> </div> <div … -
Django project file - Cannot spot the mistake: "Invalid block tag: 'static'
I have the following error Invalid block tag on line 4: 'static'. Did you forget to register or load this tag? It is being generated by this code (see below) but I cannot (even after having looked through the various similar questions and answers) spot the error. <html> <head> <link rel="stylesheet" href="{% static 'wgb/styles.css' %}"/> </head> <body> <div class="login"> <h1>Login</h1> <form method="post"> <input type="text" name="u" placeholder="Username" required="required" /> <input type="password" name="p" placeholder="Password" required="required" /> <button type="submit" class="btn btn-primary btn-block btn-large">Let me in.</button> </form> </div> </body> </html> The error is obviously in this line: <link rel="stylesheet" href="{% static 'wgb/styles.css' %}"/> but I have checked for spaces, order, and spelling/syntax but none of those seem to be the problem. More specifically, the error notes: Error during template rendering and it is pointing to: <link rel="stylesheet" href="{% static 'worldguestbook/styles.css' %}"/> -
How to make sure django migration for deleting columns is done before data migration from those columns into another table
I have 2 apps in Dajngo, A and B, which each have their own models. I'm in charge of a task that moving some fields/columns from A's model to B's Before: class Amodel: fieldA = models.BooleanField(.... fieldB = models..... fieldC = ........ class Bmodel: fieldD = models...... After: class Amodel: fieldC = ........ class Bmodel: fieldA = models.BooleanField(.... fieldB = models..... fieldD = models...... This is a bit confusing how I structure this example, but Amodel and Bmodel are in DIFFERENT apps I set up 2 migration files, one in B to add new columns in table and migrate the data from A, another in A to remove these fields When I run tests, A's deletion is triggered before B's data migration. How do I deal with this? For some info that might be related: Django: 1.11 Postgres: 9.5 -
Django send message to template
I have a small Django project and Im using a user to user message system. I added in the model a new field to block users block = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='user_block') Including in html template a simple button to block or un-block users. But now I want to dislay in the messagesystem a info/warning and remove the send button when user has blocked me. Normally I would like messages like this. messages.success(request, 'You are not allowed to send messages to this user.') But in my case its not working because of request. class MessagesListView(LoginRequiredMixin, ListView): """CBV to render the inbox, showing by default the most recent conversation as the active one. """ model = Message paginate_by = 501 template_name = "messager/message_list.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) ''' sender = self.request.user recipient = get_object_or_404(User, username=self.kwargs.get('username')) if sender in recipient.block.all(): print('recipient_user is blocked') from django.contrib import messages #messages.success(request, 'You are not allowed to send messages to this user.') else: print('recipient_user is not blocked') ''' ### remove raw sql after finish ### msg_user_list = Message.objects.raw("SELECT * FROM messager_message WHERE recipient_id = '" + str(self.request.user.id) + "' OR sender_id = '" + str(self.request.user.id) + "'") users_list = "-1" for msg_user_item in … -
How to iterate over an object of queryset if the object contains more than one character and spaces?
I tried to sort the list that was input through form,but I am getting the error that Field object does not have an attribute "split". Also, without split, it says that the object is not iterable. How do I sort it without the inbuilt method ? def listform(request): form = LLForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save(commit=True) list1 = LinkedList.objects.all().last() listll=list(list1.split()) for i in range(1, len(listll)): key = listll[i] j = i-1 while j >= 0 and key < listll[j] : listll[j + 1] = listll[j] j -= 1 listll[j + 1] = key cont={'ll': listll} return render(request,'basicapp/linked.html',context=cont) else: form = LLForm() return render(request,'basicapp/listform.html',{'form':form}) -
How can I set up site-wide password protection and privilege requirements on views with Django?
My Django app is meant for internal use at the company I work at; however, it needs to be set up such that only certain employees with login credentials can access any of the web pages. Furthermore, I need to be able to customize the views so that only accounts with the right privileges can access them. How would I go about this? My gut instinct is to use the same password protection and privilege system that the admin site uses since my project is basically just meant for viewing and editing the database easily. However, Google doesn't seem to turn up any information on how to do this, and I've only been working with Django for a month and half so I don't quite have the chops to figure this out myself. Is there a way to use the admin site's password protection and privilege system or is it inaccessible? -
Django: how to include a meta tag in only 1 template
When User registers successfully, I will display a thank you page. This page will have a meta tag to redirect after 5 seconds to home. <meta http-equiv="refresh" content="5;url=http://www.example.com/"/> However, I need to place it inside the thank you page, that extends from base. Not in base, so not other pages make this redirect. thank you page: {% extends 'base.html' %} {% load staticfiles %} {% load embed_video_tags %} {% block metadescription %} {% if category %} {{ category.description|truncatewords:155 }} {% else %} ¡Bienvenidos a Stickers Gallito Perú! {% endif %} {% endblock %} {% block title %} <p>Stickers Gallito - Confirma tu correo electrónico</p> {% endblock %} {% block content %} <div class="container"> <div class="col-md-12"> <h1> ¡Gracias por registrarte! </h1> </div> </div> {% endblock %} base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Stickers Gallito Perú"> <meta http-equiv="refresh" content="3;url=http://www.google.com/"/> <meta name="google-site-verification" content="fGkwUY2RcijkVzB6DiwIuAToP1y5xw8ECXQQabRAOIM"/> <link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet"> <script src="{% static 'js/footer.js' %}"></script> </head> <body> <div class="general-container"> </div> {% include 'navbar.html' %} {% if has_shop_in_url %} {% include 'header.html' %} {% endif %} {% block content %} {% endblock %}