Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin display queryset
In my admin panel, i want to display the userdetail objects for users who meet specific requirements: premium_users = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False,) But its not working and its not display this on the admin page. Here is my full code: class UserDetailAdmin(admin.ModelAdmin): def show_premium_users(self, request, queryset): premium_users = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False,) self.message_user(request, f'{premium_users.count()} premium users found') queryset = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False) print(queryset) return queryset show_premium_users.short_description = 'Show Premium Users' search_fields = ('user__username',) actions = ('show_premium_users') admin.site.register(UserDetail, UserDetailAdmin) How can I make it so i display the userdetail objects that meet the premium requirement on my admin page? -
Django ModelForm as controller of model field validation
I have an authorization form, and I get an error - "already have a user with this email". I want to use the forms as a layer of validating the data. I now, that i can pass instance of CustomUser in my form, but i can`t do it. Need other solution. @require_http_methods(["POST"]) @not_logged_in_user_only() def auth(request: WSGIRequest): form = UserAARForm(data=request.POST) if not form.is_valid(): return JsonResponse({'status': 'error', 'message': f'{form.errors.as_json()}'}) else: service = AuthenticateAndAuthOrRegistrUser() service.execute(req=request, data=form.clean()) if service.errors: return HttpResponseServerError() return redirect("profile_page") class SoundHomeUsers(models.Model): email = models.EmailField( max_length=254, unique=True, validators=[UserEmailValidator().is_valid]) password = models.CharField( max_length=254, validators=[UserPasswordValidator().is_valid]) class UserAARForm(ModelForm): class Meta: model = SoundHomeUsers fields = ['email', 'password'] -
How do I make an auto increment field that references other model fields in Django?
I'm making an Author model and I need to create an automatically increasing field by writing Post: Class Author(models.Model): author_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) post_count = models.PositiveIntegerField(default=0, null=True) # This field! Class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) body = models.TextField() author = models.ForeignKey('Author', to_field="author_id", null=True, on_delete=models.SET_NULL, db_column="author") created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) How do I make it? -
Django 4.2 and NGINX - The page isn’t redirecting properly
I am trying to add ssl to my test django server that is on AWS. I followed a tutorial to add ssl with certbot, add the proxy_pass but I never got it to work, so after three days trying all kinds of things, I give up. Could you guys please have a look and let me know where I am wrong? I am also confused about the environment variables, $host is blank and so are the others, I am going to assume they should be populated? I know nothing about NGINX, sorry about the noob questions. server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 404; } server { listen 80; listen [::]:80; server_name techexam.hopto.org; return 301 https://$server_name$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name techexam.hopto.org; ssl_certificate /etc/letsencrypt/live/techexam.hopto.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/techexam.hopto.org/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; include /etc/nginx/mime.types; charset UTF-8; location /static/ { alias /home/sfarmer/code/django_workspace/exam/Quiz/static/Quiz/; } location /media/ { alias /home/sfarmer/code/django_workspace/exam/Quiz/static/Quiz/; } location / { proxy_pass http://127.0.0.1:8000/; proxy_set_header Host $host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Additional logging access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; error_page 502 /error_pages/502.html; location = /error_pages/502.html { internal; root /usr/share/nginx/html; } } } -
Gunicorn, serve VPS, can't load CSS to admin panel
Previously, I have never been involved in setting up and maintaining a VPS. I recently launched a project using ubuntu + nginx + gunicorn. Everything works fine, but the CSS are not loaded to admin panel. At first, not understanding what was the reason, I tried to install grappelli - without success. After I found information that gunicorn cannot load admin CSS. The solution I see is to configure nginx to render CSS to admin panel. However, I couldn't to set up nginx correctly when I tried to set up a server without gunicorn. As a result, the server gave the nginx stub and I couldn't log into the server (although nginx did not show any syntax errors) - I had to delete the server and set up a new one. Therefore, I ask for help: what needs to be written in the nginx configuration so that, in addition to transmitting traffic, it also gives the CSS of the admin panel? I will be grateful for any answer! -
Django docker: docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed
I want to deploy my django project with docker and uwsgi on windows 11, but get some errors. docker build . -t djangohw docker run -it --rm djangohw -p 8080:80 docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "-p": executable file not found in $PATH: unknown. Dockerfile FROM python:3.9 ENV DEPLOY=1 WORKDIR /opt/tmp COPY . . RUN pip install -r requirements.txt EXPOSE 80 CMD ["sh", "start.sh"] start.sh python3 manage.py makemigrations board python3 manage.py migrate uwsgi --module=mysite.wsgi:application \ --env DJANGO_SETTINGS_MODULE=mysite.settings \ --master \ --http=0.0.0.0:0 \ --processes=5 \ --harakiri=20 \ --max-requests=5000 \ --vacuum requirements.txt django==4.1.3 django-cors-headers pytest pytest-django coverage uwsgi -
Form wont update home db page. django and python
My django project wont update my home db page with the information from the join.html page. My urls.py file from django.urls import path from . import views urlpatterns = [ path( '' , views.home, name ="home"), path('join',views.join, name ="join"), ] views.py from django.shortcuts import render from .models import PersonInfo from .forms import PersonInfoForm import csv from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage #from rest_framework.decorators import action #from rest_framework.response import Response # Create your views here. def home(request): all_members = PersonInfo.objects.all return render(request, 'home.html', {'all':all_members}) def join(request): if request.method == "POST": #console.log("hello") #if "submitButton" in request.POST: form = PersonInfoForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'join.html', {}) else: return render(request, 'join.html', {}) forms.py from django import forms from .models import PersonInfo class PersonInfoForm(forms.ModelForm): class Meta: model = PersonInfo fields = ['customerName','address','age','email','accountId'] models.py from django.db import models from django.utils.translation import gettext # Create your models here. class PersonInfo(models.Model): accountId = models.IntegerField(default=None) customerName = models.CharField(max_length = 50, default=None ) address = models.CharField(max_length = 50, default=None) email = models.EmailField(max_length = 200, default=None) age = models.IntegerField(max_length = 3, default=None) def __str__(self): return self.customerName + ' ' #return self.accountId class book(models.Model): accountId = models.IntegerField( ("Account_ID") ) customerName = models.CharField( ("Customer_Name"), max_length = 50, default=None … -
How to prevent the creation of same object using Faker?
I have the following factory: class MonthFactory(factory.django.DjangoModelFactory): class Meta: model = Month year = factory.Faker("random_int", min=2014, max=2022) month = factory.Faker("random_int", min=1, max=12) Both year and month are unique in my Django class: class Meta: unique_together = ( "month", "year", ) When I want to create two objects for a test, let's say: month1 = MonthFactory() month2 = MonthFactory() sometimes I hit the jackpot and get: django.db.utils.IntegrityError: duplicate key value violates unique constraint because Faker got the same month and year for both objects. Is there a way to prevent this? -
Microsoft Access design View in django
How can I create one model that can takes all these models to look exactly like Microsoft Access Design View? I want to put these model into a one called TablesDesign so that it would enable user to design how their data could be stored in the application, is there anyone who can help? class Numbers(models.Model): num = models.IntegerField() class Characters(models.Model): char = models.CharField(max_length=1000) class Check(models.Model): check = models.BooleanField() class Date(models.Model): date = models.DateField() class LargeNumber(models.Model): larger_num = models.DecimalField(max_digits=30 decimal_places=15) class TablesDesign(model.Models): """" I want to put all these models into the TablesDesign to create something similar to Microsoft Access Design View. -
Django: Use Proxy Models and lost history
i implement two proxy models from a main model to use them in different ModelAdmins with different get_queryset´s. ALl is running fine. But i lost the change history of the object if it switches between the main model to the proxy model. Is there a solution for that ? -
why pipenv install gives me Package installation failed... error
i want to run django app so whenever i run pipenv install to install all the packages from my pipfile it gives me this error note : -i'm running on windows -cmake did nothing -it doesn't change anything if pipenv shell is opened or closed -i tried to delete pipenv manually and reinstall -i tried to install and update wheel and thank you in advance Installing dependencies from Pipfile.lock (631114)... An error occurred while installing boto3==1.26.86 --hash=sha256:7e8fc7bfef6481e48380d13e18a0a036413d126dc7eda37eadc1a052a3426323 --hash=sha256:e981703b76d2fb9274ce5cdda6ea382e29c9e7c65bc400c94c0a259b26f8914a! Will try again. An error occurred while installing botocore==1.29.86 ; python_version >= '3.7' --hash=sha256:8a4afc6d540c01890e434b9a31fb1b17f8c759001e12c7ad7c49f55ea5805993 --hash=sha256:6083c649791559dd916c9ff7ac62486b391f6f9464d3cf6964582a489c866b11! Will try again. An error occurred while installing charset-normalizer==3.1.0 ; python_full_version >= '3.7.0' --hash=sha256:4155b51ae05ed47199dc5b2a4e62abccb274cee6b01da5b895099b61b1982974 --hash=sha256:322102cdf1ab682ecc7d9b1c5eed4ec59657a65e1c146a0da342b78f4112db23 --hash=sha256:e89df2958e5159b811af9ff0f92614dabf4ff617c03a4c1c6ff53bf1c399e0e1 --hash=sha256:73dc03a6a7e30b7edc5b01b601e53e7fc924b04e1835e8e407c12c037e81adbd --hash=sha256:7381c66e0561c5757ffe616af869b916c8b4e42b367ab29fedc98481d1e74e14 --hash=sha256:34e0a2f9c370eb95597aae63bf85eb5e96826d81e3dcf88b8886012906f509b5 --hash=sha256:74db0052d985cf37fa111828d0dd230776ac99c740e1a758ad99094be4f1803d --hash=sha256:891cf9b48776b5c61c700b55a598621fdb7b1e301a550365571e9624f270c203 --hash=sha256:e1b25e3ad6c909f398df8921780d6a3d120d8c09466720226fc621605b6f92b1 --hash=sha256:fca62a8301b605b954ad2e9c3666f9d97f63872aa4efcae5492baca2056b74ab --hash=sha256:c36bcbc0d5174a80d6cccf43a0ecaca44e81d25be4b7f90f0ed7bcfbb5a00909 --hash=sha256:6734e606355834f13445b6adc38b53c0fd45f1a56a9ba06c2058f86893ae8017 --hash=sha256:3573d376454d956553c356df45bb824262c397c6e26ce43e8203c4c540ee0acb --hash=sha256:20064ead0717cf9a73a6d1e779b23d149b53daf971169289ed2ed43a71e8d3b0 --hash=sha256:78cacd03e79d009d95635e7d6ff12c21eb89b894c354bd2b2ed0b4763373693b --hash=sha256:9a3267620866c9d17b959a84dd0bd2d45719b817245e49371ead79ed4f710d19 --hash=sha256:d2686f91611f9e17f4548dbf050e75b079bbc2a82be565832bc8ea9047b61c8c --hash=sha256:d7fc3fca01da18fbabe4625d64bb612b533533ed10045a2ac3dd194bfa656b60 --hash=sha256:de5695a6f1d8340b12a5d6d4484290ee74d61e467c39ff03b39e30df62cf83a0 --hash=sha256:830d2948a5ec37c386d3170c483063798d7879037492540f10a475e3fd6f244b --hash=sha256:1435ae15108b1cb6fffbcea2af3d468683b7afed0169ad718451f8db5d1aff6f --hash=sha256:ea9f9c6034ea2d93d9147818f17c2a0860d41b71c38b9ce4d55f21b6f9165a11 --hash=sha256:75f2568b4189dda1c567339b48cba4ac7384accb9c2a7ed655cd86b04055c795 --hash=sha256:6f6c7a8a57e9405cad7485f4c9d3172ae486cfef1344b5ddd8e5239582d7355e --hash=sha256:22908891a380d50738e1f978667536f6c6b526a2064156203d418f4856d6e86a --hash=sha256:dd5653e67b149503c68c4018bf07e42eeed6b4e956b24c00ccdf93ac79cdff84 --hash=sha256:ac3775e3311661d4adace3697a52ac0bab17edd166087d493b52d4f4f553f9f0 --hash=sha256:628c985afb2c7d27a4800bfb609e03985aaecb42f955049957814e0491d4006d --hash=sha256:a04f86f41a8916fe45ac5024ec477f41f886b3c435da2d4e3d2709b22ab02af1 --hash=sha256:04afa6387e2b282cf78ff3dbce20f0cc071c12dc8f685bd40960cc68644cfea6 --hash=sha256:12d1a39aa6b8c6f6248bb54550efcc1c38ce0d8096a146638fd4738e42284448 --hash=sha256:3160a0fd9754aab7d47f95a6b63ab355388d890163eb03b2d2b87ab0a30cfa59 --hash=sha256:3d9098b479e78c85080c98e1e35ff40b4a31d8953102bb0fd7d1b6f8a2111a3d --hash=sha256:0be65ccf618c1e7ac9b849c315cc2e8a8751d9cfdaa43027d4f6624bd587ab7e --hash=sha256:ac0aa6cd53ab9a31d397f8303f92c42f534693528fafbdb997c82bae6e477ad9 --hash=sha256:b116502087ce8a6b7a5f1814568ccbd0e9f6cfd99948aa59b0e241dc57cf739f --hash=sha256:10c93628d7497c81686e8e5e557aafa78f230cd9e77dd0c40032ef90c18f2230! Will try again. An error occurred while installing colorama==0.4.6 ; platform_system == 'Windows' --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44! Will try again. An error occurred while installing django==4.2b1 --hash=sha256:33e3b3b80924dae3e6d4b5e697eaee724d5a35c1a430df44b1d72c802657992f --hash=sha256:9bf13063a882a9b0f7028c4cdc32ea36fe104491cd7720859117990933f9c589! Will try again. An error occurred while installing django-admin==2.0.2 --hash=sha256:a92f9fb21f63edabb5db9030f36b62c6c16a0187183e7e7de4142aee4472b70f --hash=sha256:43c9f94ca5ad498789c0282691931c609c8e26db61aeb49ae8ad90d15b80cb75! Will try again. An error occurred while installing django-excel-response2==3.0.5 --hash=sha256:ba908be16decbdc97b998bd20e596c27da78d23f97b533853c778c8c9c0974e3 --hash=sha256:4bbdd374cadd2d85723d5cd4b49822301141f7e4fef69616639cf3b7535e9ea5! Will try again. An error occurred while installing django-six==1.0.5 … -
Django: How to make model for list of string as one-to-many relation?
I have data like so: [ { "name": "Alice", "hobbies": ["programming", "swimming"] }, { "name": "Bob", "hobbies": ["sleeping", "skiing", "skating"] } ] I want to be able to use hobbies for later filtering, so I would like to have separate Hobby model with many-to-one relation to the Person model. What is a good practice to do so? Is there any simple way how to save person and hobbies at once (for example using singular serializer) and/or use serializer to retrieve data in the simmilar fashion as the input? -
Switched from WSGI to ASGI for Django Channels and now CircleCI throws "corrupted double-linked list" even though tests pass
I've been working on a project which requires WebSockets. The platform is built with Django and was running the WSGI server gunicorn. We decided to implement WebSockets using Django Channels. I set everything up including switching from gunicorn to the ASGI server daphne. Everything works great in local development environment. Deployment to AWS is working and everything works great on dev/staging. pytest works and all tests pass locally. On CircleCI all the tests are passing, but at the end of the "test" step we get the following and CircleCI shows a failed status: ================== 955 passed, 2 skipped in 216.09s (0:03:36) ================== corrupted double-linked list /bin/bash: line 2: 278 Aborted (core dumped) poetry run coverage run -m pytest $TESTFILES -vv --junitxml htmlcov/junit.xml Exited with code exit status 134 CircleCI received exit code 134 There are no other errors, warnings, or unexpected output. I cannot replicate the issue outside of CircleCI. I tried adding the @pytest.mark.asyncio decorator to the one async test we have and still got the above. Even when I totally remove said test CircleCI still throws the same. Google has not been helpful. Edit: This same thing has also happened a couple of times during the "migrate" step … -
Python Django: Inline edit and sub-total automatic
I have a simple application for forecasting hours in projects for team members. The 'view' mode: For the "edit" mode I have this interface: Instead of a new view/template for "edit" I would like to have inline edit functionality. Is that feasible with Python Dango only as I don't want to use jquery or JavaScript. Similarly, can the sub-total be calculated automatically on the page just using Python Django? -
Using shell_plus doesn't import models with the same name
Let's say we have app1 and app2 that both have models MyModel. When using the console, I've noticed that app1's MyModel is the only one that is imported: python manage.py tenant_command shell_plus The above command only imports the first MyModel, and I'm assuming it doesn't do the second since there's already a MyModel imported. Is there anyway to deal with the above? Thanks I've tried to use import as but that doesn't seem to work and causes issues in a larger codebase. I can get around this by manually importing the model, but that will overwrite the one that's already imported within shell_plus -
Nginx no such file or directory unix:/run/gunicorn.sock
Разворачиваю Django на сервере. Использую Nginx и gunicorn. После настройки, получаю ошибку 502 от Nginx. В логах запись о том, что не найден файл unix:/run/gunicorn.sock, хотя файл существует и gunicorn запущен Логи Nginx (https://i.stack.imgur.com/Ru8xK.jpg) Конфиг Nginx (https://i.stack.imgur.com/VlBiD.png) Настройки Gunicorn (https://i.stack.imgur.com/CT5XP.png) Статус Gunicorn (https://i.stack.imgur.com/lj4tS.png) -
Django - New object is not created if html action argument is provided
I have simple contact form: <form method="post"> {% csrf_token %} {{ form_email.as_div }} {{ form_message.as_div }} <button name="submit">Send</button> </form> When text is provided in both fields (email and message) and then the user click on submit button, the data should be saved in data base. View function: def index(request): """The home page.""" # Send a message. if request.method != 'POST': # No data submitted; create a blank form. form_email = EmailForm() form_message = EmailMessageForm() else: # POST data submitted; proecess data. form_email = EmailForm(data=request.POST) form_message = EmailMessageForm(data=request.POST) if form_email.is_valid() and form_message.is_valid(): form_email.save() email = Email.objects.last() message = form_message.save(commit=False) message.email = email message.save() # Display a blank or invalid form. context = {'form_email': form_email, 'form_message': form_message} return render(request, 'home/index.html', context) Until now everything works as expected, but when I add action argument in order to redirect the user to the 'Thank you' page if form has been sent, the data is not saved. <form action="{% url 'home:contact_thank_you' %}" method="post"> {% csrf_token %} {{ form_email.as_div }} {{ form_message.as_div }} <button name="submit">Send</button> </form> Do you have any idea why the data is not saved when I add the action argument? -
How to filter ManyToMany fields using django-filter
How can I filter a ManyToMany field with django-filter I would like to display an input field on a template where you can filter Student to get these results: all of the Students that speak English (Student.languages contains 'English') all of the Students that speak English and German (Student.languages contains 'English' and 'German') # models.py class Student(models.Model): name = models.CharField(...) languages = models.ManyToManyField(Language) class Language(models.Model): language = models.CharField(...) # English / German / ... level = models.CharField(...) # B1 / B2 / C1 / ... #filters.py import django_filters as filters from .models import Employee class EmployeeFilter(filters.FilterSet): class Meta: model = Employee fields = ['name', 'languages'] How should I modify the EmployeeFilter to make it ready to filter the Students according to their spoken languages? I tried declaring a class variable named languages like so: class EmployeeFilter(filters.FilterSet): languages = filters.ModelChoiceFilter( queryset = Languages.objects.all() ) class Meta: model = Employee fields = ['name', 'languages'] but it did not work, the filter had no effect. Thanks for your help, it is well appreciated! -
subprocess.PIPE not working in django model
So I have this model in which there is isRunning property. When it is set to True it spawns a subprocessing instance and saves it to subprocessObject . It looks like this. class Monitor(models.Model): Name = models.CharField(max_length=143) # Some other stuff CommandToExecute = models.CharField(max_length=1000, default="python -c print('HelloWorld')") subprocessObject = None @property def isRunning(self): return False @isRunning.getter def isRunning(self): if self.subprocessObject is None or self.subprocessObject.poll() is None: return False return True @isRunning.setter def isRunning(self, value): if value is True and self.isRunning is False: self.subprocessObject = subprocess.Popen(self.CommandToExecute.split(" "), stdout=sys.stdout, stdin=sys.stdin, shell=True) elif value is False and self.isRunning is None: self.subprocessObject.stdin.close() self.subprocessObject.stdout.close() self.subprocessObject.terminate() self.subprocessObject == None def __str__(self): return self.Name For now I have a simple file that prints something each second with flush=True. The problem is that there is an error looking like this: OSError: [Errno 22] Invalid argument Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp1252'> OSError: [Errno 22] Invalid argument When I changed subprocess.PIPE to sys.stdout and when I started the subprocess in a view it worked as expected so it's probably problem with subprocess.PIPE in models? Should I start the process in a view or is there an solution? -
Django Form auto submit when user open page
I have different forms on my template. Each of these forms are displayed against specific venues for which rules/ conditions are set. The submission of the form results in a set of points being added. The rule I am struggling with relates to the following situation: If a user opens a page of a venue_1 and if venue_1 has a rule that considers that +1 is added when the page is open; then +1 point is added to the user point count on page load. It seems in order to achieve this I need to use some JavaScript. As this is a recurring question on this forum I tried the different solutions offered but cannot seem to make it work. I must be missing something. models.py class Venue(models.Model, HitCountMixin): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class VenueLoyaltyPointRule(models.Model): venue = models.ForeignKey(Venue, null = True, blank= True, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="loylaty_points_rule", null = True, blank=True) auto_submit = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) views.py def venue_loyalty_add_point_rule(request,userprofile_id): url = request.META.get('HTTP_REFERER') venue = UserProfile.objects.filter(user=request.user).values('venue') venue_loyalty_point_rule = get_object_or_404(VenueLoyaltyPointRule, venue=request.user.userprofile.venue) submitted = False if request.method == "POST": form = LoyaltyCardForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.add_points = venue_loyalty_point_rule.points data.user_id = userprofile_id data.venue_id = venue data.save() form.save() messages.success(request, 'Points added!') return … -
ProgrammingError: column ... must appear in the GROUP BY clause or be used in an aggregate function
Django's documentation mentions aggregation: pubs = Publisher.objects.annotate(num_books=Count('book')) My code is full of similar constructs (adding a count of something to a queryset, using annotate), and this always worked well. Now suddenly, for reasons unknown, I'm getting this error: ProgrammingError: column ... must appear in the GROUP BY clause or be used in an aggregate function In fact, I have the same version of Django on my dev and prod, and everything works on dev, but fails on prod (typical). Spontaneously. For no apparent reason. And I cannot add the named column to the GROUP BY clause, because then it wants me to add the next column, and the next, and the next, etc. I can also not add some random aggregate function. In short: the solutions that the error mentions make no sense! There are many more questions with this same error, many unanswered. I have no solution, but it seems this error started appearing lately, in Django versions 4+, at least for me. I've tried the failing SQL query directly within Postgres and it fails there as well, of course, with exactly the same error. The fault is not with Django. The only way to make this annotate query … -
Stop logging parameters for django background tasks?
I'm using Django Background Tasks in my app for a task that requires user authentication. To create the task, I use a command like: my_cool_task(pks, request.POST.get('username'), request.POST.get('password')) I just realized that the username and password parameters are getting stored in the Django Admin tables for the tasks, which in this case creates a security issue. Is there a way to not store these parameters? Or is there a better way to authenticate a process that will take longer than it takes for a server timeout error? -
error : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I run the testapscheduler.py file, I get the above error. Is it because I only run one file in the Dajngo frame that I get the above error? How can I test it? testapscheduler.py: import logging from models import Todo from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) # 30分以内のTODOリストの数を出力 # ログの出力名を設定 logger = logging.getLogger('mylog') #ログレベルを設定 logger.setLevel(logging.DEBUG) #ログをコンソール出力するための設定 sh = logging.StreamHandler() logger.addHandler(sh) logger.debug(f'{len(todos)}個のTODOリストが締め切り30分以内にあります。') for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) def start(): scheduler =BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=2) # 2秒ごとに実行 scheduler.start() models.py from django.db import models class Todo(models.Model): title = models.CharField("タスク名", max_length=30) description = models.TextField("詳細", blank=True) deadline = models.DateField("締切") ttime = models.TimeField("") def __str__(self): return self.title -
I am working on django website for a restaurent ,in order to display every day's menu on my homepage what should I do
How to handle the django articles in order to display the menu of restaurent on my website's homepage every day? How can I add and update menu on homepage? I tried to add a modal based menu pop ups when admin logins but didn't worked -
ModuleNotFoundError: No module named 'bootstrap5'
i have installed boostrap 5 and wrote it down on installed apps and this error keeps popping up i´ve tried everything, unisntalling and installing, writing this: python3 -m pip install django-bootstrap5, and nothing works