Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON format from Django serializer
I am using Django serializer for JSON. Using the documentation here. https://docs.djangoproject.com/en/5.0/topics/serialization/ Why does the serializer produce messy output? The documentation offers no solution. How can I get a clean, well formatted JSON without pk and model? View from django.http import HttpResponse, JsonResponse from django.core import serializers @csrf_protect def cityLookup(request, **kwargs): country = kwargs.get('Country') city = kwargs.get('Place') queryset = GeoNames_location.objects.filter(geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city).order_by('-geo_population')[:5] data = serializers.serialize("json", queryset, fields=["geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code"]) return JsonResponse(data, safe=False) # Need security check Response "[{\"model\": \"ui.geonames_location\", \"pk\": 5128581, \"fields\": {\"geoAsciiName\": \"New York City\", \"geoLatitude\": \"40.714270\", \"geoLongitude\": \"-74.005970\", \"geoCountry_code\": \"US\", \"geo_population\": 8804190, \"geo_timezone\": \"America/New_York\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 4645421, \"fields\": {\"geoAsciiName\": \"New South Memphis\", \"geoLatitude\": \"35.086760\", \"geoLongitude\": \"-90.056760\", \"geoCountry_code\": \"US\", \"geo_population\": 641608, \"geo_timezone\": \"America/Chicago\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 4335045, \"fields\": {\"geoAsciiName\": \"New Orleans\", \"geoLatitude\": \"29.954650\", \"geoLongitude\": \"-90.075070\", \"geoCountry_code\": \"US\", \"geo_population\": 389617, \"geo_timezone\": \"America/Chicago\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 5101798, \"fields\": {\"geoAsciiName\": \"Newark\", \"geoLatitude\": \"40.735660\", \"geoLongitude\": \"-74.172370\", \"geoCountry_code\": \"US\", \"geo_population\": 281944, \"geo_timezone\": \"America/New_York\"}}, {\"model\": \"ui.geonames_location\", \"pk\": 4776024, \"fields\": {\"geoAsciiName\": \"Newport News\", \"geoLatitude\": \"36.980380\", \"geoLongitude\": \"-76.429750\", \"geoCountry_code\": \"US\", \"geo_population\": 182385, \"geo_timezone\": \"America/New_York\"}}]" -
Issues with Serving Django App via Subpath in Apache
I have a Django application (Django version 4.2.11) that I want to serve under a subpath using Apache. Specifically, I want to serve the app at https://example.com/subpath so that other Django app URLs can be accessed as subpaths. For example: https://example.com/subpath/admin should load the Django admin page. https://example.com/subpath/api should load the API endpoints. However, I am encountering a 404 error when I try to access these URLs. Here is my current Apache configuration to redirect Django app to a subpath: <VirtualHost *:443> ServerName example.com DocumentRoot /var/www/html SSLEngine on RewriteEngine on # Redirect /subpath to INTERNAL_IP:8000 RewriteCond %{REQUEST_URI} ^/subpath RewriteCond %{HTTP:Upgrade} =websocket RewriteRule /(.*) ws://INTERNAL_IP:8000/$1 [P,L] RewriteCond %{REQUEST_URI} ^/subpath RewriteCond %{HTTP:Upgrade} !=websocket RewriteRule /(.*) http://INTERNAL_IP:8000/$1 [P,L] ProxyPass /subpath http://INTERNAL_IP:8000/ ProxyPassReverse /subpath http://INTERNAL_IP:8000/ ProxyRequests Off </VirtualHost> My Django urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from apscheduler.schedulers.background import BackgroundScheduler from my_app.management.commands import run_schedules urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')), path('api/', include('auth_app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) admin.site.site_header = 'My API Administration' admin.site.index_title = 'My API Admin Area' admin.site.site_title = 'My API Administration' scheduler = BackgroundScheduler() scheduler.add_job(run_schedules.Command().handle, 'interval', minutes=0.50) scheduler.start() Issue Despite these configurations, I'm still … -
Filterset_class does not working when view is called from test
I have a drf method view: @action(detail=False, methods=["get"], filterset_class=None) def count(self, request, *args, **kwargs): ... and of course, there is a filterset_class defined on class level. When I called this endpoint from postman, this filterset_class override is working, but when I called it from tests, the override is not working. Im using APIRequestFactory to do the request from test like factory = APIRequestFactory(email=user.email) view = NotificationsMessagesView.as_view({"get": "count"}) response = view(request) result = response.render() assert result.data["count"] == 1 My versions: Django = "3.2" djangorestframework = "3.12.4" django-filter = "22.1" Could someone help me? I trying to find maybe so bugreports, but i dont find anything. I think, the override of filterset_class should be applied when the view is requested from tests. -
How to send MDM commands to push an app to iOS device in python
"""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Command</key> <dict> <key>Identifier</key> <string>com.zhiliaoapp.musically</string> <key>RequestType</key> <string>RemoveApplication</string> </dict> </dict> </plist>""" In this plist, I provide the command to remove a third-party application installation. I used to perform this task using Python 2.7, but I now want to update the code to Python 3. How can I send a command to an iOS device using Python and Django? This is a plist form of commands. -
Django with gunicorn: sending requests - concurrency
We've got a Django application configured with gunicorn. That means several workers are processed in parallel. Now for some functionality we need to call a service for reverse geocoding looking something like this: reverseGeocodingURL = s.geocodingURL + '?lat=' + str(latitude) + '&lon=' + str(longitude) + '&api_key=' + s.apiKey Now it appears that sometimes the responses seem to be not aligned to the requests. It's probably a concurrency issue when one gunicorn worker receives the reponse of a request issued by another worker. Is this possible? And what possibilities do we have to circumvent this problem? -
Display data into modal form through django
I am very much new to django. I am trying to display the details of a student record in a modal form once details button clicked. But it is showing an empty modal form. Below is the code snippet. Please let me know if I am doing something wrong here. Thanks in advance. Here are the views def student(request): students = Student.objects.values("standard__standard_name", "studentid","firstname","lastname","status","nationality","Gender") return render(request, 'student.html', { 'students':students }) def student_detail(request, studentid): try: student_object = Student.objects.filter(studentid=studentid) student = student_object.values("studentid","firstname","lastname","standard__standard_name","status","nationality","dob","Gender","religion","parent__parentid") print(student) except student.DoesNotExist: raise Http404('student not found') return render(request, 'student_detail.html', {'student':student}) student.html snippet <div class="tab-pane fade show active" id="show-students-pane" role="tabpanel" aria-labelledby="show-students" tabindex="0"> <table class="table table-striped table-bordered table-hover"> <th>Name</th> <th>Standard</th> <th>Gender</th> <th>Status</th> <th>Nationality</th> {% for student in students %} <div class="studentname"> <tr> <td>{{ student.firstname |capfirst }} {{ student.lastname |capfirst }}</td></a> <td>{{ student.standard__standard_name }}</td> <td>{{ student.Gender }} </td> <td>{{ student.status }} </td> <td>{{ student.nationality }} </td> <td><button type="button" class="modalbtn btn btn-primary" data-bs-toggle="modal" data-bs-target="#studentModal" onclick="localtion.href='/student/<studentid>/detail/ student.studentid'">Details</button></td> </tr> </div> {% endfor %} </table> <div class="modal" id="studentModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title" id="studentModal">{{ student.firstname }}</h4> <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <!-- Modal body --> <div class="modal-body"> {% include 'student_detail.html' %} </div> <!-- Modal footer --> … -
$ python -m django startproject mysite . Command 'python' not found, did you mean , it is not working [closed]
django-admin.py startproject mysite . refresh command not found $ python -m django startproject mysite . Command 'python' not found, did you mean : command 'python3' from deb python3 command 'python' from deb python-is-python3 -
Add custom field to wagtailadmin ModelAdmin
I'm trying to add a custom field to wagtail ModelAdmin, but not sure how to do that. I tried from wagtail_modeladmin.options import ModelAdmin, modeladmin_register from wagtail_modeladmin.views import EditView from django import forms from django.contrib.admin.utils import quote from wagtail.log_actions import registry as log_registry from dzen_wagtail.football_maps.models import FootballMap class FootballMapAdminForm(forms.ModelForm): extra_link = forms.URLField( label="Extra link", widget=forms.URLInput(attrs={"type": "button"}), ) field_order = ["tg", "name", "location", "history", "covering", "extra_link", "status"] class Meta: model = FootballMap fields = ["tg", "name", "location", "history", "covering", "extra_link", "status"] def __init__(self, *args, **kwargs): super(FootballMapAdminForm, self).__init__(*args, **kwargs) self.fields["extra_link"].initial = "https://example.com" class FootballMapEditView(EditView): def get_form(self): return FootballMapAdminForm(instance=self.instance) @modeladmin_register class FootballMapAdminSite(ModelAdmin): model = FootballMap menu_label = "Карта коробок" menu_icon = "circle-check" edit_view_class = FootballMapEditView def get_list_display(self, request): list_display = ["location", "status"] return list_display But looks like I go in wrong direction, and such can be achieved in ModelAdmin itself -
Django Postgresql ORM optimisation
I have a PostgreSQL view called view_sales_dashboard - this consists of several millions rows of daily sales data. In the Django view I want to present a table grouped by the products, with the columns as the total base_daily_pnl of different time periods - Daily, Month to date (MTD), Quarter to date (QTD), Year to date (YTD) and Inception to date (ITD) In order to try and limit the number of SQL queries I am creating 5 querysets to then generate the table. To improve the efficiency of this I investigated the logs and expected to see 5 SQL queries. However the logging shows 20 queries (5 product types * the 4 aggregate groupings + the daily series request). See below the Django code, ORM model and the logs. Can anyone advise 1.) why so many SQL queries are being triggered 2.) how to optimise? queryset_sales_all = SalesDashboard.objects.all() queryset_daily_products = queryset_pnl_all.filter(position_date__range=[latest_pnl_date_str, latest_pnl_date_str]).values('product').annotate(base_daily_pnl=Sum('base_daily_pnl'),base_lmv=Sum('base_lmv')) for daily in queryset_daily_product: matching_mtd = queryset_pnl_all.filter(position_date__range=[start_mth_str,latest_pnl_date_str]).values('product').annotate(mtd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) matching_qtd = queryset_pnl_all.filter(position_date__range=[start_qtd_str, latest_pnl_date_str]).values('product').annotate(qtd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) matching_ytd = queryset_pnl_all.filter(position_date__range=[start_year_str, latest_pnl_date_str]).values('product').annotate(ytd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) matching_itd = queryset_pnl_all.filter(position_date__range=[start_itd_str, latest_pnl_date_str]).values('product').annotate(itd_pnl=Sum('base_daily_pnl')).get(product=daily['product']) daily['mtd_pnl'] = matching_mtd['mtd_pnl'] daily['qtd_pnl'] = matching_qtd['qtd_pnl'] daily['ytd_pnl'] = matching_ytd['ytd_pnl'] daily['itd_pnl'] = matching_itd['itd_pnl'] pnl_product = SummaryPnlProductTable(queryset_daily_product) Below is the ORM model: class SalesDashboard(models.Model): unqiue_id = models.IntegerField(primary_key=True) sales_id = models.CharField(max_length=50) base_daily_pnl … -
Automatic Wi-Fi Setup Webpage: Implementation Guide
I want to create a webpage where i have my own WiFi when i give one qr to user the directly goes to webpage where user fill the mobile number and OTP verification after verification the Wifi automatically connect for 30 minutes to solve the problem to automatically connect wifi the resulted is this to solve the many people problem -
It is a good idea to put auth in TENANT_APPS in a multi-tenancy django app?
I'm preparing a multi-tenancy app with django. I need that a user only can access and manipulate the data of your own schema. For exemple, if a have domain_a and domain_b, some users should only acess domain_a data and another users only can access domain_b data, and never both. Cause this, I decide to put the auth apps inside tenant apps: SHARED_APPS = ( 'django_tenants', 'homecare_public', ) TENANT_APPS = ( 'homecare', 'account', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'django_seed', 'drf_yasg', ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = 'homecare_public.Client' TENANT_DOMAIN_MODEL = 'homecare_public.Domain' As you can see, things like 'django.contrib.admin' and 'django.contrib.auth' are inside tenant_apps. I wanna isolate the schemas, where each one have their own users! So my question is: is this a good idea? -
Django prefetch within model method
So I have a Django model which is a foreign key for several other models. I want to add a method to my model and see if my instance of the model actually has any related objects. Two questions: I'd like to do this with one query, but I'm unsure how to use prefetch_related with "self". How do I do this? Is there a way to just return True or False if a related model exists? For example, should I just use first? (I seem to recall there being a "correct" way to do this, but it's been a while, and I may be remembering flask.) Code example: from django.db import models class Person(models.Model): # <fields> def has_device(self): # ***prefetch related phones and laptops*** if self.phone_set.first() or self.laptop_set.first(): return True return False class Laptop(models.Model): owner = models.ForeignKey(Person) # <fields> class Phone(models.Model): owner = models.ForeignKey(Person) # <fields> -
Testimonial Section Doesn't Show in WebPage Cyberpanel
i would like to ask you a question about Webpage View in Cyberpanel, so i tried to host my django project to Cyberpanel hosting service, after a few configurations was made, the index.html is loaded nice with the content, but when i scroll to the bottom of the page, there is a missing secion in testimonial, which is it only show the title but not the carousel content that i made, i am pretty confused because i just start using Cyberpanel recently, and also whe i tried to inspect the page it looks like this : here is my testimonial section html : <!-- Testimoni --> <div class="container-xxl py-5"> <div class="container"> <div class="text-center mx-auto mb-5 wow fadeInUp" data-wow-delay="0.1s" style="max-width: 600px;"> <h1 class="text-uppercase">Apa yang mereka pikirkan?</h1> </div> <div class="owl-carousel testimonial-carousel wow fadeInUp" data-wow-delay="0.1s"> <div class="testimonial-item text-center" data-dot="<img class='img-fluid' src='{% static 'img/LIA.png' %}' alt=''>"> <h4 class="text-uppercase">Lia</h4> <p class="text-danger">Customer Langganan</p> <span class="fs-5">Glory Salon adalah tempat yang luar biasa! Pelayanan yang diberikan sangat profesional dan hasilnya selalu memuaskan. Saya sangat senang dengan perawatan rambut dan wajah yang mereka tawarkan. Saya merasa lebih percaya diri setelah perawatan di sini. Sangat direkomendasikan!</span> </div> <div class="testimonial-item text-center" data-dot="<img class='img-fluid' src='{% static 'img/AGUS.png' %}' alt=''>"> <h4 class="text-uppercase">Agus</h4> <p … -
Display pdf in the browser received by JavaScript async
I have a Django app, I make a call from JS to ask for a pdf. Django view returns an HttpResponse of application/pdf How do make JS to display the received application/pdf data as a pdf? Django View def pdf_generation(request): context = {} t = get_template('html_pdf.html') html_string = t.render(context) result = HTML(string=html_string) css = CSS('/static/css/pdf.css') pdf_in_memory = BytesIO() HTML(string=html_string).write_pdf(pdf_in_memory, stylesheets=[css]) return HttpResponse(pdf_in_memory.getvalue(), content_type="application/pdf") JS async function getData_pdf() { try { const response = await fetch('http://192.168.1.2:8000/pdf/'); if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } const data = await response.text(); data.type('application/pdf'); data.end(pdf, 'binary'); } catch (error) { console.error('There has been a problem with your fetch operation:', error); } }; -
Django: Screening dangerous characters from text input
I have a Django app where a few of the forms support a text input with maximum lengths of either 50 or 250 characters. In all cases, the data entered will be stored in the backend DB and will be available for later viewing upon request. In all cases, I'm using the cleaned_data() method when collecting user inputs from the form. And in all cases, the data is such that most "special characters" are unnecessary. (There are a few I'd like to allow for convenience & flexibility, such as hyphens or parentheses, but beyond that alphas & digits should cover it.) Given all that, I'm looking to put an extra layer of screening on these fields to prevent injections. Particularly XSS but other malicious input as well. I'm thinking the simplest approach is to block/reject the more dangerous characters -- angle brackets, curly braces, and forward/backslashes being the most obvious. My questions are: Are there any other characters I should block/reject to guard against injection attacks? Or, would I be better off going the whitelist route instead? Define the full set of permissible characters and reject anything not in the list? Or -- is this whole idea of field-by-field screening … -
Social authentication (DRF + Djoser), "non_field_errors": ["Invalid state has been provided."] after POST request with state and code
I am following this video tutorial and trying to implement Google social authentication using DRF, djoser and React. I type this in browser (GET request): http://localhost:8000/auth/o/google-oauth2/?redirect_uri=http://localhost:8000 I have the response like this (I am not sure if this url is safe to share, but anyway I changed it slightly) { "authorization_url": "https://accounts.google.com/o/oauth2/auth?client_id=836198290956-fe0ilujf6e23l882oumgkufi8qm6fg3m.apps.googleusercontent.com&redirect_uri=http://localhost:8000&state=eNwMFCmEplYgbUTTP9nnrQ6MduAPxzDY&response_type=code&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+openid+openid+email+profile" } I enter this response to the browser, this redirects me to google sign in page. Then I select my account, then I press continue. I am now redirected to localhost:8000 with this url http://localhost:8000/?state=eNwMFCmEplYgbUTTP9nnrQ6MduAPxzDY&code=4%2F0AcvDMrB6f3ZQuTD563Vxriu2n0VHmLEOHnDRqC6jD5BRm068jj2tyExxfZZJDFLAtcwYLg&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&hd=circle.help&prompt=consent My problem shows up here. I take state and code parameters from this url, and make POST request using Postman (without any body, just url, but I also set Content-Type header to application/x-www-form-urlencoded) to this url: localhost:8000/auth/o/google-oauth2/?state=eNwMFCmEplYgbUTTP9nnrQ6MduAPxzDY&code=4%2F0AcvDMrB6f3ZQuTD563Vxriu2n0VHmLEOHnDRqC6jD5BRm068jj2tyExxfZZJDFLAtcwYLg But in response I receive this (Here is my problem): { "non_field_errors": [ "Invalid state has been provided." ] } I tried to debug it, and found out that the cause lies in this module: venv/lib/python3.11/site-packages/social_core/backends/oauth.py class OAuthAuth(BaseAuth): ... # Other methods def validate_state(self): """Validate state value. Raises exception on error, returns state value if valid.""" if not self.STATE_PARAMETER and not self.REDIRECT_STATE: return None state = self.get_session_state() request_state = self.get_request_state() if not request_state: raise AuthMissingParameter(self, "state") … -
Authentification avec Django REST Framework et JWT (CustomUser)
Je travaille sur un projet Django de mise en relation des Patients et docteur.j'essaie d'implémenter l'authentification par token en utilisant Django REST Framework et djangorestframework-simplejwt. Voici mon model :from django.db import modelsfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManagerfrom django.contrib.auth.models import Group, Permission Create your models here. class CustomUserManager(BaseUserManager):def create_user(self, email, username, password=None, **extra_fields):if not email:raise ValueError('l email est oblicatoire')email = self.normalize_email(email)user = self.model(email=email, username=username, **extra_fields)user.set_password(password)user.save(using=self._db)return user def create_superuser(self, email, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, username, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin):email = models.EmailField(unique=True)username = models.CharField(max_length=50, unique=True)photo=models.ImageField(upload_to='image/')is_staff = models.BooleanField(default=False)date_joined = models.DateTimeField(auto_now_add=True) groups = models.ManyToManyField( Group, related_name='custom_user_set', # Add related_name to avoid clashes blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups', ) user_permissions = models.ManyToManyField( Permission, related_name='custom_user_set', # Add related_name to avoid clashes blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email class Patient(CustomUser): nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) telephone = models.CharField(max_length=16) genre = models.CharField(max_length=1, choices=[('H', 'Homme'), ('F', 'Femme')]) adresse = models.TextField() j ai aussi précisé le AUTH_USER_MODEL dans les settings Mon problème est que ,j aimerai permettre a travers le custom user que … -
Progressive web app support is not working in Django framework
I am new to Django framework and actually I am trying to achieve PWA (progressive web App) to make standalone and installable application. I followed the same approach shared in the official GitHub: https://github.com/silviolleite/django-pwa. Settings.py PWA_APP_NAME = 'Test website' PWA_APP_DESCRIPTION = "My app description" PWA_APP_THEME_COLOR = '#0A0302' PWA_APP_BACKGROUND_COLOR = '#ffffff' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': '/static/images/logo.jpg', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': '/static/images/logo.jpg', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': '/static/images/logo.jpg', 'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)' } ] PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' PWA_APP_SHORTCUTS = [ { 'name': 'Shortcut', 'url': '/target', 'description': 'Shortcut to a page in my application' } ] PWA_APP_SCREENSHOTS = [ { 'src': '/static/images/logo.jpg', 'sizes': '750x1334', "type": "image/png" } ] Index.html {% load static %} {% load pwa %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> {% progressive_web_app_meta %} </head> <body> <h1>Home Page</h1> <br> <a href= '/about_us'>About Us</a> <a href= '/contact_us'>Contact Us</a> </body> </html> Server Running But still I am not able to view the install button where we normally see on the browser. Any reasons or … -
django.db.utils.IntegrityError: UNIQUE constraint failed: users_user.username
I try to create a custom user model, and create a new simple user via the admin panel, but I can't do that, please check my code This is my models.py file: from django.db import models from django.contrib.auth.models import AbstractUser, PermissionsMixin from .managers import UserManager class User(AbstractUser, PermissionsMixin): # Personal information fields email = models.EmailField(unique=True) name = models.CharField(max_length=255) # Permissions and status fields is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # Important dates fields created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.name This is my managers.py file: class CustomUserManager(UserManager): def create_user(self, email, password, **extra_fields): user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Super User must be staffed")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Super User must be staffed")) return self.create_user(email, password, **extra_fields) and this is my admin.py file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User class CustomUserAdmin(UserAdmin): model = User list_display = ("email", "is_active", "is_staff", "is_superuser") list_filter = ('is_active', 'is_staff', 'is_superuser') search_fields = ('name', "email") # Editing field sets fieldsets = ( ("Personal", {"fields": ("email", "password")}), ("Permissions", … -
Running the Pycharm Debugger with a Docker/Django/Notebook setup?
I feel like I am missing some foundational truth about how Pycharm works, so I wanted to lay out how I develop and what I'm looking for. I'm running a SvelteJS project with a Django backend. I usually work in Docker containers with the following compose file: version: "3.6" services: db: image: mysql:8.3 platform: linux/amd64 environment: MYSQL_ROOT_PASSWORD: <PASSWORD> MYSQL_DATABASE: <DATABASE> ports: - "3308:3306" volumes: - dbdata:/var/lib/mysql api: build: ./api restart: always image: myproject:latest env_file: - api/.env environment: - DJANGO_SETTINGS_MODULE=myproject.settings.development ports: - "8000:8000" volumes: - ./api:/api command: bash -c "python manage.py migrate && python manage.py runserver_plus --threaded 0.0.0.0:8000" depends_on: - db links: - db:db web-svelte: build: ./svelte-frontend command: bash -c "npm install && npm run dev -- --host" ports: - "5173:5173" volumes: - ./svelte-frontend:/svelte-frontend depends_on: - "api" notebook: build: ./notebook command: python manage.py shell_plus --notebook env_file: - api/.env environment: - DJANGO_SETTINGS_MODULE=myproject.settings.development volumes: - ./notebook:/api/notebooks - ./api:/api ports: - "8990:8990" depends_on: - db - api links: - db:db volumes: dbdata: Because my project is so backend heavy, I typically work with a set of Jupyter Notebooks that have all of my objects created and I run backend code manually that way to test it. I want to be able to drop breakpoints … -
Using difference() on Django model and then creating aggregation annotation
I have a Django app that imports data from a third-party source and allows me to map it to standardized data sets using a translation table. The translation table takes two values from the source data (manufacturer and model) and returns the model ID for the matching model in the standardized data. The reason for the translation table is that the model description isn't 100% consistent in the source data, so I might need to map 2 or 3 model #s in the source data to a single model # in the standardized model table. I have an interface that provides me the models in the source data that have not been matched to a model in the standardized data. I don't currently use a foreign key field in the Django model, so what I've been doing to get the list to feed to the template is mkt = MarketData.objects.all() mapped_mdls = MktModel.objects.all().values('mfr','mdl') mdl = mkt.values('equip_mfr','equip_model').distinct() \ .annotate(mfr=F('equip_mfr'),mdl=F('equip_model')).values('mfr','mdl').difference(mapped_mdls) \ .order_by('mfr','mdl') The values...annotate...values chain is to change the field names in the source data to match the lookup table. I am trying to add the total number of units represented by the manufacturer/model combo, which is contained in a field called … -
django grpc framework server interceptor does not seem to run properly
I am using djangogrpcframework 0.2.1 and I am trying to write a interceptor to see if a key is present in the request metadata. I also log somethings to see the progress of the interceptor. from grpc import ServerInterceptor, StatusCode class CustomInterceptor(ServerInterceptor): def intercept_service(self, continuation, handler_call_details): print("start intercepting") metadata = handler_call_details.invocation_metadata if 'key' not in metadata: context = handler_call_details.invocation_metadata.context() context.abort(StatusCode.UNAVAILABLE, 'No key provided') return continuation(handler_call_details) This class is located in path/to/CustomInterceptor. I have added this interceptor to my django project settings like this: GRPC_FRAMEWORK = { 'ROOT_HANDLERS_HOOK': "project.urls.grpc_handlers', 'SERVER_INTERCEPTORS': [ "path.to.CustomInterceptor", ] } I run grpc server with the command: python manage.py rungrpcserver When trying to call any handler from a golang client to this server I do not see any log of the progress of interceptor, and I get the following error on my client rpc error: code = Unknown desc = Error in service handler! I already tried to see if the server has successfully imported the interceptor and that was not the problem. I tried setting GRPC_VERBOSITY=DEBUG to see any log of error on my server but there was no log. -
Foriegn key Fields isn't translated in django admin page with django-parler
I am using django-parler to translate models. In django admin page, When I change the language, the foriegn key isn't changing to current language, always displaying default language. enter image description here class Country(TranslatableModel): translations = TranslatedFields( title = models.CharField(max_length=255, blank=True, null=True), name = models.CharField(max_length=50) ) def __str__(self): # return self.name return self.safe_translation_getter('name', any_language=True) class Tour(TranslatableModel): translations = TranslatedFields( title=models.CharField(max_length=255, db_index=True), ) country = models.ForeignKey(Country, on_delete=models.CASCADE) I tried customizing admin form. class Tour(TranslatableModel): translations = TranslatedFields( title=models.CharField(max_length=255, db_index=True), ) country = models.ForeignKey(Country, on_delete=models.CASCADE) class TourAdminForm(TranslatableModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['country'].queryset = Country.objects.language('es') #for debug spanish lang print(self.fields['country'].queryset) # prints the translation, but doesn't display in admin page -
Chrome is ignoring my attempts to unset cookies (Django)
I'm trying to unset my cookie on an https site. The cookie was set by the server after successful login but chrome is not unsetting the cookie when logout is called even though the Set-Cookie header is present on the response headers with the correct directives. @api_view(['POST']) def login(request): data = request.data email = data.get('email') password = data.get('password') if not email or not password: return JsonResponse({'error': 'Email and password are required'}, status=400) user = authenticate_user(email, password) if user is not None: token = RefreshToken.for_user(user) # Create response object response = JsonResponse({'message': 'Login successful'}) # Set the token in a secure, HTTP-only cookie response.set_cookie( key='access_token', value=str(token.access_token), httponly=True, secure=True, # Ensure you use HTTPS samesite='Lax', path='/', domain='my-domain.com' ) return response else: # Authentication failed return JsonResponse({'error': 'Invalid credentials'}, status=401) This is my logout method: @api_view(['POST']) def logout(request): # Create response object response = JsonResponse({'message': 'Logout successful'}) response.set_cookie( 'access_token', value='', max_age=0, path='/', secure=True, httponly=True, samesite='Lax', domain='my-domain.com' ) return response Additionally I have the following in my settings.py file: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = 'Lax' SESSION_COOKIE_PATH = '/' CSRF_COOKIE_PATH = '/' SESSION_COOKIE_DOMAIN = 'my-domain.com' CSRF_COOKIE_DOMAIN = 'my-domain.com' I've tested on Firefox and also in incognito … -
How to get form file data rendered in form invalid cases in django
i have defined a form in django as : forms.py @parsleyfy class CreationForm(forms.Form): sample_name=forms.CharField(label="Agent Name",max_length=40, widget=forms.TextInput(attrs={'maxlength': '40', 'placeholder':""}),error_messages={'error-message': "Enter valid Name",'required':'Please Enter Name'}) sample_description=forms.CharField(label="agent description",max_length=100,widget=forms.Textarea(attrs={'maxlength': '40', 'placeholder':""}),error_messages={'error-message': "Enter valid Description",'required':'Please Enter Description'}) logo=forms.FileField(label="Logo",error_messages={'error-message': "Please Upload Valid File",'required':'Please Upload Logo'}) def __init__(self,request,*args, **kwargs): if request: self.request=request kwargs.setdefault('label_suffix', '') super().__init__(*args, **kwargs) I am using classbased views: Views.py: class CreationView(FormView): template_name = 'creation.html' form_class = CreationForm def dispatch(self, *args, **kwargs): try: return super(CreationView, self).dispatch(*args, **kwargs) except Exception as e: print("Exception in dispatch of CreationView form",e) def get_initial(self): init = super(CreationView, self).get_initial() init.update({'request':self.request}) return init def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def get_context_data(self,**kwargs): context = super(CreationView, self).get_context_data(**kwargs) form_class = self.get_form_class() context['form']=self.get_form(form_class) return context def post(self, request, *args, **kwargs): try: print(self.request.POST,"POST Request") print(self.request.FILES,"files in the request") form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form, **kwargs) else: print("inside form invalid") return self.form_invalid(form, **kwargs) except Exception as e: print("Exception in creationview",e) def form_valid(self, form): print("inside form valid") return render(self.request,'creation.html',{'form':form}) def form_invalid(self,form): return self.render_to_response(self.get_context_data(form=form)) creation.html: <form method="post"> {% csrf_token %} {% for field in form.visible_fields %} {{ field }} {{ field.label_tag }} {% for error in field.errors %} <div class="error"> {{ error }} </div> {% endfor %} {% endfor %} <button type="submit">Submit</button> …