Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django behind NGINX reverse proxy and AWS Application Load Balancer doesn't get HTTPS forwarded from client in HTTP_X_FORWARDED_PROTO
I'm running Django on Gunicorn behind a NGINX reverse proxy, and an AWS Application Load Balancer. The ALB has 2 listeners. The HTTPS listener forwards to a Target Group in port 80, and the HTTP listener redirects to HTTPS. The ALB thus connects with an AWS ECS Cluster, which runs a task with 2 containers: one for the Django app, and another for the NGINX that acts as a reverse proxy for the Django app. Here's the configuration for the NGINX reverse proxy: upstream django { server web:8000; } server { listen 80; listen [::]:80; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_ssl_server_name on; proxy_redirect off; } } This configuration ensures that whenever the client tries to hit the website app using an HTTP request, he gets redirected to HTTPS. And everything works fine with one exception. In Django, when I run request.is_secure() I'm getting False instead of True as expected. If I run request.build_absolute_uri(), I get http://mywebsite.com and not https://mywebsite.com as expected. I already tried adding the following lines to settings.py: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') as explained in the documentation, but it doesn't … -
How to get additional context without repeating database queries?
I want to provide extra context in my serializer in get_serializer_context. Currently I'm having to repeat the database queries that the serializer is performing by itself anyway in order to do so. Is there a way around this, to access the data that's already been queried? class MyView(generics.ListCreateAPIView): def get_serializer_context(self): context = super().get_serializer_context() # Is this somewhere I can get to it? data = self.paginate_queryset(self.filter_queryset(self.queryset)) context["extra_stuff"] = get_extra_stuff_for(data) return context -
How to fix Heroku Openai Django Deployment Error?
When deploying a new Heroku App Using a Django Docker Enviorment Inside my requirments.txt I have openai==0.11.0 When doing git push heroku master During Build I get this Error Building wheel for pandas (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for pandas (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [1803 lines of output] gcc: fatal error: cannot execute 'cc1plus': execvp: No such file or directory compilation terminated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] Building wheel for numpy (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for numpy (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [251 lines of output] RuntimeError: Broken toolchain: cannot link a simple C++ program. note: A compiler with support for C++11 language features is required. [end of output] Any help really appreciated. Thank You -
Django admin.TabularInline import csv function
The following code is an inline class, how to make it support the import and export functions of django-import-export。 class DataSourceTableFieldline(admin.TabularInline): # resource_class = DataSourceTableFieldForm model = DataSourceTableField list_display = ( 'column_name_cn', 'column_name_en', 'column_type', 'column_length', 'ordinal_position', 'column_is_pk') extra = 0 class DataSourceTableAdmin(admin.ModelAdmin): inlines = [DataSourceTableFieldline] list_display = ['table_name_zh', 'table_name_en', 'table_logical_name', 'table_code', 'table_sort_id'] search_fields = ['table_name_zh', 'table_name_en'] list_display_links = ['table_name_en'] -
"detail": "JSON parse error - Extra data: line 1 column 9 (char 8)" in django rest framework post request
Here is my view @api_view(["POST"]) def afficher_donnees_instantanees(request): if request.method == "POST": print(request.data) deveui = request.data["deveui"] donnees = Historique.objects.filter(infos_signal__machine=deveui, infos_signal__jour=datetime.today()).order_by("-id").first() serializer = HistoriqueSerializer(donnees) return Response(serializer.data) else: return Response({"echec": "echec"}) serializer.py class HistoriqueSerializer(serializers.ModelSerializer): class Meta: model = Historique fields = '__all__' I want to display data from my Historique model in response to a POST request, but I get the message "JSON parse error - Extra data: line 1 column 9 (char 8)". Knowing that the response code is 400. Where can this error come from please? -
Django can't get the correct url path to media file
I have a problem when I try to show the media files pictures from my database Django keeps renaming '/media/' to '/dashboard/' in the requests to my media files here is the model:` class PetPhoto(models.Model): photo = models.ImageField( upload_to='photos/', blank=True ) tagged_pets = models.ManyToManyField( Pet, ) description = models.TextField( null=True, blank=True, ) publish_date = models.DateTimeField( auto_now_add=True, ) likes = models.IntegerField( default=0, ) Here is the view class CreatePetPhotoView(auth_mixin.LoginRequiredMixin, views.CreateView): model = PetPhoto template_name = 'web/photo_create.html' fields = ('photo', 'description', 'tagged_pets') success_url = reverse_lazy('dashboard') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) ` Here is settings.py MEDIA_ROOT = BASE_DIR / 'mediafiles' MEDIA_URL = '/media/' Here is the urls.py file from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('petstagram.web.urls')), path('accounts/', include('petstagram.accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django admin form multi validation
admin.py class UserControlAdmin(ExportActionMixin, admin.ModelAdmin): form = UserControlModelForm fields = ('user', 'team', 'position') forms.py class UserControlModelForm(forms.ModelForm): def clean_position(self): position = self.cleaned_data['position'].id if not isinstance(self.cleaned_data['team'], type(None)): team = self.cleaned_data['team'].id ... if p['company_group'] != t['company_group']: raise ValidationError('...') return self.cleaned_data['position'] def clean_team(self): if isinstance(self.cleaned_data['team'], type(None)): position = self.cleaned_data['position'].id if position < 4: ... raise ValidationError('...') return self.cleaned_data['team'] I get error KeyError at /admin/information/user/add/ 'position'. I found a problem that, inside clean_team doesn't have position value because position stands behind team in admin fields. How can I fix that? Is it possible to check after getting all parameters? In post request still have position parametr. -
Django multi project user management
I want to learn is there a way to keep django multi project and authenticate/authorize them with one project? For example: I have Project-B and Project-C with different operation fields like hotel automation and gas station. Both of them are my products and I want to manage them by keep licences and users in one place, in other words different project, Project-A. In Project-B and Project-C has it's own apps and apps' models so I don't want to merge them in one project, I want to keep them separate. But I want authorize/authenticate users from one place Project-A. So Project-A will be used only for management. I am planning to use OAuth toolkit for it, but in the first place I have another problem. Project-B and Project-C's apps' models have foreign key fields and many to many fields that defined in Project-A like customer itself. Authentication can be solved Rest Framework and OAuth2 I think but I don't have a solution for this problem. Can you help me out? Thanks in advance. -
Django access related items in template
Please help me I’m stuck in understanding how Django ORM works. Here is my very simple models: class Department(models.Model): title = models.CharField(max_length=50) class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.PROTECT) I want a template that looks like: Department 1 Employee 1 Employee 2 Department 2 Employee 3 Employee 4 But I can’t figure out what I should do in my view and(or) template -
how to display images in templates while using django wagtail
I have the codes below: models.py class BlogImagePage(Page): feature_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True) body = RichTextField(blank=True) excerpt = models.TextField(blank=True) thumbnail_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, related_name='+', null=True) content_panels = [ FieldPanel('title'), FieldPanel('body', classname='full'), FieldPanel('excerpt'), ImageChooserPanel('feature_image'), ImageChooserPanel('thumbnail_image'), ] class BlogPageIndex(Page): content_panels = [ FieldPanel("title"), ] class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] using wagtail admin I am able to create an instance of the table BlogImagePage. Now i am trying to display the image field in the BlogPageIndex page: blog_page_index.html {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-blogindexpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <div class="intro">{{ page.intro|richtext }}</div> {% for post in page.get_children %} <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2> {{ post.specific.body|richtext }} {% endfor %} {% endblock %} It does show/render the instance with the title but unfortunately i am not able to render/display the image saved either on the page above or the detail page of BlogImagePage instance that has the code below blog_image_page.html {% extends "base.html" %} {% load wagtailcore_tags %} {% block body_class %}template-blogindexpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <div class="intro">{{ page.intro|richtext }}</div> {% for post in page.get_children %} <h2><a … -
How to deploy a Django backend and Flutter frontend web app
I've been working on a web application that uses Django REST Framework and Django channels in the backend and has a Flutter frontend. It works successfully when tested locally, but my question was how would I deploy this: What server is most appropriate for this application? (it should be free as this is just a personal project I've been testing) Do I need to deploy the frontend and backend separately? Are there any online resources I can refer to, to help me in this process? Any help is appreciated :) -
Django get user data in main template
I'm trying to check if user logged in in the main template using this: {%if request.user%} ... {%endif%} but it's not working maybe because main template doesn't have a view could any one help i don't know if the question duplicated,but i didn't find my answer. -
How can we specify organization level permissions using Django Rest Framework
I am new to Django authentication and Authorisation , we have a login and signup implemented with ReactJS on the client side and the Django JWT authentication on the server side. Now, I want to take this to next level by adding authorisation aswell by making users from same organizations only must be able to view/read/write the data existing in the application. Every user will be identified using a specific domain name ex: @gmail.com,@xyz.com. Users from one domain must not have any access to the database of the other organizations. I think we can achieve this with Permissions concept in Django but dont know how we can do it technically. Any ideas are well appreciated. Thanks -
django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails
from django.db import models from django.contrib.auth.models import User Previously my models was like this . class Login(models.Model): pid = models.AutoField(primary_key=True) custom_username = models.BooleanField(default=False) tnx_hash = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.username Then i changed to like this to inherit from base admin user model. class Login(User): pid = models.AutoField(primary_key=True) custom_username = models.BooleanField(default=False) tnx_hash = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.username Now when i am running makemigrations and migrate getting below error . File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`baby`.`#sql-16a7_6a`, CONSTRAINT `api_login_user_ptr_id_7f748092_fk_auth_user_id` FOREIGN KEY (`user_ptr_id`) REFERENCES `auth_user` (`id`))') Please take a look. How can i solve this problem safely. Because i have data in my database and login table is foreign key for many tables. -
Move Authentication error in django crispy form
I created a login page using django authentication system. The validation errors are showing good, but I don´t know how to manipulate location for my error messages within my LoginForm layout. I attached where I need to displace my message message displacement forms.py class LoginForm(AuthenticationForm): remember_me = forms.BooleanField(required=None) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = "id-authenticationForm" self.helper.form_class = "form-signin" self.helper.form_method = "post" self.helper.form_action = "login" self.helper.layout = Layout( HTML("""{% load static %}<img class="mb-4" src="{% static 'images/logo.jpg' %}" > <h1 class="h3 mb-3 fw-normal">Please sign in</h1>"""), FloatingField("username", "password"), Div( Div( Div("remember_me", css_class="checkbox mb-3"),css_class="col"), Div(HTML("<p><a href='{% url 'password_reset' %}'>Lost password?</a></p>"),css_class="col"), css_class="row" ), Submit('submit', 'Sign in', css_class="w-100 btn btn-lg btn-primary"), HTML("""<p class="mt-5 mb-3 text-muted">&copy; 2022 all rights deserved</p>""") ) login.html.py {% extends "blog/base.html" %}{% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} views.py def custom_login(request, user, backend=None): """ modificated generic.auth login. Send signal with extra parameter: previous [session_key] """ # get previous seesion_key for signal prev_session_key = request.session.session_key #send extra argument prev_session_key user_logged_in.send(sender=user.__class__, request=request, user=user, prev_session_key=prev_session_key) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): super().form_valid(form) """Security check complete. Log the user in.""" #changed default login custom_login(self.request, form.get_user()) #get remember me data from cleaned_data of … -
Unable to call django view using ajax
I want to call the django view from client side that will display all the messages from the models on the html page AJAX function <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/load_with_room_name/{{room_name}}/", success: function(response){ console.log(response); $("#display").empty(); }, error: function(response){ alert('An error occured') } }); },1000); }) </script> django view function def load_with_room_name(request,room_name): try: current_user = Account.objects.get(email=str(request.user)) chat_room = ChatRoom.objects.get(room_name=room_name) if chat_room.room_user_1 == current_user or chat_room.room_user_2 == current_user: print(current_user) return redirect('room',room_name,current_user.username) else: return redirect('chat') except Exception as e: log_exception(request,e,view_name="load_with_room_name") return render(request,"error.html") django urlpattern for the above view urlpatterns = [ path('load_with_room_name/<str:room_name>',views.load_with_room_name,name='load_with_room_name'), ] -
Angular 12 - I get data from backend to component but it doesn't show on my HTML View
Since yesterday I am trying to understand what I did wrong. I want to pass data from my django backend to my frontend angular. Supposedly, backend is sending data. I can see it by this command: [18/Mar/2022 11:41:46] "GET /list-users/ HTTP/1.1" 200 82 My front end is making the request, and my backend is responding aswell. Also, I can see the results by a console.log here: Array(5) [ "admin@lab.com", "lab@lab.com", "lab2@lab.com", "lab3@lab.com", "lab4@lab.com" ] 0: "admin@lab.com" 1: "lab@lab.com" 2: "lab2@lab.com" 3: "lab3@lab.com" 4: "lab4@lab.com" length: 5 <prototype>: Array [] main.js:164:80 I guess, everything is right until now. This is my component code, and my html component code. import {Component, OnInit} from '@angular/core'; import { SharedService } from 'app/shared.service'; @Component({ selector: 'app-regular', templateUrl: './regular.component.html', styles: [] }) export class RegularComponent implements OnInit { userlists: any; constructor(private service: SharedService) { } ngOnInit() { this.getUserlist(); } getUserlist() { let observable = this.service.getUsersList(); observable.subscribe((data) => { this.userlists = data; console.log(data); return data; }); } } html component <div class="card main-card mb-3"> <div class="card-header"> </div> <table class="table table-striped"> <thead> <tr> <th scope="col">No.</th> <th scope="col">Date</th> <th scope="col">Patient Code</th> <th scope="col">Status</th> </tr> </thead> <tbody> <tr *ngFor="let user of userlists"> <td>{{user.email}}</td> … -
How to get table data based on id which obtains from another table data? Django
Views company = Company.objects.get(id = company_id) # getting input from django urls (<int:company_id>) vehicles = CompanyContainVehicles.objects.filter(company_id=company.id) # Give all rows having same id (company.id) all_vehicles = Vehicles.objects.filter(id=vehicles.vehicle_id) # Not Working How do I get data from tables whose multiple id's obtained by another table? Models class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) description = models.TextField() class Vehicles(models.Model): id = models.AutoField(primary_key=True) vehicle_number = models.IntegerField() name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True, unique=True) class CompanyContainVehicles(models.Model): id = models.AutoField(primary_key=True) company_id = models.ForeignKey(Company, on_delete=models.CASCADE) vehicle_id = models.ForeignKey(Vehicles, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True) Above are my table details and I need to get all vehicles from table Vehicles which is obtained from CompanyContainVehicle table (that define which company seel out which vehicle) based on company_id that obtain from table Company which contains details of companies. -
allauth tests return errors
For changing things like translations in forms i included allauth app directly in my project but now when i want to run tests it returns lots of errors i think it runs every test while i am not using social logins it tests it and fails my project on Github : github.com/MrHamedi/VSC/tree/dev Shall i delete allauth test to resolve this problem ? or what should i do so allauth tests only test allauth.account tests -
superuser authenticate in class based view
I am working on blog project in which I added an add post which add post now I want only the superuser can add post and that page is visible only to superuser. 1st Method Views.py class AddPostView(CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' this is my current view I am able to achieve authenticate for superuser using 2nd method 2nd Method class AddPostView(View): def get(self,request): if request.user.is_superuser == True: return render(...) else: pass How can I achieve the same result using 1st method.I tried using LoginRequiredMixin but nothing is happening . I just import LoginRequiredMixin and use it like this . class Addpost(CreateView,LoginRequiredMixin): ... Thanks in advance and advice will be helpful. -
Django, DRF: two similar models views, separate endpoints or not
There are two similar models as shown below. class ProductVideo(models.Model): ... class UserVideo(models.Model): ... Should it be handled dynamically with query_params in one View? # /videos/:id/comment?product=1 class CommentView(generics.CreateAPIView): def get_serializer_class(self): s = self.request.query_params.get("product") if s: return ProductVideoSerializer else: return UserVideoSerializer Or should I create one View at a time? # /videos/product/:id/comment class ProductVideoCommentView(generics.CreateAPIView): ... # /videos/user/:id/comment class UserVideoCommentView(generics.CreateAPIView): ... -
Celerybeat Multiple schedules of the same task
I got following Celery beat task which cleans 1000 items daily at 1 AM: from celery.schedules import crontab from .celery import app as celery_app celery_app.conf.beat_schedule['maintenance'] = { 'task': 'my_app.tasks.maintenance', 'schedule': crontab(hour=1, minute=0), 'args': (1000,) } I want to clean additional 5000 items every Sunday at 5PM. Is there a way to add second schedule? 'schedule': crontab(hour=17, minute=0, day_of_week='sunday'), 'args': (5000,) And how to ensure they won't overlap? -
Local chat on machine used for Outline VPN
I have a remote Ubuntu server on Linode. I use it to provide Outline VPN for me and my friends. Can I somehow create a web chat on this machine so that only users connected by Outline can use it? I tried to run django local server on it, but I couldn't connect. -
Inconsistance between `request.user` and `request.session` in Django
I do understand that login() will attach User to request.session and request.user after authenticate() successfully validate credentials. I am wondering will there be any occasions where request.user becomes anonymous user and request.session still has User attached ? I encountered this myself. If answer to above is yes, then when request.user.is_authenticated == False, should we flush the existing session, and prompt for login again to avoid someone use previously stored session. or we can directly attach user in request.session to request.user to make it logged_in user. thanks for your insights. -
AttributeError: 'JSONParser' object has no attribute 'parser'
when i post data from postman application then this error is accour code elif request.method == 'POST': data = JSONParser().parser(request) serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) **error ** data = JSONParser().parser(request) AttributeError: 'JSONParser' object has no attribute 'parser'