Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache reverse proxy issue with otree/django
I am trying to set up apache with SSL as a reverse proxy for an oTree application. oTree is a framework for social science experiment that is build on django and also uses django channels. The reverse proxy generally works but I am having issues with websockets. My apache config is <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName myurl.net ProxyRequests Off ServerAdmin webmaster@localhost ProxyPreserveHost On ProxyPass / http://127.0.0.1:8000/ ProxyPassReverse / http://127.0.0.1:8000/ SSLEngine on SSLProxyEngine on RewriteEngine On RewriteCond %{HTTP:Connection} upgrade [NC] RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteRule /(.*) wss://127.0.0.1:8000/$1 [P,L] ServerName econ-experiments.net SSLCertificateFile /etc/letsencrypt/live/myurl.net/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/myurl.net/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> I get the following error in apache [Wed Jan 06 15:42:51.137016 2021] [proxy:error] [pid 5573:tid 140468195309312] [client myip] AH00898: Error during SSL Handshake with remote server returned by /no_op/ [Wed Jan 06 15:42:59.029500 2021] [proxy:error] [pid 5574:tid 140468096587520] (20014)Internal error (specific information not available): [client myip] AH01084: pass request body failed to 127.0.0.1:8000 (127.0.0.1) In my browser I get the following error. (index):94 WebSocket connection to 'wss://myurl.net/create_demo_session/' failed: Error during WebSocket handshake: Unexpected response code: 500 Does anyone have an idea what I am missing? -
Data filtering problem with multiple dependent users in Django
I am trying to filter data with some particular condition in Django. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.ForeignKey(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) gmail = models.EmailField(null=True, blank=False, unique=True) my views.py: @method_decorator(industry_required, name='dispatch') class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Employee_list = Employee.objects.order_by('id') context['employee_table'] = Employee_list return context Here I fetch all Employee's data in my code with Employee.objects.order_by('id').But I need to fetch only those Employee's data, which only associate with the particular Industry that I am currently visiting in the Detailsview. How can I filter those particular data only? -
Form Not Working After Converting to Bootstrap
I've got the following form that's fully working, but is just basic and ugly: {{ form.non_field_errors }} <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> When I try to convert it to a bootstrap form, like below, the Submit button does not actually submit changes. Any idea why this isn't working? When I hit Submit the values display as None, and when I go back to my selection screen the edits are not updated (they are also not updated in the backend database). Any idea what's wrong? {{ form.non_field_errors }} <form method="post">{% csrf_token %} <div class="form-group"> {{ form.stakeholder_group.errors }} <label for="{{ form.stakeholder_group.id_for_label }}">Stakeholder Group</label> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Add a Stakeholder Group" value="{{ form.stakeholder_group.value }}"> <small id="emailHelp" class="form-text text-muted">What group(s) is this invdividual associated with?</small> </div> <div class="form-group"> {{ form.employee.errors }} <label for="{{ form.employee.id_for_label }}">Employee Name</label> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Log the employee" value="{{ form.employee.value }}"> <small id="emailHelp" class="form-text text-muted">Who does this individual report to?</small> </div> <input type="submit" value="Submit"/> </form> -
Using Spotify API with Django and react
I was experimenting with the Spotify API with Django, and recently found out that you cant control the playback unless you have a premium account. Is there a way to stream the music from spotify into a component using react, the same way how discord bots can play music from spotify in a voice channel? If this doesnt work, is there any other way to achieve this same goal? -
background-tasks creating of tasks and handling completed tasks
I am using django-background-tasks to read data from an API into my database. A cronjob is starting python manage.py process_tasks every 15 minutes and works off the jobs in the queue. The task is looking like: @background(schedule = 900) def API_2_DB() .... return None Now for the first question: How do I actually create these tasks while no user is on my site? Right now I have a call to API_2_DB() somewhere in my view, but this is not called when the page is not being used, right? class DataViewSet(viewsets.ViewSet): def list(self, request): request.session["time_now"] = int(time.time()) try: if (request.session["time_now"] - request.session["time_old"]) < 900: pass else: API_2_DB() request.session["time_old"] = request.session["time_now"] except: request.session["time_old"] = request.session["time_now"] API_2_DB() So, how do I reliable create the tasks that will be worked off while the page is "not in use"? Second question: The database is stockpiling completed tasks - I know I can easily delete them with CompletedTasks.objects.all().delete() somewhere - but is there no built in automatism for this? -
Run a APScheduler task in a django_tenant backend not working
I have a Django-multi-tenant SaaS running in Django with Ubuntu 18.04. I'm using APscheduler to run schedule tasks for user online verification, in the Public Schema, everything works very well. But the schedule is not starting in the subsequent schemas. Anyone have any solution for it ? BR -
Django Multiple Choice Field Data Differs in POST Data and Form Data
I want to validate form data of Multiple Choice field but I get different results on selected data request.POST.getlist('mchoicefield') returns all the selected values but form.data['mchoicefield'] returns only one of the selected values. So I am unable to clean and validate all selection. Why is there two different results? -
Django - Gunicorn - shutdown and reboot ubuntu
I've built an application in Django. While testing I've used manage.py runserver commando. Now when I am done, I've transferred the Django application to Gunicorn. All works fine, except one thing: The web application has an option to shutdown and reboot the Ubuntu server machine (for logged in admin users). When running the application using manage.py runserver, it had permissions to do it. But now with gunicorn, it doesn't. However it's maybe not fully save, I now the risks and want to do it. Does anyone have an option to shutdown and reboot the Ubuntu machine using the Django application? With manage.py runserver I've used: cmd = "sleep 5 && reboot" result = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True) Thanks for the replies. -
Django how to compare correctly against django.utils.timezone.localtime and PostgreSQL time with time zone?
I have a legacy PostgreSQL table with time with time zone column. in models.py I have the filed set to models.TimeField I want to compare accessed Django.utils.timezone.localtime() with db_field_time_with_time_zone I have tried below: # let's say now=20:00 and db_field_time_with_time_zone=16:00 now = timezone.localtime() data = timezone.datetime.combine(timezone.localdate(), db_field_time_with_time_zone) self.assertTrue(now > data) # I get False... In the raw PostgreSQL column it's stored as 16:00:00+09:00 but when I retrieve data using python manage.py shell it returns 16:00:00+00:00 and I also think this is the cause of this problem. In my settings.py TIME_ZONE = 'Asia/Tokyo' USE_TZ = True -
Use Django Subquery as FROM table or CTE in order to have a Window over an aggregate?
I am trying to sum costs within groups, and then have add a cumulative cost over multiple groups. Simplified: class Cost(Model): year = IntegerField() month = IntegerField() cost = DecimalField() select "year", "month", month_cost, sum(month_cost) over (partition by 1 order by "year", "month" rows between unbounded preceding and current row) as cum_cost from ( select "year", "month", sum("cost") as month_cost from app_cost group by "year", "month" ) as innerq order by "year", "month" But I can't work out how to write it with Django's ORM: innerq = Cost.objects.values("year", "month").annotate(month_cost=Sum("cost") is all very well, but then if I do: outerq = innerq.annotate( cum_cost=Window( expression=Sum("cost"), partition_by=[Value(1)], order_by=[F("year"), F("month")], frame=RowRange(None, 0), # UNBOUNDED PRECEDING -> CURRENT ROW ), ) I get a: FieldError: Cannot compute Sum('cost'): 'cost' is an aggregate How can I force the queryset innerq into a subquery, as in my SQL above? (I am aware of Subquery, I just haven't found a way to apply it here.) -
How to update a django formset?
I am new to Django and web development. I am using a formset to save the data into the database. The creation part works fine, but I am facing issues when I try to update the existing data in the database using formsets. Here are the relevant code snippets: models: from django.db import models class GradingSchemeName(models.Model): name = models.CharField(max_length=250, null=False, blank=False, unique=True) class GradingScheme(models.Model): scheme_name = models.ForeignKey(to=GradingSchemeName, on_delete=models.CASCADE) grade = models.CharField(max_length=250, null=False, blank=False) score_range_begin = models.SmallIntegerField() score_range_end = models.SmallIntegerField() class Meta: unique_together = ('scheme_name', 'grade',) forms: from django.forms import ModelForm, inlineformset_factory GradeFormSet = inlineformset_factory( parent_model=GradingSchemeName, model=GradingScheme, fields=['scheme_name', 'grade', 'score_range_begin', 'score_range_end'], extra=10, max_num=100, can_delete=False ) views: # Passing the pre-filled form for rendering. For the sake of illustration, I have hardcoded the `id=1`: instance = GradingSchemeName.objects.get(id='1') context['grade_formset'] = GradeFormSet(instance=instance) # checking the request data from the post(request) on form submission: grades_formset = GradeFormSet(request.POST, instance=instance) Note that 3 records were saved in the GradingScheme Model during formset creation. When I try to update using the above approach, I see the grades_formset has 13 records (3 from the instance attribute and 10 from the extra forms). The issue is caused when the is_valid() method is executed: if not grades_formset.is_valid(): messages.error(request, 'Form data is … -
Display admin TabularInline in list_display
I have two models, which are linked reverse by foreign key from my admin point of view: class Product(models.Model): name = models.CharField("name", max_length = 128) class Store(models.Model): store_id = models.PositiveIntegerField(unique = True) product = models.ForeignKey(Product, on_delete = models.CASCADE, null = True, blank = True) And I have an admin view where I want to display the store_id of each product it is available in list_display. I ask because I found TabularInline - my apporach: class StoreInline(admin.TabularInline): model = Store readonly_fields = ['store_id', "product"] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["name",] inlines = [StoreInline,] But how would i be able to display the store_id value in list_displays using the Inlines method? I worked around by creating a custom method but, I feel like from reading (1, 2, 3) that I have solved it "by hand" and not using a path Django already has. This works: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ["name", "get_stores"] def get_stores(self, obj): return [s.store_id for s in Store.objects.filter(product = obj)] -
i am tring to write a customr permissions class to add permissions for the user to rate the movie once per user
here i am trying to add custom permissions 1.user can rate the movie once 2.Users can add a movie and other people, except the creator, can rate it. i have written the custom permission class in the permission.py but still it not doing what i want but it is going wrong .can please some help one models.py from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Movie(models.Model): title = models.CharField(max_length=128) director = models.CharField(max_length=128) added_by = models.ForeignKey(User, related_name="movie", on_delete=models.CASCADE, null=True) added_at = models.DateTimeField(auto_now_add=True) # rating=models.IntegerField() class Meta: db_table = "Movie" class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_rating') class Meta: db_table = "Rating" views.py from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAuthenticated from knox.models import AuthToken from TestApp.models import Movie, Rating from TestApp.serializer import UserSerializer, RegisterSerializer, LoginSerializer, MovieSerializer, RatingSerializer from TestApp.permissions import * class UserAPIView(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user class RegisterAPIView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return … -
Best way to save Raw SQL queries in Django
What is the best way to make raw SQL queries in django? I have to search a table for the mode of another table. I could not find a way to solve this in django's ORM so I turned to raw SQL queries. Yet creating all these very long queries in python is very unreadable and does not feel like a proper way to do this. Is there a way to save these queries in a neat format perhaps in the database. -
django ckeditor won't show the errors
I am using django-ckeditor package in my django project. These are my problems: when my text has tabs and spaces, no object is created and it does not give any error! Here is my codes: Also Ckeditor does not show any error when I leave the about_me field blank! But it does not create a new object. view, template, model and form -
How to redirect a user to submited confrim page if he has submited a kyc from?
Well here I just want to redirect a user to submitted confirm page. There is one option in sidebar for kyc form , If he ones submitted the kyc forms then whenever he clicks on kyc form he should redirect to the submitted confrim page instead of kyc create form. How it can be done ? class KycFormCreateView(CreateView): model = KycModel template_name = "accounts/kyc/new_kyc.html" def get(self): userkyc = KycModel.objects.filter(owner=self.request.model) print('user kyc form count ',userkyc.count()) userkyc = KycModel.objects.filter(owner=self.request.model) print('user kyc form count ',userkyc.count()) if userkyc.count() >=1: return('accounts:submitted') else: form_class = KycModelForm return form_class I'm trying this way and this is not making sense at all.... and getting an error: TypeError at /accounts/kyc get() takes 1 positional argument but 2 were given -
Django UpdateView get name error: pk is not defined
I get a name error: pk is not defined although I can see that the pk is passed to the view from the url. urls.py: from django.conf.urls import url from cashflow.views import cashflowView, SelectAccountView, CashflowEditView from django.urls import path app_name = 'cashflow' urlpatterns = [ url(r'^select_account', SelectAccountView.as_view(), name="select_account"), url(r'^$', cashflowView.as_view(), name="cashflow_processing"), path('edit/<pk>/', CashflowEditView.as_view(), name="cashflow_editing"), ] views.py: class CashflowEditView(UpdateView): model = ttransactions template_name = 'cashflow/cashflow_processing.html' form_class = CashflowForm success_url = 'cashflow' def get_form_kwargs(self): kwargs = super(CashflowEditView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def get_queryset(self, **kwargs): transaction = ttransactions.objects.filter(pk=pk) transaction_lines = transaction_lines.objects.filter(transaction=transaction.id) return transaction, transaction_lines I get the error on the line transaction = ttransactions.objects.filter(pk=pk) When I run in debug I can see that pk is send to the view but when I use it on the object I get the error. I will appreciate help to resolve the problem for me. -
How to get the ssl certificate from request object in Django?
I have an API developed using Django Rest Framework. When a request is sent to the API, the client certificate is bound to the request object. But from the server-side, I need to access the client's SSL certificate from the request object. But it is not working. Please give me some suggestion to get the certificate: Server-Side API: class GetBalance(APIView): def get(self, request, format=None): print(request.session.cert) // Raising Exception Here Client-Side Request resp = requests.get('API ENDPOINT', verify=True, cert=['/path/to/my/ca.crt']) But Getting key error when I am printing in get method/ -
Django admin didn't allow me to create a group for one app
I am trying to create a group for a specific app like blog, so that group users can only create and edit blog posts. I also assign staff status to the users of that group. The group is created but it didn't allow me to login in it. After some research, I came to know that if I give access to all of the installed apps it allows me to log in. any suggestion on how to give permission for any specific app. -
How do I fill an empty div with js?
The aim is to access a particular endpoint after performing a search only when I hit a button but I am finding it difficult to do that with JS. I have an HTML which is rendered in an html endpoint, and I want that html file to fill an empty div I created in another HTML file. I am trying to achieve this with vanilla JS but all answers I see are in JQuery and I do not really know JS Implement search for friends. def results(request): if request.method == "GET": search_query = request.GET.get("username") searched_user = UserProfile.objects.filter( user__username__contains=search_query ) return render( request, "toggle.html", { "searched_user":searched_user }) else: return HttpResponse("Search returned nothing") rendering html to fill empty div def html(request): return render(request, template_name= "search_results.html" ) index.html <p>Welcome</p> <form id="search" method="GET" action="{% url 'results' %}" placeholder= "Search for user" autocomplete="off"> {{form}} <input type="submit" value="search" name="search"> </form> search_results.html {% extends "base.html" %} {% block spotify %} {%if searched_user %} {% for each_searched_user in searched_user %} <br/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}}<br/> {% endfor %} {% endfor %} {% endif %} {% endblock %} toggle.html {% extends "base.html" %} {% block spotify %} <div id="div"> </div> <button id=likedsongsbutton>View liked songs</button> <script> var request = … -
Django jsonresponse for making chart
I want to display a chart using chart js with data from django back end. Currently it works if data is there, if data is not there in a particaular day it is not showing proper data, this is my view def member_week_graph(request): labels = [] data = [] date = datetime.date.today() current_week = date.today().isocalendar()[1] member_in_week = User.objects.filter(date_joined__week=current_week).exclude(is_staff=True).values( day=TruncDay('date_joined') ).annotate( total_members=Count('date_joined') ).order_by('day') for entry in member_in_week: labels.append(entry['day']) data.append(entry['total_members']) return JsonResponse(data={ 'labels': labels, 'data': data, }) the output is {"labels": ["2021-01-05T00:00:00Z", "2021-01-06T00:00:00Z"], "data": [1, 5]} this is correct data, if data is not there for a day I want to display the date and an empty string, hope someone can help, thank you. -
Complex custom React component in Django Template
I've made a custom react component based on the react-chatbot-kit and it works fine with React. However, I now want to use the same component inside a Django template. Have tried looking at browserify, webpack but it is not helping since the web tutorials use very simple components like Hello World or the likes to show how to do it. In fact some of the tutorials are not even working the way they should even after following each and every instruction. I need help to use/display my custom React component in a Django template or rather any HTML for that matter. Thanks in advance. Following is the code in App.js to display the Chatbot component. import React from "react"; import './App.css'; import Chatbot from 'react-chatbot-kit'; import ActionProvider from './components/react-chatbot-kit/ActionProvider'; import MessageParser from './components/react-chatbot-kit/MessageParser'; import config from './components/react-chatbot-kit/config'; function App() { return ( <div className="App"> <header className="App-header"> <Chatbot config={config} actionProvider={ActionProvider} messageParser={MessageParser} /> </header> </div> ); } export default App; -
What's the benefit of using Django ManyToManyField instead of just get by related_name?
I was just wondering "Why" use Django ManyToManyField. I can still retrieve data form related_name. -
Django Rest Framework DjangoModelPermissions now working properly
Why the DRF permission class DjangoModelPermissions allow every users to perform all requests like POST, PUT, DELETE even those user i didn't manually assign them the add, change, delete permissions from my django admin. they are allowed to be only view the objects but why the are getting all unsafe request POST, DELETE... ? Views.py class HotelViewSet(viewsets.ModelViewSet): queryset = Hotel.objects.all() serializer_class = HotelSerializer authentication_classes = [SessionAuthentication] permission_classes = [DjangoModelPermissions] settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissions', ] } -
Count error with annotate() & values() while filtering categories, repetition
Django : Count error with annotate() & values() while filtering categories, duplication error as I'm using below count function to filter categories but its displaying accountant separately twice. queryset = Blogpost \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset > My function in template {% for cat in category_count %} <div class="item d-flex justify-content-between"> <a href="#">{{ cat.categories__title }}</a><span>{{ cat.categories__title__count }}</span> </div> {% endfor %}