Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx, gunicorn & django on amazon lightsail, what is the hostname of the ip address?
I deployed a Django application to Amazon Lightsail VPS, and it works as expected when I access it by the domain name xxxxx.com, However, if I tried to access it by the IP address, it gave an error: Invalid HTTP_HOST header: 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com'. You may need to add 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com' to ALLOWED_HOSTS. DisallowedHost at / Invalid HTTP_HOST header: 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com'. You may need to add 'ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com' to ALLOWED_HOSTS. Request Method: GET Request URL: https://ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com/` Of course, the MY-IP-ADDR-Here is my actual IP address number. I wander: Why did the lightsail change the url from 'MY.IP.Addr.Here' to ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com/? Why did the nginx proxy this request to Django? I expected it to discard the request. Is it safe to add the ec2-MY-IP-ADDR-Here.compute-1.amazonaws.com to my allowed hosts? Is it a good idea to remove MY-IP-ADDR-Here from my'settings.py`? The following are the related configuration parameters: /etc/nginx/sites-enabled/mysite server { listen 80; server_name xxxxx.com MY.IP.ADDr.Here; location / { include proxy_params; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass http://unix:/run/gunicorn.sock; } } # many lines created hy certbot # `# I added the following block to tell nginx to discard any request that doesn't match the xxxxx.com MY.IP.ADDr.Here; # https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/#allowed-hosts` server { listen 80 default_server; listen [::]:80 default_server; return 444; } myproject/settings.py … -
Does wagtail tag {% slugurl 'page' %} work with Wagtail-localize?
I'm building a website with Django, Wagtail and Wagtail Localize. But when I'm load my website on "https://exemple.com/fr/" the slugurl tags generates links like href="/en/about/" I followed settings for urls.py : urlpatterns = urlpatterns + i18n_patterns( path("search/", search_views.search, name="search"), path("", include(wagtail_urls)), ) I also added middleware and others setting like LANGUAGES. Page are correctly translated and accessible with urls. The language code is detected because tag like {% if LANGUAGE_CODE == "fr" %} is working but this slugurl never work and always display "/en/about/" : <a href="{% slugurl 'about' %}" class="nav-links">about</a> Navigation isn't very fluid, because when you access a page you have to reselect the language each time. Is slugurl supposed to work with Wagtail-localize? -
Django: psychopg2 unique violation error anyway to fix this
I was updating my django projects version from 2.1 to 2.2 and it looks like some errors occurred with my staging database (I am assuming from all the answers that look similar to my problem). I however am unsure on how to correct this without losing or corrupting the data any further. Attached are the console errors I am facing, anyway to solve these? [ubuntu@staging.internal.] out: [36;1mOperations to perform:[0m [ubuntu@staging.internal.] out: [1m Apply all migrations: [0madmin, adverts, apple_news, articles, auth, bookmarks, captcha, checkins, contacts, contenttypes, contests, custom_flatpages, events, favourites, features, flatpages, hipimagingtools, home, listings, notifications, patio_guide, photos, profiles, ratings, sessions, sites, slide_shows, streams, tastypie, team, todos, videos [ubuntu@staging.internal.] out: [36;1mRunning migrations:[0m [ubuntu@staging.internal.] out: Applying auth.0010_alter_group_name_max_length...[32;1m OK[0m [ubuntu@staging.internal.] out: Applying auth.0011_update_proxy_permissions...Traceback (most recent call last): [ubuntu@staging.internal.] out: File "/project/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute [ubuntu@staging.internal.] out: return self.cursor.execute(sql, params) [ubuntu@staging.internal.] out: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "auth_permission_content_type_id_key" [ubuntu@staging.internal.] out: DETAIL: Key (content_type_id, codename)=(114, add_djangouser) already exists. [ubuntu@staging.internal. out: [ubuntu@staging.internal.] out: [ubuntu@staging.internal.] out: The above exception was the direct cause of the following exception: [ubuntu@staging.internal.] out: [ubuntu@staging.internal.] out: Traceback (most recent call last): [ubuntu@staging.internal.] out: File "manage.py", line 14, in <module> [ubuntu@staging.internal.] out: execute_from_command_line(sys.argv) [ubuntu@staging.internal.] out: File "/project_name/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in … -
django IntegrityError: Check constraint failed: new__blog_blogpage
I'm trying to build a blog using Django(wagtail cms) and have this error now that I'm not quite sure I understand. I'm assuming it has to do with my blog model. I've been googling for a day and half with no success. Many times the results are for NOT NULL constraint or ForeignKey error, but obviously my error is something different... I'm going to post my entire blog model because of the error text: new__blog_blogpage I just kept building off the getting started tutorial from wagtail docs and much of their demo project on github. I'm just not using all that code, mainly just the blog stuff... from __future__ import unicode_literals from django import forms from django.db import models from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.fields import ParentalKey, ParentalManyToManyField from wagtail.models import Page, Orderable from wagtail.fields import RichTextField, StreamField from wagtail.admin.panels import FieldPanel, InlinePanel, MultiFieldPanel, MultipleChooserPanel from wagtail.snippets.models import register_snippet from base.blocks import BaseStreamBlock # add this: from wagtail.search import index # keep the definition of BlogIndexPage model, and add the BlogPage model: class BlogPersonRelationship(Orderable, models.Model): page = ParentalKey( "BlogPage", related_name="blog_person_relationship", on_delete=models.CASCADE ) person = models.ForeignKey( "base.Person", related_name="person_blog_relationship", on_delete=models.CASCADE ) panels = [FieldPanel("person")] class BlogPage(Page): introduction = models.TextField(help_text="Text to describe the … -
Django with datatables bootstrap 5 pagination is not working properly
I am learning Django with a sample web page. And I am trying to integrate Jquery DataTable with Bootstrap 5. The issue is, I have a total of 12 records in the DB. When I do the code and return the data to jquery, the table loads and it interpret it as a single set. So instead of showing pages 1 and 2 in the pagination, it is showing page 1 only. Giving my code below views.py def get_recipe(request): if request.method == "POST": # all_recipes = Recipe.objects.all() # data = list(all_recipes.values()) # return JsonResponse({"data": data}, safe=False) draw = int(request.POST.get("draw", 0)) start = int(request.POST.get("start", 0)) length = int(request.POST.get("length", 10)) # Default to 10 records per page search_value = request.POST.get("search[value]", "") order_column = request.POST.get("order[0][column]", "") order_dir = request.POST.get("order[0][dir]", "asc") page = start // length # Filter and retrieve data based on parameters (replace with your logic) total_data_count = Recipe.objects.all().count() filtered_data_count = total_data_count data = Recipe.objects.all()[page * length : (page + 1) * length] # Convert data to a list of dictionaries (or use a serializer) data_list = list(data.values()) # Prepare the response data response = { "draw": draw, "recordsTotal": total_data_count, "recordsFiltered": total_data_count, "data": data_list, } return JsonResponse(response, safe=False) else: return JsonResponse({"status": "error", … -
Atomic transaction with more than one model
I have a view that saves the data in two different models "Eliel_FuncionarioAlocacao" and "Eliel_FuncionarioAlocacaoCentro", however if an error occurs when creating "Eliel_FuncionarioAlocacaoCentro", it is not giving the rollback so as not to also create "Eliel_FuncionarioAlocacao", what am I doing wrong in this view? from .serializers import FuncionarioAlocacaoSerializer from auditlog.context import set_actor from client.app_eliel.models import Eliel_FuncionarioAlocacao, Eliel_FuncionarioAlocacaoCentro from django.db import transaction from microservices.serializers import ActorSerializer from oauth2_provider.contrib.rest_framework import OAuth2Authentication, TokenHasReadWriteScope from project_datafit.utils import log_error from rest_framework import status from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.exceptions import ValidationError from rest_framework.response import Response import json import re @api_view(['POST']) @authentication_classes([OAuth2Authentication]) @permission_classes([TokenHasReadWriteScope]) def funcionarioAlocacao_create_api(request): actor_serializer = ActorSerializer(data=request.data) funcionarioAlocacao_serializer = FuncionarioAlocacaoSerializer(data=request.data) try: actor_serializer.is_valid(raise_exception=True) funcionarioAlocacao_serializer.is_valid(raise_exception=True) actor = actor_serializer.validated_data['actor'] matricula = funcionarioAlocacao_serializer.validated_data['matricula'] data_inicio = funcionarioAlocacao_serializer.validated_data['data_inicio'] data_fim = funcionarioAlocacao_serializer.validated_data['data_fim'] obs = funcionarioAlocacao_serializer.validated_data.get('obs') centros_data = funcionarioAlocacao_serializer.validated_data.get('centros', []) with transaction.atomic(): with set_actor(actor): try: funcionarioAlocacao = Eliel_FuncionarioAlocacao(Matricula=matricula, DataInicio=data_inicio, DataFim=data_fim, Obs=obs) funcionarioAlocacao.save() for centro_data_str in centros_data: centro_data = json.loads(centro_data_str) centro = centro_data.get('centro') porcentagem = centro_data.get('porcentagem') Eliel_FuncionarioAlocacaoCentro.objects.create( IdAlocacao=funcionarioAlocacao, CodCentro=centro, Peso=porcentagem ) return Response({'success': 'Alocação feita com sucesso'}, status=status.HTTP_200_OK) except Exception as e: log_error(request.path, str(e), actor) return Response({'error': 'Erro ao alocar funcionário'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except ValidationError as e: error_message = str(e.detail) error_message = re.search(r"ErrorDetail\(string='([^']*)'", error_message).group(1) return Response({'error': error_message}, status=status.HTTP_400_BAD_REQUEST) I want the atomic transaction … -
ImportError in Views.py inside my django project
I am trying to import a function form a project I have made a few months ago, but I get a this error: ModuleNotFoundError: No module named 'seleniumtrack' I tried some things ChatGPT recommended and I tried to look things up on the internet, but unfortunately it didn't work. This is how my files are ordered: python/ ├── seleniumtrack.py └── tracklist/ ├── manage.py └── downloader/ └── views.py I am trying to learn Django, but here is my views.py script: from django.shortcuts import render from django import forms from django.http import HttpResponseRedirect from django.urls import reverse import seleniumtrack class SearchTracklist(forms.Form): url = forms.CharField(label="Tracklist url") class StartScraping(forms.Form): start = forms.CharField(widget=forms.HiddenInput(), initial="start") # Create your views here. def index(request): if "urls" not in request.session: request.session["urls"] = [] if request.method == "POST": form = StartScraping(request.POST) if form.is_valid(): for url in request.session["urls"]: seleniumtrack.scrape(url) else: return render(request, "tracklist/index.html", { "form": form }) return render(request, "tracklist/index.html", { "urls": request.session["urls"] }) def add(request): if request.method == "POST": form = SearchTracklist(request.POST) if form.is_valid(): url = form.cleaned_data["url"] request.session["urls"] += [url] return HttpResponseRedirect(reverse("downloader:index")) else: return render(request, "tracklist/index.html", { "form": form }) return render(request, "tracklist/add.html", { "form": SearchTracklist() }) Can somebody help? -
ckeditor is not good for django anymore
before ckeditor worked for django but now it is not working and expired. django by itself suggest non-free ckeditor 4 LTS or ckeditor 5 but I don't know how to use it please if there is give me another editor for django or guide me for this ckeditor. -
django-dbbackup: server and pg_dump version mismatch
I faced on this error. who can help me? command: python manage.py dbbackup error: Traceback (most recent call last): File "/passchain/manage.py", line 22, in <module> main() File "/passchain/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/dbbackup/utils.py", line 120, in wrapper func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/dbbackup/management/commands/dbbackup.py", line 93, in handle self._save_new_backup(database) File "/usr/local/lib/python3.10/site-packages/dbbackup/management/commands/dbbackup.py", line 106, in _save_new_backup outputfile = self.connector.create_dump() File "/usr/local/lib/python3.10/site-packages/dbbackup/db/base.py", line 92, in create_dump return self._create_dump() File "/usr/local/lib/python3.10/site-packages/dbbackup/db/postgresql.py", line 112, in _create_dump stdout, stderr = self.run_command(cmd, env=self.dump_env) File "/usr/local/lib/python3.10/site-packages/dbbackup/db/base.py", line 171, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: pg_dump --dbname=postgresql://root:%251fiY%263%40%21%4073%2A6%25ZJ6dT%40%40%253703%2A%5E%2A3%26%254oW046%264%25%250%24%40fexO%2AY%40CRhFy8%2A%240%5E05%2105%407%23@db:5432/db --format=custom pg_dump: error: aborting because of server version mismatch pg_dump: detail: server version: 16.0; pg_dump version: 15.6 (Debian 15.6-0+deb12u1) i have installed postgress-client and therre is not exist any pg_dump package newer version 15 -
How to sort a queryset by a attributes's choices
I have a model with a selectable month and year, like so: class Item(models.Model): MONTHS_CHOICES = [ ('JANUARY', 'January'), ('FEBRUARY', 'February'), ('MARCH', 'March'), ('APRIL', 'April'), ('MAY', 'May'), ('JUNE', 'June'), ('JULY', 'July'), ('AUGUST', 'August'), ('SEPTEMBER', 'September'), ('OCTOBER', 'October'), ('NOVEMBER', 'November'), ('DECEMBER', 'December') ] month = models.CharField(max_length=9, choices=MONTHS_CHOICES, default="JANUARY", db_index=True) year = models.IntegerField(default=0) (...) If I try to order the items by month and year Item.objects.all().order_by("-year", "month"). Logically the months will be be ordered alphabetically. What can I do to get the items ordered by the same order I have the months on MONTHS_CHOICES? Option B is just redo the models to include a DateField with only year and month, like this question here and order it by that field I also tried the solutions on this page but nothing worked to me. -
TypeError at /api/register-application/
I was trying to deploy my system, as everything was working easily on localhost:8000 but when i deploy same code on the server then with the domainname api i cannot post any data with same function worked in localhost:8000. the error is TypeError at /api/register-application/ unhashable type: 'set' Request Method: POST enter image description here I want a solution to fix this issue. -
How to refactor a couple of fields from one model to another with FK relation
I currently have a model class Car(models.Model): name = models.CharField(max_length=20) manufacturer_name = models.CharField(max_length=20) manufacturer_url = models.URLField() Now I would like to extract the manufacturer information into its own model, so that I can get rid of redundant data. Like so: class Manufacturer(models.Model): name = models.CharField(max_length=20) url = models.URLField() class Car(models.Model): name = models.CharField(max_length=20) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) Doing this however the Django migration tool just detects this as "delete fields" and "add fields". Can Django somehow do this migration automatically? Or will I have to write those migrations myself. It seems like a common use case, so I figured maybe Django has something in store for ootb. -
Django Bootstrap form-select...how do I find the selected value?
I have a Django application using Bootstrap form-select. This is filled up from a table like this: <div class="div-1 rounded bg-light text-dark "> {% trans "Active restaurant: " %} <select class="form-select-sm bg-light text-dark" aria-label={% trans "Select a restaurant" %} id="Selected_Restarurant"> <option selected>{% trans "Select a restaurant" %}</option> {% for restaurant in restaurants %} <option value="restaurant.name">{{ restaurant.name }}</option> {% endfor %} </select> </div> I have no idea how to address the value selected by the user in the form-select above. I need to run a filter on employee and update an employee table in the home.html template below to only show the employees of the selected restaurant. I know it has to do with the model and filters, that is also well documented, but how do I find the selected value and update the table below based on the selection?: <table class="table table-sm table-hover"> <thead class="table-success"> <tr> <!--th scope="col">{% trans "Employees" %}</th--> <th scope="col">{% trans "Restaurant" %}</th> <th scope="col">{% trans "First name" %}</th> <th scope="col">{% trans "Last name" %}</th> <th scope="col">{% trans "Username" %}</th> </tr> </thead> <tbody class="table-group-divider"> {% for employee in employees %} {% if employee.restaurant.name == "McDonalds in the bush" %} <tr> <!--td>{{ employee.user.first_name }}</td--> <td>{{ employee.restaurant.name }}</td> <td>{{ … -
I am having issues with the user signup, authentication and views in django
I have a django app and i have created a function to login a user but it shows error this is the view def loginpage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: return HttpResponse("Username or Password is incorrect!!!") return render(request, 'login.html') def LogoutPage(request): logout(request) return redirect('login') this is the html code {% load static %} <!DOCTYPE html> <html lang="us"> <head> <meta charset="UTF-8"> <title>Login</title> <link rel="stylesheet" href="{% static 'css/login.css' %}"> </head> <body> <div class="login-form"> <form method="post"> {% csrf_token %} <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <button type="submit">Login</button> </form> <p>Don't have an account? <a href="{% url 'signup' %}">Sign up here</a></p> </div> </body> </html> this is the url path('login/', userview.loginpage, name='loginpage'), this is the error shown TypeError at /login/ login() missing 1 required positional argument: 'user' Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 4.2.11 Exception Type: TypeError Exception Value: login() missing 1 required positional argument: 'user' Exception Location: C:\Users\kakarot\PycharmProjects\TradingApp.venv\Lib\site-packages\django\core\handlers\base.py, line 197, in _get_response Raised during: django.contrib.auth.login Python Executable: C:\Users\kakarot\PycharmProjects\TradingApp.venv\Scripts\python.exe Python Version: 3.11.7 Python Path: ['C:\Users\kakarot\PycharmProjects\TradingApp', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\kakarot\AppData\Local\Programs\Python\Python311', 'C:\Users\kakarot\PycharmProjects\TradingApp\.venv', 'C:\Users\kakarot\PycharmProjects\TradingApp\.venv\Lib\site-packages'] Server time: Tue, 16 Apr … -
Django ManifestStaticFilesStorage throwing Value Error
I am attempting to ensure that the cache is refreshed whenever I spin up a new instance in Django. I have implemented the following custom storage class to disable the strict handling of manifest files: from django.contrib.staticfiles.storage import ManifestStaticFilesStorage class NonStrictManifestStaticFilesStorage(ManifestStaticFilesStorage): manifest_strict = False This is used in conjunction with the setting: STATICFILES_STORAGE = "myapp.custom_storages.NonStrictManifestStaticFilesStorage" While everything appears to function correctly, I encounter a ValueError when a file does not exist, despite having set manifest_strict = False. This error was not expected under these circumstances. Could someone assist me in debugging this issue? As a temporary solution, deleting the problematic file resolves the error, but this is prone to future errors. For instance, if someone inadvertently removes a CSS file while cleaning up the code, it could disrupt the backend server, which must be avoided. -
Django: how to disable the HTTP_HOST check on a specific endpoint?
I defined a super simple healthcheck endpoint in my Django app (urls.py) to be used in a docker compose environment, like: services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile depends_on: db: condition: service_healthy env_file: - ./.envs/.production/.django command: /start healthcheck: test: ["CMD", "curl", "-f", "http://localhost:5000/healthcheck/"] start_period: 20s interval: 15s timeout: 10s retries: 5 start.sh #!/bin/bash set -o errexit set -o pipefail set -o nounset python /app/manage.py collectstatic --noinput exec /usr/local/bin/gunicorn config.asgi --bind 0.0.0.0:5000 --chdir=/app -k uvicorn.workers.UvicornWorker # ... various imports def healthcheck(): return HttpResponse() urlpatterns = [ # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path("accounts/", include("allauth.urls")), # Hijack path("hijack/", include("hijack.urls")), # Healthcheck path("healthcheck/", healthcheck, name="healthcheck"), # Media files *static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), ] if settings.DEBUG: # Static file serving when using Gunicorn + Uvicorn for local web socket development urlpatterns += staticfiles_urlpatterns() In a local environment there are no issues since localhost is inside the ALLOWED_HOSTS configuration variable. But if I'm in a production environment this is not allowed of course. Indeed I get: ... django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'localhost:5000'. You may need to add 'localhost' to ALLOWED_HOSTS. ... Since the healthcheck endpoint is only used internally is there a way to resolve this? On the top of … -
Why I get an "name 'os' is not defined" error (with import os done)
Good day! I write simplest code #!/usr/bin/python3 import os import os.path dirname = os.path.dirname(__file__) or '.' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") from django.template.loader import render_to_string rendered = render_to_string('Login.html', {'foo': 'bar'}) And got an error BASE_PATH = os.path.dirname(__file__) ^^ NameError: name 'os' is not defined. Did you forget to import 'os'? Clearly I don't forgot "import os". Any way to deal with this error? I try different code parts from any advice find on web, but no luck at all. -
Django Prefetch object with generic relation
As stated in the documentation: class Prefetch(lookup, queryset=None, to_attr=None) The Prefetch() object can be used to control the operation of prefetch_related(). The queryset argument supplies a base QuerySet for the given lookup For example, it can be used to specify the columns from the related object to SELECT, by using only(): Author.objects.prefetch_related(Prefetch("hometown", City.objects.only(["name"])) However, when prefetching the objects related through a generic relation, what model should be passed to the queryset param of Prefetch? I can't see any references to that on the docs nor SO. Something like: Prefetch("foo", GenericRelation.objects.only(["title"])) -
What's wrong with this Django view fucntion editpage func, EditForm class and editpage.html?
I am trying to just display page contents in console after the form is submitted. Also how to change editpage.html file's 'name' variable in such a way that instead of hardcoding 'ewew' variable name can be passed with name of each different pages.debug display on browser debug display on browserserver console view file of django: from django.shortcuts import render from . import util from django.http import HttpResponseRedirect from django.urls import reverse from django import forms from string import Template import markdown2 import re def writetofile(name,entryBody): file1 = open(f"encyclopedia/templates/wiki/{name}.html","w") file1.write('{% extends "encyclopedia/layout.html" %}\n') file1.write('{% block body %}\n') file1.write(entryBody) #editLink=f"<a href=\"{% url 'encyclopedia:editPage',{"name":{name}} %}\">Edit Page</a>" #editLink=f"<a href=\"{% url 'encyclopedia:editPage' name=name %}\">Edit Page</a>" #editLink=f"<a href=\"{% url 'encyclopedia:editPage' name='{name}' %}\">Edit Page</a>" #editLink="<a href=\"{% url 'encyclopedia:editPage' name='{}' %}\">Edit Page</a>".format(name) #editLink="<a href=\"{\% url 'encyclopedia:editPage',{'name': %s} \%}\">Edit Page</a>".format(name) #editLink = Template("<a href=\"{% url 'encyclopedia:editPage' , {name:'$name' }} %}\">Edit Page</a>") editLink = Template("<a href=\"{% url 'encyclopedia:editPage' name='$name' %}\">Edit Page</a>") editLink=editLink.substitute(name=name) print(editLink) file1.write(editLink) file1.write('\n{% endblock %}') file1.close() def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def newPageError(request): return render(request, "encyclopedia/newpageerror.html") #def content(request): def wiki(request,name): #name=request.GET.get('name') entryBody=util.get_entry(name) if entryBody: entryBody= markdown2.markdown(entryBody) writetofile(name,entryBody) #file1 = open(f"encyclopedia/templates/wiki/{name}.html","w") #file1.write('{% extends "encyclopedia/layout.html" %}\n') #file1.write('{% block body %}\n') #file1.write(entryBody) #file1.write('\n{% endblock %}') #file1.close() return … -
Trying to ban user as a super user (banned user can't create posts)
i give permission to my superuser to ban all the other types of users, this my views.py file: @login_required(login_url='login') def Home(request): posts = Post.objects.all() if request.method == "POST": #taking the id i passed in value attribute post_id = request.POST.get("post_id") user_id = request.POST.get("user_id") if post_id: post = Post.objects.filter(id=post_id).first() if post and (post.auther == request.user or request.user.has_perm('main.delete_post')): post.delete() elif user_id: user = User.objects.filter(id=user_id).first() if user and request.user.is_staff: try: group = Group.objects.get(name="default") group.user_set.remove(user) print("removed successfully") except: print("something went wrong") pass try: group = Group.objects.get(name="mode") group.user_set.remove(user) print("removed successfully") except: print("something went wrong") pass return render(request,"main/home.html", {"posts":posts}) my html file: {% if user.is_staff %} <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-warning" value={{post.id}} name="user_id">Ban User</button> </form> {% endif %} i tried to print messages if the user is removed and it printing removed successfully, and then i logged as that banned user i can still create post,did i miss something in views.py? -
Get values from 2 database statements with radio buttons
I am trying to connect two database statements via two radio buttons. As soon as I change the radio button value, these have to be retrieved again directly via the database. I am currently trying to do this via HTML, JavaScript and Python. However, only one of the two statements is currently displayed. js: $("#id_base-0-show_null").change(function () { var show_null_value = document.querySelector('input[name=base-0-show_null]:checked').value; var checked_0 = document.getElementById('id_base-0-show_null_0').checked; var checked_1 = document.getElementById('id_base-0-show_null_1').checked; console.log(show_null_value, checked_0, checked_1); **currently doesn't do anything** }); exporter.py: def get_last_values_of_target(self, target_type, target_name): ... def get_zero_values_of_target(self, target_type, target_name): ... manual_input.py: def get_last_values_of_target(request): if is_ajax(request): target_type = int(request.POST['target_type']) target_name = request.POST['target_name'] exporter = Exporter() exporter.station = target_type values = exporter.get_last_values_of_target(target_type, target_name) **here is the current single exporter where i'm trying to add a second one (get_zero_values_of_target)** return HttpResponse(simplejson.dumps({'values': values}), 'application/javascript') else: return HttpResponseBadRequest("Not allowed") template: {% block content %} <form action="" method="post" id="manual_input_form" name="manual_input_form"> {% csrf_token %} <div class="timeDiffer"> {% for base_form in base_formset %} *** <div class="{% if base_form.non_field_errors %}error {% else %}showDiff{% endif %}"> <div>{{ base_form.show_differences.label_tag }}{{ base_form.show_differences }}</div> </div> {% if base_form.show_differences %} <div class="{% if base_form.non_field_errors %}error {% else %}showNull{% endif %}"> <div class="flex">{% trans base_form.show_null.label_tag %}{{ base_form.show_null }}</div> </div> {% endif %} {% endfor %} <input type='hidden' … -
python makemigration creating tables error
Traceback (most recent call last): File "C:\python\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\python\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\Asus\Documents\projects\valeohr\backend\app\apps.py", line 9, in ready from .jobs import updater File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\updater.py", line 3, in <module> from app.jobs.jobs import Syncing File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\jobs.py", line 8, in <module> class Syncing: File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\jobs.py", line 13, in Syncing db = DB.get_db('geco1') File "C:\Users\Asus\Documents\projects\valeohr\backend\app\models\base.py", line 14, in get_db dbo = cls.objects.filter(code=db).first() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 1047, in first for obj in (self if self.ordered else self.order_by("pk"))[:1]: File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 394, in __iter__ self._fetch_all() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 1867, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 87, in __iter__ results = compiler.execute_sql( File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1398, in execute_sql cursor.execute(sql, params) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return … -
CSS on the site is not visible
I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the HTML. Would you like me to share the code? I try to change something on setting.py -
How can I troubleshoot an authentication issue?
When making a request to http://127.0.0.1:8000/auth/users/reset_password/. The endpoint works only if i include ""rest_framework_simplejwt.authentication.JWTAuthentication" at(DEFAULT_AUTHENTICATION_CLASSES) but not when using my Custom authentication "passportBackend.custom_auth.JWTOrOAuth2Authentication".I think the documentation of rest_framework_simplejwt it returns None when permission is not required. from rest_framework.authentication import BaseAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication from oauth2_provider.contrib.rest_framework import OAuth2Authentication from rest_framework.exceptions import AuthenticationFailed class JWTOrOAuth2Authentication(BaseAuthentication): def authenticate(self, request): # Try authentication additional_info = request.META.get("HTTP_X_ADDITIONAL_INFO") # # DRF OAuth2 # print(additional_info) if additional_info == "OAuth2": oauth2_authentication = OAuth2Authentication() oauth2_user, oauth2_auth = oauth2_authentication.authenticate(request) if oauth2_user is not None: return oauth2_user, oauth2_auth # # Simple JWT # elif additional_info == "jwt": jwt_authentication = JWTAuthentication() jwt_user, jwt_token = jwt_authentication.authenticate(request) if jwt_user is not None: return jwt_user, jwt_token return None def authenticate_header(self, request): # Override this method if needed pass "DEFAULT_AUTHENTICATION_CLASSES": ( "passportBackend.custom_auth.JWTOrOAuth2Authentication", ), How can I troubleshoot an authentication issue with my custom JWTOrOAuth2Authentication class ? -
How to connect to the existing database through NGINX?
I have a project what I need to start with Docker. I've successfully created images and containers of Django, NGINX and postgreSQL, so the project starts correctly. I noticed that when I try to login to the admin panel, Django raises OperationalError at /admin/login/ connection to server at "database" (192.168.144.2), port 5432 failed: fe_sendauth: no password supplied. Everything worked fine without nginx, but now I cannot access to the database. As I understand the problem, I need to change nginx.config, but I tried almost everything and still cannot figure this out. Seems like postgreSQL doesn't see my user maybe. My code snippet below. uwsgi.ini [uwsgi] wsgi-file = config/wsgi.py strict = true socket = :8000 protocol = http master = true no-orphans = true die-on-term = true lazy-apps = true processes = 4 threads = 8 enable-threads = true max-requests = 500 reload-on-rss = 1024 worker-reload-mercy = 60 harakiri = 60 harakiri-verbose = true vacuum = true post-buffering = 1048576 buffer-size = 65535 nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; include /etc/nginx/uwsgi_params; server { listen 80; server_name localhost; location / { proxy_pass http://django:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header …