Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django channels are not receiving headers?
I am trying to code simple python websocket client that will communicate with django channels. I am using python websockets library to achieve that. After running the following function I expect the get custom headers in scopes['headers'] async def connect(self): async with websockets.connect( f'ws://{self.HOST}:{self.PORT}/{self.URL_PATH}/{self.ID}/', extra_headers=[ ('CUSTOM_HEADER_1', 'NyNLFijhMasdaasdssA21TST1aJL_zLDArCbr8o',), ('CUSTOM_HEADER_2', '0',), ('CUSTOM_HEADER_3', '21312312',), ('CUSTOM_HEADER_4', 'dasdsadwq',), ('CUSTOM_HEADER_5', 'dshaghdashdghasdgjhsgkagukILKDSLHFb') ] ) as ws: await ws.ping() Instead of my custom headers I receieve following headers in the scope [(b'host', b'localhost:8001'), (b'upgrade', b'websocket'), (b'connection', b'Upgrade'), (b'sec-websocket-key', b'9asdasdasjAc9ruOg=='), (b'sec-websocket-version', b'13'), (b'sec-websocket-extensions', b'permessage-deflate; server_max_window_bits=12; client_max_window_bits=12'), (b'user-agent', b'Python/3.8 websockets/10.0')] -
Google Calendar API authorization working on localhost but not on Heroku
I want to use the Google Calendar API for my Django application. I have followed the instructions here: https://karenapp.io/articles/how-to-automate-google-calendar-with-python-using-the-calendar-api/ I have also added the redirect uri's in Google API - seems like a browser tries to open up on the server side (as it does on local, but I am unable to manipulate it as the browser from the server side does not show up). Any ideas on what I can do? -
OIDC with Keycloak and Django - Missing States
I'm attempting to set up OIDC with Keycloak as my IdP and Django (using Django Rest Framework and mozilla-django-oidc) as my client server. I have got keycloak installed and a rough Django application stood up that successfully redirects to keycloak where I can then successfully authenticate (to keycloak), but when I'm redirected back to django I'm missing information, specifically oidc_states. The redirect to django triggers this log entry: [12/Oct/2021 08:28:06] "GET /api/oidc/callback/?state=QGsO26esqdtHZcsfRfYoXvUy0QWcGdZv&session_state=493887a4-600e-4dd2-aaaf-4134ea671c9a&code=dfe1573e-cf8e-4829-8874-a3500ba63712.493887a4-600e-4dd2-aaaf-4134ea671c9a.c1dfdb46-140c-4ccd-8308-6db3b468346a HTTP/1.1" 302 0 This contains three keys: state, session_state, and code. The default callback view provided by mozilla-django-oidc contains this: def get(self, request): """Callback handler for OIDC authorization code flow""" if request.GET.get('error'): if request.user.is_authenticated: auth.logout(request) assert not request.user.is_authenticated elif 'code' in request.GET and 'state' in request.GET: if 'oidc_states' not in request.session: return self.login_failure() # ... Because keycloak isn't making the redirect with oidc_states added, this is immediately failing and I haven't been able to figure out why. I'm guessing that the problem is with my keycloak client configuration? -
Dockerized django, permission denied
Hi I dockerized django and I have a problem, after computer restart I can not run my app because some "data/db" directory was added which throws an error - " Permission denied: '/home/maciej/djangoapp/fitshop/data/db'" It happens when I want to "runserver" or just git add . settings.py : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fituser', 'PASSWORD': 'fitpass', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yaml services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=fitshop - POSTGRES_USER=fituser - POSTGRES_PASSWORD=fitpass ports: - "5432:5432" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code restart: always ports: - "8000:8000" depends_on: - db -
Caching authentication result in django-rest-framework-jwt
I`m using Auth0 authentification in a webapp / django-server combination. Auth0 is not the fastest auth framework, it always takes 200ms to authenticate. My webapp sends a lot of requests to the django server, so I thought about caching the authentication for a few seconds. This improves the speed of my app a lot. Is this a good way? Do you see any disadvantages / security issues in doing it this way? django config: REST_FRAMEWORK = { (...) 'DEFAULT_AUTHENTICATION_CLASSES': ( (...) 'rg_auth.rest_framework_authentication_classes.RgJSONWebTokenAuthentication', (...) ), (...) } authentication class: import hashlib from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.authentication import get_authorization_header from django.core.cache import cache class RgJSONWebTokenAuthentication(JSONWebTokenAuthentication): def authenticate(self, request): # Get from cache cache_key = self._rg_get_cache_key(request) cached_user_payload_tuple = cache.get(cache_key) # Is cache set? if cached_user_payload_tuple: # Cache is set: Return user/payload tuple return cached_user_payload_tuple else: # Cache is not set: Authenticate and save tuple to cache for 10 seconds user_payload_tuple = super().authenticate(request) if user_payload_tuple: # Set cache cache.set(cache_key, user_payload_tuple, 10) # Return tuple return user_payload_tuple def _rg_get_cache_key(self, request): auth_header = get_authorization_header(request) auth_header_md5 = hashlib.md5(auth_header).hexdigest() return "RgJSONWebTokenAuthentication_{}".format(auth_header_md5) -
djnago project is not running on putty (digitalocean)
I trying to run my django project on putty (digital ocean). but when I am running this its not loading. getting error ERR_CONNECTION_TIMED_OUT I am not setting any environment variable. just trying to run project on IP address of putty this is my settings.py ALLOWED_HOSTS = [ '*',] Step 1 — Install Python and pip sudo apt-get update && sudo apt-get -y upgrade sudo apt-get install python3 sudo apt-get install -y python3-pip Step 2 — Install virtualenv pip3 install virtualenv Step 3 — Move to home cd /home mkdir Electronics cd Electronics Step 4— create virtual Environment and activate it virtualenv Unions . env/bin/activate it’s activated once the prefix is changed to (Unions) Step 5— Install Django pip install django Step 6 – Move our project outsite the Unions folder Step 7- sudo ufw allow 8000 Step 8— Move to project folder (Unions) root@localhost:/home/Electronics# cd Webproject/ Step 9—Run Project (Unions) root@localhost:/home/UnionElectronics/Webproject# python manage.py runserver ip_address:8000 I does this for run project on putty(digital ocean) ip. How can I run project on http://ip_address:8000/ -
Django Broken pipe
I opened the website I am currently working, in localhost with Django. The fonts, and layout has changed. The terminal displays broken pipe (don't know what it is). Font has changed and text has become bold. I restarted the server, but it was of no use. How can I fix this issue? The bootstrap navbar has changed, so has this paragraph What was the reason for this happening and how can I fix it? I have made no changes to the code and this just happened all of a sudden. Edit 1 : There are no database connections or any API calls -
Django save changes not reflecting on database
I know there are some similar posts, but nothing I've read could fix my issue. I have the following model: class Run(models.Model): id = models.AutoField(primary_key=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) description = models.TextField(blank=True, null=True) model = models.ForeignKey(Model, on_delete=models.CASCADE) script = models.ForeignKey(Script, on_delete=models.CASCADE) parameters = models.ForeignKey(Parameters, on_delete=models.CASCADE) weights = models.ForeignKey(Weights, on_delete=models.CASCADE, null=True) status = models.ForeignKey(Status, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) train_score = models.FloatField(blank=True, null=True) validation_score = models.FloatField(blank=True, null=True) and the following function: def save_run(run_id: str, model, train_score: float, validation_score: float): ... run: Run = Run.objects.get(id=run_id) run.train_score = train_score run.validation_score = validation_score run.save() but, even though it finds the run on the database, "saves successfully" and logs all attributes fine, even after saving it, the changes don't reflect on the database. I've tried forcing with update_fields=["train_score", "validation_score"] and force_update=True without success. Any ideas? -
receiver is not working in django signals
I've tried to implement django signal's m2m_changed from the documentation here https://docs.djangoproject.com/en/3.2/ref/signals/#django.db.models.signals.m2m_changed Whenever I add/remove new position from the admin panel, the total_price is supposed to change by using signal receiver. But the receiver is not responding at all. I am supposed to see the pre_save/post_save at the shell when a new position is added, and pre_delete/post_delete when a new position is removed as the value of the action. But in the shell absolutely nothing gets printed. Even not the string 'action' gets printed. So I understand that the receiver is not working. I can't seem to find the issue here. Kindly help me. my model is class Position(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.FloatField(blank=True) created = models.DateTimeField(blank=True) # overriding the default save method def save(self, *args, **kwargs): self.price = self.product.price * self.quantity return super().save(*args, **kwargs) def __str__(self): return f"id:{self.id}, product: {self.product.name}, quantity: {self.quantity}" class Sale(models.Model): transaction_id = models.CharField(max_length=12, blank=True) # In utils position = models.ManyToManyField(Position) total_price = models.FloatField(blank=True, null=True) #in signals salesman = models.ForeignKey(Profile, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) created = models.DateTimeField(blank=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f"Sales amount: {self.total_price}円" # overriding the default save method def save(self, *args, **kwargs): if self.transaction_id == '': … -
Django annotate a list of aggregate methods
I have this qs = queryset\ .values(x=F('timestamp'))\ .annotate(min=Min('speed'), avg=Avg('speed'), max=Max('speed')) \ .order_by('-x') which results in <MotionQuerySet [{'x': 1632249000, 'min': 77, 'avg': 83.4, 'max': 96}, {'x': 1632162600, 'min': 61, 'avg': 83.6667, 'max': 114}, ...] Is there any way to make this output like <MotionQuerySet [{'x': 1632249000, 'y': [77, 83.4, 96}, {'x': 1632162600, 'y': [61, 83.6667, 114]}, ...] ? I can achieve it by iterating over each object of the returned queryset and creating a list of dictionary but I am looking for a better approach. -
How to change image field into file field in django?
I have a model with imagefield in it, is there any way to change that into filefield. Please also explain way to identify image while uploading. -
Wrong Python version running in Docker
No matter what I try, my Docker container is using Python 3.10 rather than what I need and specify, which is Python 3.7. How can I force Docker to use 3.7 for a specific image/container? I'm a novice Docker user and some of these Docker configuration files were not written by me, so forgive my ignorance. The Error Here's the error. You can clearly see that Docker is using Python 3.10. website_1 | Traceback (most recent call last): website_1 | File "/code/manage.py", line 10, in <module> website_1 | execute_from_command_line(sys.argv) website_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line website_1 | utility.execute() website_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 357, in execute website_1 | django.setup() website_1 | File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup website_1 | apps.populate(settings.INSTALLED_APPS) website_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 120, in populate website_1 | app_config.ready() website_1 | File "/code/website/apps.py", line 11, in ready website_1 | import website.signals website_1 | File "/code/website/signals.py", line 4, in <module> website_1 | from wand.image import Image, Color website_1 | File "/usr/local/lib/python3.10/site-packages/wand/image.py", line 3383, in <module> website_1 | class Iterator(Resource, collections.Iterator): website_1 | AttributeError: module 'collections' has no attribute 'Iterator' Docker configuration files My Dockerfile FROM python:3.7 # Setup some other prereqs needed: RUN apt-get update && apt-get … -
Can I use Django admin panel as the only view for the admin of the site not for developer?
I am creating an E-Learning system (similar to Udemy) where I have instructors, students and admins. I was thinking to create a panel for each one of these stakeholders. My question is, can I use Django's admin panel, where I need this panel to block users and block a course and so on? Thank you. -
l'utilisation d'un channels_layer dans un models django [closed]
hello I want to communicate my Notification class with my websocket so that I register a new instance of the notification object that I can retrieve a message via my websocket unfortunately my code does not work as I expected Class notification here my : class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.TextField(max_length=300) is_seen = models.BooleanField(default=False) def __str__(self): string = f'{self.user} ({self.notification}): {"False" if self.is_seen is False else"True"}' return string def save(self, force_insert=False, force_update=False, using=None, update_fields=None): channel_layer = get_channel_layer() notification_count = Notification.objects.filter(is_seen=False).count() data = {'count': notification_count, 'courrent_notification': self.notification} async_to_sync(channel_layer.group_send)( 'notification_groupe', { 'type': 'disconnect', 'value': json.dumps(data)}) super(Notification, self).save() my model consumer: class Notification_consumer(WebsocketConsumer): def connect(self): self.room_group_name = 'notification_groupe' self.room_name = 'notification_consumer' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.room_name ) self.accept() self.send(json.dumps({"status": "connected to notification consumer!"})) def receive(self, text_data=None, bytes_data=None): print(text_data) self.send(json.dumps({"status": "notification consumer a votre service"})) def send_notification(self, event): print('send_notification') print(event) print('send_notification') def disconnect(self, code): self.send(json.dumps({"status": "déconnexion effectuée!"})) print('déconnecxion') -
How can i load .tar and do predictions in django
I am building a web application to make predictions using PyTorch. I have trained a model and saved the model weights in the .tar file and now I want to load the model and do predictions in Django how can I do it. need help I am attaching my prediction code below def predicting(model, device, loader): model.eval() total_preds = torch.Tensor() total_labels = torch.Tensor() print('Make prediction for {} samples...'.format(len(loader.dataset))) with torch.no_grad(): for solute_graphs, solvent_graphs, solute_lens, solvent_lens in tqdm(loader): outputs, i_map = model( [solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device), torch.tensor(solvent_lens).to(device)]) total_preds = torch.cat((total_preds, outputs.cpu()), 0) # total_labels = torch.cat((total_labels, data.y.view(-1, 1).cpu()), 0) # return total_labels.numpy().flatten(),total_preds.numpy().flatten() return total_preds.numpy().flatten() -
Django docker-compose-prod isn't work correctly
I'm trying to prep a Django application for production. I created an alternate docker-compose YML file where I specify DEBUG=False. However when I run the Django check for deployment, it says that DEBUG is set to True. $ docker-compose down $ docker-compose -f docker-compose-prod.yml up -d --build $ docker-compose exec web python manage.py check --deploy but in local server it is worked(I mean the debug is Turn off) How can I fix it? -
How to use reverse with optional parameters in django?
I have the below URL in which I pass an integer value (pk) now when I am calling reverse on this URL I am getting the below-mentioned error. urls.py urlpatterns = [ path('batch-postpone/<int:pk>/', postpone_batch, name='batch-postpone'), ] tests.py class ABCTestCases(APITestCase, TestCase): self.postpone_batch_url = reverse('batch-postpone') Error that I am getting... django.urls.exceptions.NoReverseMatch: Reverse for 'batch-postpone' with no arguments not found. 1 pattern(s) tried: ['batch\\-postpone/(?P<pk>[0-9]+)/$'] -
No pylint warning "Redefining built-in" for a class local variable
I came across a Django model like this: class Car(models.Model): type = CharField() ... However, pylint does not issue any warnings about redefining the built-in function type. It is only when I move it out of the class to the global scope pylint warns about this, but not within the class. Is this the expected behavior? If so, how can I override it to show warnings within classes or functions as well? VSCode 1.61.0 Ubuntu 20.04 Python 3.8.10 -
WSL2 - pip install django takes a long time (around 4 minutes to complete)
I just activated WSL2 on Windows 10. I already activated virtualenv to install django using pip install django. But it takes around 4 minutes to complete the installation. Is it normal for WSL2 to takes that long time only pip packages? Any tweaks to speed up pip install on WSL2? Here is the screenshot -
C# operator \n for string in HTML not working
Website on Django 3.2, Visual Studio 2019. It is necessary to transfer the text of the link description - a text string in the HTML code. There are special HTML codes &#10; &#13; for line feed and carriage return. Their use does not give the desired result. <br> - is working: <a href="link">Text3.<br>Text4.</a>. But why HTML special codes not working? {% extends "/layout.html" %}<!--♕-->{% block content %}<div class="Jambotron"> <h1>Welcome!</h1> <p class="lead">Text1!&#10;&#13;Text2.</p> <a href="link">Text3.&#10;&#13;Text4.</a> </div>{% endblock %} Example: special codes HTML did not work out as intended -
Django making url with slug but "django.db.utils.IntegrityError: UNIQUE constraint failed:" error occurs
I want to make url with building name using slug. ex) api/buildingdata/Abuilding And this url has review data. urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view()) ] models.py from django.db import models # Create your models here. from django.utils.text import slugify class buildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(unique=True, allow_unicode=True) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): self.slug = slugify(self.building_name, allow_unicode=True) return super().save(*args, **kwargs) class reviewData(models.Model): building = models.ForeignKey(buildingData, related_name='reviews', on_delete=models.CASCADE, null=False, blank=False) review_content = models.TextField() star_num = models.FloatField() errors File "c:\Users\admin\Desktop\crawler\crawling.py", line 190, in button_clicked crawling(search_key, search_cnt, file_name) File "c:\Users\admin\Desktop\crawler\crawling.py", line 133, in crawling buildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() File "c:\Users\admin\Desktop\crawler\crawling_data\models.py", line 17, in save return super().save(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\ProgramData\Anaconda3\lib\site-packages\django\db\models\sql\compiler.py", line … -
Django custom registration form errors
Hope you have wonderful day. I've build custom register form, but when form is not valid, the form returns without error on it. Example: Im inserting incorrect password to "confirm password" input, and after sending the form, no error could be found on the form it self. It might because im not returning the form correctly? This is my form.py file: class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=50, help_text='Required. Inform a valid email address.', widget=(forms.TextInput(attrs={'class': 'form-control'}))) password1 = forms.CharField(label=('Password'), widget=(forms.PasswordInput( attrs={'class': 'form-control'})), help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label=('Password Confirmation'), widget=forms.PasswordInput(attrs={'class': 'form-control'}), help_text=('Just Enter the same password, for confirmation')) username = forms.CharField( label=('Username'), max_length=150, help_text=( 'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), error_messages={'unique': ( "A user with that username already exists.")}, widget=forms.TextInput(attrs={'class': 'form-control'}) ) class Meta: model = User fields = ('username', 'email', 'password1', 'password2',) the signup function using the Signup form: csrf_exempt def signup1(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid() is False: form = SignUpForm() return render(request, 'accounts/register.html', {'form': form}) if form.is_valid(): print(str(form.cleaned_data["email"])) email = str(form.cleaned_data["email"]) username = str(form.cleaned_data["username"]) p1 = str(form.cleaned_data["password1"]) p2 = str(form.cleaned_data["password2"]) try: user1 = User.objects.get(email__exact=email) except: form = SignUpForm() return render(request, 'accounts/register.html', {'form': form}) if p1 != p2: form = SignUpForm() return render(request, 'accounts/register.html', … -
In my html template a tag href doesn't work
I am developing a project using django.But in html template href function doesn'work.When ı come to area,link is showing on the bottom of the page.But url doesn't work.Not just django url.When ı write there https://www.google.com,again it is not working.How can I fix it? index.html <div class="chat-users-list" style="height: 112%;"> <div class="chat-scroll" > {% for user in users %} <a class="media {% if forloop.counter0 == 0 %} read-chat active {% endif %} " href="{% url 'startChat' user.slug %}" > <div class="media-img-wrap"> <div class="avatar avatar-away"> <img src="{% static 'assets/img/patients/patient.jpg' %}" alt="User Image" class="avatar-img rounded-circle"> </div> </div> <div class="media-body"> <div> <div class="user-name">{{user.get_full_name}}</div> <div class="user-last-chat">Hey, How are you?</div> </div> <div> <div class="last-chat-time block">2 min</div> <div class="badge badge-success badge-pill">15</div> </div> </div> </a> {% endfor %} </div> </div> style.css .chat-window .chat-scroll { min-height: 300px; max-height: calc(100vh - 224px); overflow-y: auto; } .chat-cont-left .chat-users-list { background-color: #fff; } .chat-cont-left .chat-users-list a.media { border-bottom: 1px solid #f0f0f0; padding: 10px 15px; transition: all 0.2s ease 0s; } -
I cannot make user admin in django rest framework
I work on next.js Django project. I m testing admin functionality so i try to make a user admin. in django admin interface, I checked in user.is_staff and user.is_superuser but i still get the user.isAdmin false. I tried to do change the isAdmin from shell $ from django.contrib.auth.models import User $ user=User.objects.get(username="user@hotmail.com") # 'User' object has no attribute 'isAdmin' $ user.isAdmin # I manually set it to be True $ user.isAdmin=True $ user.isAdmin # True $ user.save() now I currently user.is_staff and user.is_superuser is selected from admin interface, I manually set the isAdmin property to True in shell, I exit, restart the server. I still get it False: I interacted with user in shell again, when I enter admin.isAdmin, i get the error "has no attribute isAdmin" -
Django - New URL not working in working app
I have an app in my project wich is working fine. Now i added a new URL to the url.py with my new view, got an 'not found' error. Now I set the url at first place of the urls.py and used an other view wich is definetly working with the original URL. Same issue. So in the same app where other views are displayed without any issue, the new one could not be found, weather with a new (maybo faulty view) or one that works perfectly with an other url. in the example tritemphyg is working perfectly with its url. But when I want to direct cis/ to the same view, it can now be found. from django.urls import path from . import views urlpatterns = [ path('cis/', views.TriTempHygView.as_view()), path('tritemphyg/', views.TriTempHygView.as_view()), path('cistern/', views.SpuKasView.as_view()), path('quadtemphyg/penis/', views.PenisView.as_view()), ]