Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SECURE_HSTS_SECONDS preventing access
I have a Django application deployed on a Linux virtual machine using Nginx as a reverse proxy. The website used to work very well and was accessible by users via HTTPS. However, I have set SECURE_HSTS_SECONDS = 3600 in the settings.py. This blocked access to the website, resulting in a timeout and a status code of 301. I then commented out this line of code. I expected the application to be accessible by users after an hour or so, since the variable SECURE_HSTS_SECONDS was set to 3600 seconds, but it still remains unaccessible. My relevant settings are: if not DEBUG: # Production settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # SECURE_HSTS_SECONDS = 3600 # NOTICE that this line was present before but is not commented out SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True Any idea as to why this might be the case? -
How would one scrape <figure> tags in bs4?
I am trying to scrape images off of https://nytimes.com, however , most of the main headlines' corresponding images on their website is stored inside a <figure> tag, not an <img> tag with a specific src attribute. How would i be able to scrape the urls for the images inside those <figure> tags so i'd then be able to aggregate them on my own website? -
django file opens locally but fails in server
What I wanted to achieve was for a user to upload a file through a form, lets say profile picture, My aim is to take that file, send it through imgbb's api and get the image url to store for use in my template later. I was able to achieve this with the piece of code below, that works locally(Windows) but as soon as I push to my production server(pythonanywhere in this case), the code fails. # CODE: def testingpage(request): image = '' url = '' if request.method == 'POST': pic = request.FILES['image'] url = upload_to_bb(request, pic) if url is not None: from django.contrib import messages messages.info(request, 'Uploaded Successfully') return render(request, 'test.html', {'image': url}) def upload_to_bb(request, pic): import os from django.conf import settings from django.core.files.storage import FileSystemStorage import base64 import requests base_url = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) fs = FileSystemStorage() filename = fs.save(pic.name, pic) file_path = f'{base_url}\media\{filename}' apikey = settings.IMGBB_API_KEY with open(file_path, "rb") as file: url = "https://api.imgbb.com/1/upload" payload = { "key": apikey, "image": base64.b64encode(file.read()), } r = requests.post(url, payload) js = r.json() if r.status_code == 200: data = js['data'] file.close() os.remove(file_path) return data['image']['url'] else: file.close() os.remove(file_path) from django.core.exceptions import ValidationError raise ValidationError("An error occurred processing the image") return None the culprit is … -
Reverse query via foreign key in Django
What query can I use to return all the Organisation objects that are members of a certain membership_id value? e.g. return all Organisation objects that have a membership_id = 101 class Organisations(model) id = models.CharField() class Memberships(model) membership_id = models.IntegerField() organisation_id = models.ForeignKey(Organisations) -
While testing a Django DRF application, how can I make the user in my tests superuser?
I currently have a Django Rest Framework application that executes different logic for superusers than regular users. I've written my tests using both rest_framework.test and pytest-django. My Tests are currently failing because of the error: TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User?. So because I don't have a user set (my app does not allow unauthenticated users), my code is trying to look for a profile of the user making the call and failing. Right now, I'm not looking to test the functionality of User logic. Is there a way to set the default user in test_settings.py to a superuser, or setup a superuser in the def setup(self, request) function at the start of each of my test classes? The DRF docs relating to authentication in testing seem to be geared towards testing the authentication itself as opposed to assuming authentication around other tests. Based on those docs, I think I could hack something together, but there must be a standard way of doing what I'm trying. From what I've read, I can use force_authenticate on a particular user, but it's unclear to me where that user comes from. Do I … -
How to create a table of events which are summarized daily
I have a model for user hours: class Hours(models.Model): project = models.ForeignKey(Project, related_name='project',on_delete=models.DO_NOTHING) owner = models.ForeignKey(User, related_name='owner', on_delete=models.DO_NOTHING, default=1) quantity = models.DecimalField(max_digits=10, decimal_places=2, default=1) product = models.ForeignKey(Product, related_name='product', on_delete=models.DO_NOTHING) inserted_at = models.DateTimeField(default=datetime.now, blank=True) date = models.DateTimeField(default=datetime.now, blank=True) and I want to display the hours in a django template as a table so that the hours are grouped and summed up daily. I understand that I cannot do the math in template, so I need to do it in view, but can you please give me some hints for that? Indrek -
How to filter class fields using objects.filter and the id=pk in django
Good evening I would like to ask for some assistance am trying to filter the title of a post so I can write the title into a file to track user activity. This is my code for writing in the file: ''' def cover(request,pk): text = coverposts.objects.get(id=pk) thistime = datetime.datetime.now() Name = coverposts.objects.get(title__id=pk) articlefile = open('useractivity.txt','a') articlefile.write('\n'+ str(Name) + ', '+ str(thistime)) articlefile.close() return render(request,'cover.html',{'text':text}) ''' And this is the class I wish to get information from : ''' class coverposts(models.Model): title = models.CharField(max_length=100) visual = models.ImageField(upload_to='images') subtitle = models.CharField(max_length=100) body = models.CharField(max_length=100000000) created_at = models.DateTimeField(default =datetime.now(), blank= True) ''' Kindly advise where am going wrong -
Celery Child Tasks Don't Run in Correct Queues on ECS
I have a django project that uses celery for task management and rabbitmq for the broker. The tasks are divided into multiple queues and in production these queues run in separate ECS containers. All the period tasks defined in celery.py scheduled via celery-beat run in the correct queues however when defining the queue inside a task using apply_async they always spawn in the default. 'default_task': { 'task': 'webapp.tasks.default_task', 'schedule': crontab(minute="*/1"), }, 'parent_task': { 'task': 'webapp.tasks.parent_task', 'schedule': crontab(minute="*/1"), 'options': {'queue' : 'secondary'} }, @shared_task(ignore_result=True) def parent_task(): qs = SomeModel.Objects.filter(status='in progress') task_expiration = 3600 for sm in qs: child_task.apply_async((sm.id,), expires=task_expiration, queue='secondary') I can confirm that the tasks are running just not on the specified queue which creates issues with timing due to potential noisy neighbors on the default queue container. Versions: django: 3.0.1 celery: 5.0.0 rabbitmq: 3.8.11 python: 3.8 -
Django dates calculator
this application should take a date from the user, store it in the database then count 9 days after it and show those 10 days in a list, I managed to make two views one to count the 10 days and show them in a list. The other view is to take the day from the user and store it in the database, now I want to connect both so by the end of the process I want the user to select the date then the application automatically stores the date and counts them and show the list. Models: from django.db import models from django.db.models.fields import DateField from datetime import datetime from django.db.models import CharField, Model # Create your models here class Event(models.Model): title = models.CharField(max_length=40) start = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) end = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) def __unicode__(self): return self.title class PeriodDate(models.Model): per_date = models.CharField(max_length=15) serializer: from dataclasses import fields from rest_framework import serializers from .models import PeriodDate class PeriodDateSerializer(serializers.ModelSerializer): class Meta: model = PeriodDate fields = '__all__' URLs: from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('CalendarCount', views.CalendarCount, name= 'index' ), path('form', views.form), ] Views: @api_view(['GET']) def CalendarCount(request): #Taking date … -
Why does Celery task autodiscovery never trigger under Django?
I've got Celery 5.2.6 and Django 3.0.6. Everything is working except task autodiscovery under Django. If I run celery worker, the worker triggers autodiscovery, finds all my tasks, and displays them in a list as part of it's startup process. However, if I run my Django app or Django shell, this never happens. Additionally, even though the docs promise that accessing the task registry will trigger autodiscovery, it does not. I print app.tasks, I call app.tasks.keys(), and still no autodiscovery - it only shows the tasks that are built-in or were registered when the module containing them happened to be imported for other reasons. What do I need to do to trigger task autodiscovery? PS - If I try adding force=True to app.autodiscover_tasks(), it fails because the Django app registry hasn't finished loading at that time. -
Django image does not duplay
I'm new to Django, and I encounter this problem with images that I can't solve... The path is like this: Django-Project, Profiles, static, media, profileIMG. Here is my model. from django.db import models from accounts.models import NewUser class UserProfile(models.Model): user = models.OneToOneField(NewUser, on_delete=models.CASCADE) profile_pic = models.ImageField(default='Untitled.png', upload_to='profileIMG') def __str__(self): return self.user.username settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' MEDIA_URL = '/media/' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('', include('profiles.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) form.py from django.forms import ModelForm from .models import UserProfile class ProfileForm(ModelForm): class Meta: model = UserProfile fields = '__all__' exclude = ['user'] view.py function @login_required(login_url='login_user') def profiles(request): indexID = request.user form = ProfileForm(instance=indexID) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=indexID) if form.is_valid(): messages.success(request, ("The file is valid")) form.save() else: messages.success(request, ("Invalid File.")) context = {'form': form} return render(request, "profiles/profiles.html", context) And my template profiles.html. {% load static %} <div class="main"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <img class="profile-pic" src="{{ request.user.UserProfile.profile_pic.url }}"/> <p>This is profile page </p> <span>Hello, {{request.user}} </span> <p>{{ form }}</p> <input class="imgBTN" type="submit" name="imgBTN"> <span><a href="{% url … -
warnings.warn("DateTimeField %s received a naive datetime (%s)"
I use django simple-history to get history on my models I then search the history results by date but I get the error below. How can I format the date? RuntimeWarning: DateTimeField HistoricalIssue.history_date received a naive datetime (2022-04-13 10:34:32) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" def SearchByDate(request): date_search = request.POST['date-search'] if date_search: admin_hist_search_results = Issue.history.filter(history_date=date_search) -
can you help to find a mistake?
Terminal says that i didn't defined DJANGO_SETTINGS_MODULE but i tried as i thought every method to do it and so far nothing helper (coding on windows) Can someone help me out please? I am stuck and dont know what to do Maby this will help - i run my virtual env through Anaconda - conda activate djangoenv raise ImproperlyConfigured(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. from faker import Faker from app.models import AccessRecrod, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get topic for entry top = add_topic() # create fake data for entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create new webpage entry webpg = Webpage.objects.get_or_create( topic=top, url=fake_url, name=fake_name)[0] # create fake access record acc_rec = AccessRecrod.objects.get_or_create( name=webpg, date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete!') -
Error 500 on Websocket, deploying Django-app on Heroku
I'm having some problems with websockets that I don't have locally. The problem is that heroku is telling me that there is a 500 error. My settings on prod: ASGI_APPLICATION = 'config.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis_url")] }, }, } My ASGI.py import django from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from my_app.chat import ( routing, ) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) I'm ready using wss instead of ws, and that not the problem. Thanks! -
How to use Django Filter with Arrayfield
Is it possible to use django-filter BaseInFilter with with django ArrayField? Here is a sample of what I am trying to do; models.py class Stays(models.Model): best_describes_house = ArrayField( models.CharField(max_length=500, blank=True, null=True), default=list, ) filterset.py class ItemInFilter(filters.BaseInFilter, filters.CharFilter): pass class StayFilter(filters.FilterSet): best_describes_house__in = ItemInFilter( field_name="best_describes_house", lookup_expr="in" ) class Meta: model = Stays fields = [ "best_describes_house__in", ] I am trying to make a request to http://127.0.0.1:8000/api/v1/stays/best_describes_house__in=villa,lake. I keep getting; operator does not exist: character varying[] = text[] LINE 1: ...ays" WHERE "lodging_stays"."best_describes_house" IN (ARRAY[... Am I doing something wrong? I have also tried doing this using IntegerField as stated from this example in the documentation - BaseInFilter, and it works fine -
Why Web server like apache/nginx cant directly server web apps made in django or flask framework?
I would like to know what's the need of this middle man- application servers like uwsgi, gunicorn. why cant a web server like Apache and Nginx directly serve a web app built in Django or flask. if your answer is that the uwsgi converts the request into a python understandable language. please elaborate on what kind of request python needs which it will understand. -
how do i get the highiest occured user in a table in Django
please I need help with this, am building an app that allows users to send out invites, and I want to get the user with the highest sent out invitations, how do I go about it. my model is as below. class Invite(models.Model): host_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL) invite = models.CharField(max_length=200, null=True,blank=True) def __str__(self): return self.name``` -
Issue migrating on m1 mac: geos incompatible architecture
I have run through a setup and I'm having issues migrating my app (within my venv). When I run python manage.py migrate I recevie this error: OSError: dlopen(/opt/homebrew/opt/geos/lib/libgeos_c.dylib, 0x0006): tried: '/opt/homebrew/opt/geos/lib//libgeos_c.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/opt/geos/lib/libgeos_c.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/opt/geos/lib//libgeos_c.1.16.0.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/Cellar/geos/3.10.2/lib/libgeos_c.1.16.0.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')) I've tried the answers to this question (missing libgeos_c.so on OSX), but none of them are working for me. I've also tried adding export DYLD_LIBRARY_PATH=/opt/homebrew/opt/geos/lib/ to my ~/.bash_profile. The output of file /opt/homebrew/Cellar/geos/3.10.2/lib/libgeos.dylib = /opt/homebrew/Cellar/geos/3.10.2/lib/libgeos.dylib: Mach-O 64-bit dynamically linked shared library arm64 The output of file $(which python3) = /Users/danieljohnson/Documents/code/project/venv/bin/python3 (for architecture x86_64): Mach-O 64-bit executable x86_64 /Users/danieljohnson/Documents/code/project/venv/bin/python3 (for architecture arm64): Mach-O 64-bit executable arm64 I'm not sure where to go from here. -
Google Drive API, Python, Django
I have some csv files that I want to generate everytime I run the script and upload them directly to google drive. When you have the files locally, it is easy to upload them. But, when I want to upload them I can't do that. I got this error instead : TypeError: expected str, bytes or os.PathLike object, not _csv.writer I am using googleapiclient.MediaFileUpload to upload the files, and the method Create_Service from Google. Here is a snippet of my code: from datetime import datetime from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload from .Google import Create_Service @api_view(['GET']) def uploadFile(request): current_date = datetime.today().strftime("%d-%m-%y") content_disposition = 'attachment; filename=' + \ 'solde_quotidien_' + str(current_date) + '.csv' response = HttpResponse() response['Content-Disposition'] = content_disposition writer = csv.writer(response) writer.writerow(['Date', 'Compte', 'Nom du client', 'Solde', 'Hold Balance', 'Type client']) client = ['2022', '34995277', 'Mehfoud', '1000000', '500'] writer.writerow(client) # Upload a file # Le nom sur le cloud file_metadata = { 'name': 'test.csv', 'parents': ['1QXu_mk5lWbNQyk-EiBnRSIQYmXqNmAdm'] } media_content = MediaFileUpload(writer, mimetype='text/csv') file = service.files().create( body=file_metadata, media_body=media_content ).execute() print(file) return response Apparently, the problem is with MediaFileUpload. What should I do in this situation? Thanks in advence. -
Error - type object '' has no attribute '' when calling class method
So I'm having a pretty weird issue with my Django app. I have a model called acsUser with a class method called getAcsMgr that should return a list of managers who have employees with access to the system. When running the app using the runserver management command this works just fine, but when running the server using Gunicorn and Nginx and navigating to the view being served the list as context I get type object 'acsUser' has no attribute 'getAcsMgr'.I'm not sure why this works locally but not when running it on the server. Please see the model and information below. Model: class acsUser(models.Model): # Everything but the adAcct field is information pulled directly from ACS using it's API call description = models.CharField(max_length=200, null=True) acsId = models.CharField(max_length=20, null=True) identityGroupName = models.CharField(max_length=200, null=True) acsName = models.CharField(max_length=20, null=True) fullName = models.CharField(max_length=200, null=True) jobTitle = models.CharField(max_length=200, null=True) supervisor = models.CharField(max_length=200, null=True) location = models.CharField(max_length=200, null=True) userDefEmail = models.CharField(max_length=200, null=True) userDefManagerId = models.CharField(max_length=200, null=True) legacySystem = models.CharField(max_length=20, null=True) created = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) enabled = models.CharField(max_length=20, null=True) lastModified = models.CharField(max_length=200, null=True) maxFailureEnabled = models.CharField(max_length=20, null=True) adAcct = models.ForeignKey('employee', null=True, blank=True, on_delete=models.CASCADE, related_name='ACSadAccount') # What to return when an instance is called … -
Why can't find or install home module in Django?
I am new to Django and is learning it from a youtube video. In the video the tutor does this from home import views. Now when i try to do the same thing i get an error saying "Unresolved reference home". So i tried installing home using pip installer but is constantly getting the following error:- Collecting uwsgi>=2.0 Using cached uwsgi-2.0.20.tar.gz (804 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\clash\AppData\Local\Temp\pip-install-gpajfqiw\uwsgi_5085974451e542118156b6196d19b2cf\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\clash\AppData\Local\Temp\pip-install-gpajfqiw\uwsgi_5085974451e542118156b6196d19b2cf\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname'. Did you mean: 'name'? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. Can somebody please tell me why this is happening and what is the solution to this error. … -
Python got error "NameError: name '_mysql' is not defined"
With Python 3.7.9, Django 3 and MariaDB, the application always fails with the error "NameError: name '_mysql' is not defined". Please see the exception trace and pip package list attached in the Details section below, and let me know if you need to see the yum package information. We highly appreciate your help. Details: 1. The full exception trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/data/app/venv3.7/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libperconaserverclient.so.21: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/data/app/venv3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/data/app/venv3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/data/app/venv3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/data/app/venv3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/data/app/venv3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/data/app/venv3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/data/app/venv3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/data/app/venv3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", … -
How to make static directory in Django
I created static directory which included css and image files in my Django project. When I run my project the css do display("GET /static/website/barber.css HTTP/1.1" 200 69) but the images do not("GET /static/website/images/balloons.gif HTTP/1.1" 404 1840), -
Uploading story to user story field without creating new story object ,but rather add to already upload stories of that user
Okay I have been stack in trying to have user create stories and add to their already uploaded stories in the backend database, but my current challenge is each time that a user uploads a story it doesn't add the story to the already existing field for that user, but rather create a new story object for that user! Is there a way that i could let users upload their new stories to add to already uploaded stories of that user ? My view for creating stories. def create_story(request): if request.method == "POST": form = StoryImageForm(request.POST, request.FILES) videos =request.FILES.getlist('video') images = request.FILES.getlist('image') title = request.POST['title'] # slug = str(title).lower().replace(" ", "-") story_data = Story(user=request.user,title=title) story_data.save() if form.is_valid(): data = form.save(commit=False) for image in images: data = StoryImage(post=story_data,user=request.user,images=image) data.save() return redirect('feed:feed') return render(request,"story/create_story.html") -
django admin panel healthcheck
I want to create a healthcheck endpoint for my django admin panel. I want to register it via admin.site.register_view (I am using the adminplus package) but I can't figure out how to made it accessible to the public, without the need to authenticate first. Any ideas?