Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VPS Ubuntu 22.04 - Django - Gunicorn - Nginx
If I use; gunicorn --bind 0.0.0.0:8000 my_project.wsgi works Then this is my config: gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=my_user Group=www-data WorkingDirectory=/home/my_user/test EnvironmentFile=/home/my_user/test/.env ExecStart=/home/my_user/test/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ my_project.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/test server { listen 80; server_name IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/my_user/test; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Every systemctl status is running but I still show Welcome to Nginx! I want to show my Django App. What can i do? -
can't browse server for videos in Django Rest Framework project using CKEditor in admin panel
I use CKEditor for my django project to write Articles rich text. I easily can upload images to the server and next time select them by browsing server like this (by click on Embed Image button): enter image description here enter image description here But the problem is when I choose a video that I uploaded before I can't use that and Embed Image button doesn't appears. (just also IDM shows a page to start download video). and I just see a loading icon. enter image description here I also have to say that I'm using HTML5Video CKEditor plugin for the approach. my CKEditor configs in settings.py : STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR) MEDIA_URL = '/images/' MEDIA_ROOT = BASE_DIR/'media' CKEDITOR_UPLOAD_PATH= 'uploads/' # MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') STATICFILES_DIRS = os.path. join(BASE_DIR, 'static'), CKEDITOR_BASEPATH = '/static/ckeditor/ckeditor/' CKEDITOR_CONFIGS = { 'default':{ 'toolbar': 'full', 'removePlugins':'exportpdf', 'extraPlugins': ','.join([ 'codesnippet', 'widget', 'html5video', 'uploadimage' ]) } } I wanted to use CKFinder in my DRF project but I didn't find any guideline to do that. -
Creating many models dynamically for an app in django
Hello folks, I want to know if it is possible to create models dynamically for example from the admin panel in django ? For example an app which is role is to have a model itself with many fields and by theses fields we will be able to create new models. Thanks for the answer -
Django Channels: Error UNKNOWN while writing to socket. Connection lost
We have Django Channels coupled with uvicorn and azure redis instance. Our sentry is getting swamped with errors such as: Exception in ASGI application ssd.consumers in disconnect Error UNKNOWN while writing to socket. Connection lost. The exception is thrown in asyncio/streams.py file as shown on example My main issue is that I have no idea if redis cuts this connection, or server is not keen to keep it? Any hints appreciated. I haven't observed such behaviour on local instance of redis. We opearte on following packages: Django = "~4.2" redis = "^4.3.1" channels = {extras = ["daphne"], version = "^4.0.0"} channels-redis = "^4.1.0" uvicorn = {extras = ["standard"], version = "^0.24.0.post1"} It's worth to point that it works majority of the times, websockets are operational, sometimes it just randomly throw an exception mentioned above. -
Djago DRF deosn't deserialize json
I faced a very weird issue with django drf. The below view does not deserializes the event_time in post() method. class EventListCreateView(generics.ListCreateAPIView): class EventSerializer(serializers.ModelSerializer): school_id = serializers.IntegerField(read_only=True) class_number = serializers.CharField(source='class.universal_number', read_only=True) class_id = serializers.IntegerField(write_only=True) class Meta: model = Class fields = ('pk', 'event', 'school_id', 'class_number', 'class_id', 'event_time',) serializer_class = EventSerializer filterset_class = EventFilterSet ordering_fields = ['event_time'] def get_queryset(self): return ( Event.objects.select_related('class') .annotate(school_id=F('class__school')) .order_by('-pk') ) It works only after I explicitly mention event_time in the serializer: class EventListCreateView(generics.ListCreateAPIView): class EventSerializer(serializers.ModelSerializer): school_id = serializers.IntegerField(read_only=True) class_number = serializers.CharField(source='class.universal_number', read_only=True) class_id = serializers.IntegerField(write_only=True) event_time = serializers.DateTimeField() class Meta: model = Class fields = ('pk', 'event', 'school_id', 'class_number', 'class_id', 'event_time',) serializer_class = EventSerializer filterset_class = EventFilterSet ordering_fields = ['event_time'] def get_queryset(self): return ( Event.objects.select_related('class') .annotate(school_id=F('class__school')) .order_by('-pk') ) Which doesn't make sense to be correct approach. Any suggestion on how to solve the issue will be appreciated. -
django celery with redis, celery worker not receive any message
I have a django project with celery Here is my proj/settings.py (just the celery parts) # -----CELERY CELERY_TIMEZONE = "Asia/jakarta" CELERY_BROKER_URL = "redis://localhost" CELERY_TASK_DEFAULT_QUEUE ='taibridge' CELERY_DEFAULT_QUEUE ='taibridge' CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True # ---EOF-CELERY and here is my proj/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') app = Celery('main') app.config_from_object('django.conf:settings', namespace='CELERY') Running the worker from console, I Got [2024-05-16 06:09:54,926: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2024-05-16 06:09:54,928: DEBUG/MainProcess] | Worker: Building graph... [2024-05-16 06:09:54,928: DEBUG/MainProcess] | Worker: New boot order: {Beat, Timer, Hub, Pool, Autoscaler, StateDB, Consumer} [2024-05-16 06:09:54,933: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2024-05-16 06:09:54,933: DEBUG/MainProcess] | Consumer: Building graph... [2024-05-16 06:09:54,941: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Mingle, Gossip, Heart, Agent, Tasks, Control, event loop} -------------- celery@taiga-project v5.4.0 (opalescent) --- ***** ----- -- ******* ---- Linux-5.15.0-60-generic-x86_64-with-glibc2.35 2024-05-16 06:09:54 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: main:0x7fd4d824ab00 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> taibridge exchange=taibridge(direct) key=taibridge [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord … -
Python Daylight Savings Accomodation
Iam working on a django project. Im fairly new to it. I have a requirement to sent out email reports in which I need to convert datetimes into yours local timezone. Im saving records in utc time and I have users time zone with me. Iam using the python package pytz to convert utc time into user's local time. The convsersion is working fine. No issues there. from pytz import timezone as pytz_timezone input_time.astimezone(pytz_timezone(time_zone) This is how i convert utc time into user's local time Im confused with Daylight savings time. I want to know whether this conversion will also account for daylight savings? Suppose the user is in New South Wales so he will have the time_zone as 'Australia/Sydney'. If the above mentioned code is applied during DST and not during DST , is it accounted in the conversion or do I need to add some other manipulation to the converted user local time to account for the DST. if so what should I do? I hope my confusion and question makes sense. Thanks in advance. -
Setting field.required to false cause error list indices must be integers or slices, not str
I want to set a page to update a user information, including a field to create a new password. This page is strictly for updating existing user. The password field in this page will be optional. There is another page with another view to create user where the password field is required there. My current approach is to set the field required to be false in the view as below class User(AbstractUser): password = models.CharField(max_length=200) # ommited the rest for brevity class UserEdit(UpdateView): model = User fields = ['fullname', 'username','status','email','phone_number','role','program_studi','password'] template_name = 'user-management-edit.html' success_url = reverse_lazy('user-management') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initial['password'] = '' self.fields['password'].required = False def form_valid(self, form): form.instance.edited_by = self.request.user password = form.cleaned_data.get('password', None) if password: form.instance.set_password(password) return super().form_valid(form) {% for field in form %} {% if field.name in inline_field %} <div class="col-4"> {% if field.field.required %} {% bootstrap_field field label_class='control-label required' %} {% else %} {% bootstrap_field field %} {% endif %} </div> {% else %} <div class="col-12 {% if field.name == 'radio_input' %} col-radio-input {% endif %}"> {% if field.field.required %} {% bootstrap_field field label_class='control-label required' %} {% else %} {% bootstrap_field field %} {% endif %} </div> {% endif %} {% endfor %} … -
how to mysql database in django project
i set database connecting statement in settings.py it returns no biulding tools and ask to install mysqlclient. django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
Django views file says
So i have the folloing error: didn't return an HttpResponse object. It returned None instead. And from what I read it was due to to not having a render in the return line, however after checking multiple times, the render is being output from the return function as it did on the code that worked (the second part) I have double checked and it seems right, I also get the following errors from django: \django\core\handlers\exception.py, line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ line 204, in _get_response self.check_response(response, callback) line 332, in check_response raise ValueError( # Create your views here. def home(request): #define a view, a home view that passes a request ## goes to home html and passes in a dictionary later import json import requests api_request = requests.get("https://www.airnowapi.org/" # secret key erased) try: api = json.loads(api_request.content) except Exception as e: api = "Chiiispas, something went wrong" if api[0]['Category']['Name'] == "Good": ## sets a conditional when the output comes out and links it onto the corresponding html class category_description = 'Esta con madre el clima y puedes hacer cosas chingonas' category_color='Good' # html classes are on the base html file elif api[0]['Category']['Name'] == "Moderate": category_description ='Cámara mi tibio, toma … -
KeyError at /cart/ 'product_obj' Django
In my cart i can add same product with different size and color. but randomly when i want to to add same product with different size and color i have this error in my cart iter function. i've tracked the process in debugger and found that it somehow traped in my Product model str method and finally this error raise. models: from django.db import models from django.urls import reverse from django.conf import settings from colorfield.fields import ColorField class Product(models.Model): GENDER_MALE = 'm' GENDER_FEMALE = 'f' GENDER_BOTH = 'b' GENDER_CHOICE = [ (GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female'), (GENDER_BOTH, 'Both') ] name = models.CharField(max_length=200) category = models.CharField(max_length=200) gender = models.CharField(choices=GENDER_CHOICE, max_length=1) sizes = models.ManyToManyField(to="store.Size", related_name="sizes") slug = models.SlugField(unique=True, allow_unicode=True, db_collation='utf8_persian_ci') price = models.PositiveIntegerField() description = models.TextField() inventory = models.IntegerField() datetime_created = models.DateTimeField(auto_now_add=True) datetime_modified = models.DateTimeField(auto_now=True) discounts = models.IntegerField(default=0) available_colors = models.ManyToManyField(to="store.Color", related_name="colors") status = models.BooleanField(default=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("product_detail", kwargs={"slug": self.slug}) class Size(models.Model): size = models.CharField(max_length=2) def __str__(self): return self.size class Color(models.Model): color = ColorField() name = models.CharField(max_length=200) def __str__(self): return self.name class Picture(models.Model): picture = models.ImageField(upload_to=f'static/store/images/') product = models.ForeignKey(Product, default=None, related_name='images', on_delete=models.PROTECT) def __str__(self): return self.picture.url views: def cart_detail_view(request): cart = Cart(request) colors = Color.objects.all() for item in … -
How to implement connection pooling in django?
We have multiple servers accessing a central MySQL database, which is causing connection churn and potentially impacting performance. To mitigate this, I've implemented connection pooling in Django using the django-db-connection-pool package (https://pypi.org/project/django-db-connection-pool/#:~:text=django%2Ddb%2Dconnection%2Dpool%5Ball%5D). However, I'm unsure how to effectively test this setup within Django. What methods or tools can I use to verify if the connection pooling is indeed functioning as expected? I've set up Percona for my database and crafted a load test script to assess its performance under simulated traffic. However, I'm uncertain about the best approach to compare the results obtained from these load tests. What are some recommended methods or metrics to use when comparing load test results in Percona? -
Django Tests Throw ORA-00942: table or view does not exist
I haven't found any questions with respect to Django tests and Oracle DB. I am trying to run a test on an existing application, but am running into the table or view doesn't exist error. I am confused as the test says it is deleting and creating those tables/views. Creating test database for alias 'default'... Failed (ORA-01543: tablespace 'TEST_EMS12250' already exists) Got an error creating the test database: ORA-01543: tablespace 'TEST_EMS12250' already exists Destroying old test database 'default'... Creating test user... Failed (ORA-01920: user name 'TEST_PRCQA' conflicts with another user or role name) Got an error creating the test user: ORA-01920: user name 'TEST_PRCQA' conflicts with another user or role name Destroying old test user... Creating test user... Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 459, in execute_manager utility.execute() File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 49, in run_from_argv super(Command, self).run_from_argv(argv) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv self.execute(*args, **options.__dict__) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/test/simple.py", line 381, in run_tests old_config = self.setup_databases() File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/test/simple.py", line 317, in setup_databases self.verbosity, autoclobber=not self.interactive) File "/scratch/prcbuild/releasejango_project/venv/lib/python2.7/site-packages/django/db/backends/creation.py", line … -
Python 5-Card Draw tech stack decision
I am trying to create a 5 Card-Draw poker game (single player with up to 4 bots) for my 85 year old father to use hopefully on a tablet - using touch controls. I have been learning python and I am fine using python to help continue my learning. I am also learning django. I found a great pokergame opensource python program that uses terminal input and output - I am using this to refactor for the game. I have been using AI (with mixed results) to help assist while also digging deep into the logic. I am now at a point where the game I am creating for my father is turning into a python/django/bootstrap5/websockets web game. It is proving to be a great learning opportunity but frustrating in the level of complexity. Is this still a good approach for a poker game? I figured if I hosted it I could update it much easier for him. That said, it seems much much easier if I just used pygame and made a executable game that could play on the tablet. I am all ears for opinions as I am just learning and need all the help I can get. … -
Gunicorn doesn't get cookie
I've DjangoApp with gunicorn and NGNIX. I use a language switcher: def setlang(request): if get_language() == 'de': lang = 'en' else: lang = 'de' response = redirect('index') response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang) return response index: def index(request): return render(request, 'index.html') manage.py runserver everthing works fine. Cookie is set and after redirect, translation works. If I run gunicorn pro.wsgi:application --bind=202.61.253.165:8199 the side is served (without the statics of course) the setlang(request) sets the cookie (chromedevtools) BUT after the redirect the translation doesn't activate. -
Django Tenants - I spent a lot of time on it
I have a problem with django-tenants. I am still learning to program, so it is possible that I have made a beginner's mistake somewhere. I will explain what I am trying to achieve with a model example. Some procedures are quite awkward and serve mainly to identify the problem. The problem is that the middleware likely does not switch the tenant. Specifically, I would expect that if /prefix/domain_idorsubfolder_id is in the URL, the middleware would automatically detect the prefix, subfolder ID, and set the corresponding schema as active. However, this is not happening, and the login to the tenant does not occur. Instead, the login happens in the "public" schema in the database. Model example: A user goes to http://127.0.0.1:8000/login/ and enters their email, which filters the appropriate tenant and redirects the user to /client/tenant_id/tenant/login. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/client/test2f0d3775/tenant/login/ Using the URLconf defined in seo_app.tenant_urls_dynamically_tenant_prefixed, Django tried these URL patterns, in this order: client/test2f0d3775/ basic-keyword-cleaning/ [name='basic_cleaned_keyword'] client/test2f0d3775/ ai-keyword-cleaning/ [name='auto_cleaned_keyword'] client/test2f0d3775/ keyword-group-creation/ [name='content_group'] client/test2f0d3775/ looking-for-link-oppurtunities/ [name='search_linkbuilding'] client/test2f0d3775/ url-pairing/ [name='url_pairing'] client/test2f0d3775/ creating-an-outline/ [name='article_outline'] client/test2f0d3775/ analyses/ [name='all_analyses'] client/test2f0d3775/ download/<str:model_type>/<int:file_id>/ [name='download_file'] client/test2f0d3775/ dashboard/ [name='dashboard'] client/test2f0d3775/ client/ The current path, client/test2f0d3775/tenant/login/, didn’t match any of these. Notice that the … -
Django installation process
I have downloaded Django and "from django.shortcuts import render" is giving me error And some other imports from Django too is giving me error I've tried using chat gpt but the steps didn't work I tried reinstalling Django still didn't work -
Django: Update form without updating date/time when Date/TimeField is auto_now=True
I have build a record keeping app. I want the user to be able to edit an event but without updating the Date/TimeField when those are set to auto_now=True. models.py class Game(models.Model): # ForeignKeys user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) deck = models.ForeignKey(Deck, on_delete=models.CASCADE, null=True) wincon = models.ForeignKey(Wincon, on_delete=models.CASCADE, null=True, blank=True) tournament = models.BooleanField(default=False) num_players = models.IntegerField(choices=NUM_PLAYERS_CHOICE, default=4) start_pos = models.CharField(max_length=20, choices=START_POS_CHOICE, default=1) mull = models.CharField(max_length=20, choices=MULL_CHOICE, default='1st 7') outcome = models.CharField(max_length=10, choices=OUTCOME_CHOICE, default='Win') medium = models.CharField(max_length=10, choices=MEDIUM_CHOICE, default='Paper') date = models.DateField(auto_now=True) time = models.TimeField(auto_now=True) forms.py class GameForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(GameForm, self).__init__(*args, **kwargs) # Set deck list shown to only decks from user user_decks = Deck.objects.filter(user=user) user_decks_list = [] for deck in user_decks: if deck.is_cedh: deck.deck += ': cEDH' user_decks_list.append((deck.id, deck.deck)) self.fields['deck'].choices = user_decks_list # Set wincon list shown to only wincon from user user_wincon = Wincon.objects.filter(user=user) user_wincon_list = [] for wincon in user_wincon: user_wincon_list.append((wincon.id, wincon.wincon)) self.fields['wincon'].choices = user_wincon_list class Meta: model = Game exclude = {'date', 'time', 'user'} labels = { 'deck': 'What deck', 'num_players': '# of Players', 'start_pos': 'Starting position', 'mull': 'Starting hand', 'outcome': 'Outcome', 'wincon': 'Your Wincon', 'medium': 'Paper or Online', 'tournament': 'Tournament', } class UpdateGameForm(forms.ModelForm): class Meta: model = Game exclude = {'date', … -
Django and Webpack - Implementing modern Javascript Tools
I am working on a Django project and want to enhance the front-end using npm and webpack. My web development experience has been primarily with Django, and I'm new to npm and webpack. I've run into a few issues during this integration process and need some guidance. Here are some of the libraries I am including in my project: Django v3.2 python 3.7.13 Node Libraries I am using Bootstrap v5.3.3 Bootstrap-icons v1.11.3 jQuery v3.7.1 jQuery-ui v1.13.3 jQuery-validation v1.20.0 metro4-dist v4.5.0 webpack v5.91.0 webpack-cli v5.1.4 webpack-dev-server v5.0.4 [etc] Tutorials/Guides I've Used Sharing guides I used to help others in my scenario along their way. Modern JavaScript for Django Developers : This helped me understand why npm and webpack were necessary. Definitive Guide to Django and Webpack : Great guide for detailed configuration. Learn Webpack - Full Tutorial for Beginners : Video that walks you through setup Django with Webpack : Another video explaining how to configure webpack with a Django Project. Coming from "Modern Javascript for Django" put it best for me on my situation. First you learn Django. You go through the tutorial, learn about models and views, and get your very first "hello world" application up and running. You're … -
I can't manage to upload images, using NextJS and Django rest framework. TypeError: RequestInit: duplex option is required when sending a body
I want to be able to add products, using a form. The product fields are : title and picture. The error catched is : TypeError: RequestInit: duplex option is required when sending a body. The page for adding a product looks like this : "use client"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useState } from "react"; async function addProduct(body) { const res = await fetch("http://localhost:3000/api/products/", { method: "POST", body: body, }); const data = await res.json(); return data; } export default function AddProductPage() { const [title, setTitle] = useState(""); const [picture, setPicture] = useState(null); const onSubmit = async (e) => { e.preventDefault(); const formData = new FormData(); formData.append("title", title); formData.append("picture", picture); const body = formData; const res = await addProduct(body); console.log(res); }; return ( <form onSubmit={onSubmit}> <div className="container space-y-4 py-16"> <div className="grid w-full max-w-sm items-center gap-1.5 mx-auto"> <Label htmlFor="title">Title</Label> <Input type="text" id="title" name="title" placeholder="Product Title..." value={title} onChange={(e) => setTitle(e.target.value)} /> </div> <div className="grid w-full max-w-sm items-center gap-1.5 mx-auto"> <Label htmlFor="picture">Picture</Label> <Input type="file" id="picture" name="picture" placeholder="Product Picture..." onChange={(e) => setPicture(e.target.files[0])} /> </div> <div className="flex w-full max-w-sm items-center gap-1.5 mx-auto justify-end"> <Button variant={"secondary"} type="reset"> Reset </Button> <Button type="submit">Submit</Button> … -
Error 500 with "Invalid block tag" issue, for no reason
Right, is there any particular reason as to why Django has an issue with my template tags, despite my making no errors in my code? The template traceback is as follows: File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\backends\django.py", line 33, in get_template return Template(self.engine.get_template(template_name), self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\engine.py", line 177, in get_template template, origin = self.find_template(template_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\engine.py", line 159, in find_template template = loader.get_template(name, skip=skip) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\loaders\cached.py", line 57, in get_template template = super().get_template(template_name, skip) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\loaders\base.py", line 28, in get_template return Template( ^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 154, in __init__ self.nodelist = self.compile_nodelist() ^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 196, in compile_nodelist return parser.parse() ^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 510, in parse raise self.error(token, e) File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 508, in parse compiled_result = compile_func(self, token) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\loader_tags.py", line 295, in do_extends nodelist = parser.parse() ^^^^^^^^^^^^^^ File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 504, in parse self.invalid_block_tag(token, command, parse_until) File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 565, in invalid_block_tag raise self.error( django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 18: 'content'. Did you forget to register or load this tag? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\xxxx\.venv\Lib\site-packages\django\template\base.py", line 502, in parse compile_func = self.tags[command] ~~~~~~~~~^^^^^^^^^ KeyError: 'content' During handling of the above exception, another exception … -
Django cookies http working but https doesn't
I use a language switcher: def setlang(request): if get_language() == 'de': lang = 'en' else: lang = 'de' response = redirect('index') response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang) return response index: def index(request): return render(request, 'index.html') Works on http, on https (nginx+gunicorn+certbot) the cookie is set, which I can see though googledeveloper console, the function get_language is also working, which I checked by 'LANGUAGE_CODE = ...' alterration, but Django doesn't change the language after the redirect. Any ideas? -
when I want to logout it shows HTTP ERROR 405
please help me. I'm trying to make a logout, but it only give HTTP ERROR 405. I read some info about this problem, that it gives "GET" method and I need a "POST" method, but it still doesn't work. urls.py enter image description here logged_out.html enter image description here Tried to log out but it doesn't work -
error in django 404 Page not found (404) Request Method: GET
When clicking on this link: http://127.0.0.1:8000/accounts/register it gives a 404 error, I do not know what to do with it Here is the code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views urlpatterns = [ path('/register', views.register, name='register'), ] registration/views.py: from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from .forms import RegistrationForm from django.shortcuts import render, redirect def sign_up(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = RegistrationForm() return render(request, 'registration/register.html', {'form': form}) def register(): print("hello!") urls.py(In the project itself): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('news/', include('news.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I've tried a lot of YouTube videos and documentations, but everything is even -
Django gettext internationalization/translation not working for production in cloud run with docker
I'm working on website using Django + gettext + docker and hosting it on cloud run, my dev is windows 11 environment.(I went through a lot until I manage to deploy my build). But something funny happened when I'm trying to setup multilanguage support. My Chinese translation config work on my local build but not on my google cloud run. I'm using Django==5.0.2 and python-gettext==5.0. I followed some Youtube tutorial and did my localization. Works perfectly on my local but not working in google cloud run. I'm using # 5. Localization step to make messages - name: gcr.io/google-appengine/exec-wrapper args: - "-i" - "$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA" - "-s" - "${PROJECT_ID}:${_DEPLOY_REGION}:${_DB_INSTANCE}" - "-e" - "SETTINGS_NAME=${_SECRET_SETTINGS_NAME}" - "-e" - "DJANGO_SETTINGS_MODULE=lt3aelaw.settings.production" - "--" - "python" - "manage.py" - "makemessages" - "-l" - "zh_HAns" id: Localization make messages # 5.1 Localization step to make messages for de - name: gcr.io/google-appengine/exec-wrapper args: - "-i" - "$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA" - "-s" - "${PROJECT_ID}:${_DEPLOY_REGION}:${_DB_INSTANCE}" - "-e" - "SETTINGS_NAME=${_SECRET_SETTINGS_NAME}" - "-e" - "DJANGO_SETTINGS_MODULE=lt3aelaw.settings.production" - "--" - "python" - "manage.py" - "makemessages" - "-l" - "de" id: Localization make messages for de # 6. Localization step to compile messages - name: gcr.io/google-appengine/exec-wrapper args: - "-i" - "$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA" - "-s" - "${PROJECT_ID}:${_DEPLOY_REGION}:${_DB_INSTANCE}" - "-e" - …