Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
$ 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> … -
How to Configure a Reverse Proxy for a Django Project on GoDaddy with Apache to Hide Port 8000
I have a Django project that I've uploaded to a GoDaddy server running Apache. I’m using a domain with the .com extension, and I've started the Django development server with the command python manage.py runserver 0.0.0.0:8000. This makes the project accessible through the domain with port 8000 (e.g., www.example.com:8000). I would like to hide the port or route requests internally to port 8000 using a reverse proxy, but it’s not working. Additionally, when I try to access the site directly through the domain without specifying the port, it shows my folder structure instead of the Django application. Could you help me with configuring the reverse proxy or resolving the issue with accessing the Django project directly through the domain? I’ve attempted various commands and configuration setups in the .conf file to configure a reverse proxy and hide the port, but nothing seems to work -
Django Admin: Model visible locally but not in production
I'm encountering an issue with a Django application. I created a model and registered it in the admin. Everything works fine locally and I can see the model in the admin interface, but in production, it doesn't appear. I have verified that the migrations have been applied correctly both locally and in production. I used showmigrations and everything seems to be in order. I checked the production database via shell_plus and the model's table exists. I also created a record manually to ensure it works. My admin.py is configured correctly and looks identical in both the local and production environments. # admin.py from django.contrib import admin from myapp.models import MyModel @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('field1', 'field2', 'field3') I cleared the browser cache and tried a different browser, but nothing changed. I can't figure out why the model doesn't appear in the admin in production. Any suggestions on what I might check or do to resolve this issue? -
How can I have a different method instead of user.is_authenticated?
I have an academy website , which has 3 different kinds of users. The first one is the staff that I handle with the admin panel. The second one is parents or people who are going to get some information about the academy. The third one is students who have a different panel. My question is how can I authenticate this students ? I mean we have a method that is {% user.is_authenticated %} but it isn't ok for me because I want to check a different model named "students" and I used this method for other places. I expect a different authentication system. Because the one which I used is for regular users and I want to check that if he is a student he can have access to the special panel. Please share your ideas. -
Socket IO is rejecting requests from Nginx proxy
I have this docker application running several containers. One of these containers is a Python application that can handle both socket io requests and normal HTTP requests. Django's ASGI handles HTTP/ASGI requests while python-socketio handles socket requests. Since there are 4 other applications like this which must all be server via Nginx, I have to specify namespace URLs for both the socket io and ASGI applications for all the applications. I am using the following configuration for the application: location /app/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://app:8000/; # docker container name is "app" } location /app/socket.io/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://app:8000/socket.io/; # docker container name is "app" proxy_read_timeout 86400s; proxy_send_timeout 86400s; } asgi.py import os import socketio from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") django_application = get_asgi_application() from app.async_socketio.server import sio # noqa 402 # this allows Socket IO to handle requests by default to a # default path of /socket.io and forwards any other requests # to the Django application. application = socketio.ASGIApp(sio, django_application) # just so all my socket event handles can … -
Django reduce number of returned rows for chart
I have model with timestamp=DateTimeField() and some extra numerical data. In table I stores data from sensor collected each minutes. I have views returning chart with data from mentioned table which is parameterize by start_date and end_date. Chart works great for data from max few days period, but everything "explode" when period is longer (do many records). I don't want to reinvent the wheel. I want return only n representatives records for time period (for example with avg value). I believe that my problem is common one, but I can not google ready solution for it. -
Django DateField persistence
I have a model / Form / view for a request that works well, but when I want to update a request all the fields are loaded except the due_date field (with a date widget) witch remains empty. If I don't pay attention I validate and the due_date become None. I would like it to load the date that was saved during creation by default and then I modify it or not. Here is the code. Model class Request(models.Model): thematic = models.ForeignKey( Thematic, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Thématique", ) context = models.ForeignKey( Context, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Contexte", ) technical_element = models.CharField( max_length=255, verbose_name="Élément technique", blank=True, null=True ) due_date = models.DateField(verbose_name="Date d'échéance", blank=True, null=True) def __str__(self): return self.context class Meta: verbose_name = "Request" verbose_name_plural = "Requests" Forms class RequestForm(forms.ModelForm): new_thematic = forms.CharField( max_length=255, required=False, label="New Thematic" ) new_context = forms.CharField( max_length=255, required=False, label="New Context" ) due_date = forms.DateField( widget=forms.DateInput(attrs={"type": "date"}), required=False, ) class Meta: model = Demande fields = "__all__" widgets = { "thematic": forms.Select(attrs={"class": "form-control"}), "context": forms.Select(attrs={"class": "form-control"}), "technical_element": forms.TextInput(attrs={"class": "form-control"}), "due_date": forms.DateInput( attrs={"class": "form-control", "type": "date"} ), } def __init__(self, *args, **kwargs): super(DemandeForm, self).__init__(*args, **kwargs) if "instance" in kwargs: instance = kwargs["instance"] if instance.due_date: self.fields["due_date"].initial = instance.due_date self.fields["thematic"].queryset = Thematic.objects.all() …