Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Certain Celery Tasks starts but hangs and never executes
I have an issue with Django and Celery where some registered tasks never get executed. I have three tasks in my tasks.py file, two of them; schedule_notification() and schedule_archive() work without issue. They are executed without issue at the predefined ETA. With the schedule_monitoring() function, I can see the job is started in Celery Flower but it never actually executes. It just sits there. I have confirmed I can run the command locally from the worker so I'm not sure where the issue could be. tasks.py (failing function) @task def schedule_monitoring(job_id: str, action: str) -> str: salt = OSApi() # This is a wrapper around a REST API. job = Job.objects.get(pk=job_id) target = ('compound', f"G@hostname:{ job.network.gateway.host_name } and G@serial:{ job.network.gateway.serial_number }") policies = [ 'foo', 'bar', 'foobar', 'barfoo' ] if action == 'start': salt.run(target, 'spectrum.add_to_collection', fun_args=['foo']) for policy in policies: salt.run(target, 'spectrum.refresh_policy', fun_args=[policy]) create_activity("Informational", "MONITORING", "Started proactive monitoring for job.", job) elif action == 'stop': salt.run(target, 'spectrum.remove_from_collection', fun_args=['bar']) for policy in policies: salt.run(target, 'spectrum.refresh_policy', fun_args=[policy]) create_activity("Informational", "MONITORING", "Stopped proactive monitoring for job.", job) else: raise NotImplementedError return f"Applying monitoring action: {action.upper()} to Job: {job.job_code}" Celery Configuration # Async CELERY_BROKER_URL = os.environ.get('BROKER_URL', 'redis://localhost:6379') CELERY_RESULT_BACKEND = os.environ.get('RESULT_BACKEND', 'redis://localhost:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER … -
Deploy Django App to Render as a static site
Anyone kind enough to tell me what should the build command be? Also what should there be in the publish directory (I named it dist and it has an empty index.html). My build script right now is: #!/usr/bin/env bash # exit on error set -o errexit python manage.py collectstatic --no-input python manage.py migrate -
How get another field than GROUP BY using MIN django ORM?
FIRST: This question is NOT THE SAME as this one: How to query as GROUP BY in django? please read carefully, I am asking to get the different field than the one group by. That questions for the same field. This is NOT THE SAME question. If we have table with columns: warehouse; product; price; How can we do this SQL query SELECT product, min(price) FROM table GROUP BY warehouse How to do that with django orm besides raw query? Can we do it with extra()? -
How to walletconnet with QR code in django?
Well I just wanted to ask that is there any package for django python to connect wallet by scanning QR code in django. I am using web3.py but i didn't see any package for wallet connect. If there is such package then please share with me and tell me how is possible. -
Name error when trying to filter date field from base table in django
I have two models class Rule(models.Model): pmdruleid = models.BigIntegerField(primary_key=True) effectivedate = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'rule' class Ruledefinitions(models.Model): ruleactivestatus = models.CharField(max_length=14) pmdclinicalruleid = models.OneToOneField(Rule, models.DO_NOTHING, db_column='pmdclinicalruleid', primary_key=True) class Meta: managed = False db_table = 'ruledefinitions' unique_together = (('pmdclinicalruleid', 'pmdclinicalvariableid'),) I am trying to filter records based on effectivedate field in viewset like below class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid').filter(pmdclinicalruleid__effectivedate < datetime.now()) I am getting NameError: name 'pmdclinicalruleid__effectivedate' is not defined. -
create() populates manytomany with every row in the related table, rather than leave it blank
Currently, I have three models in models.py: class User(AbstractUser): pass class Watchlist(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) listings = models.ManyToManyField('Listing', related_name = "watchlists", blank = True) class Listing(models.Model): title = models.CharField(max_length = 150) description = models.TextField() The problem occurs when a user creates their watchlist, which is handled by this piece of code in views.py: # Each listing has it's own page, # with a URL of the form /listing/<int:pk> def listing(request, pk): listing_instance = Listing.objects.get(pk = pk) if request.method == "GET": # return the page for the listing with primary key pk elif request.user.is_authenticated: watchlist_instance = Watchlist.objects.get_or_create(user = request.user)[0] watchlist_instance.listings.add(listing_instance) I would expect the row created by Watchlist.objects.get_or_create(user = request.user) to have no relations in its listings, but instead it has relations to every row in the Listing table (meaning the last line does nothing). For example, if the Listing table contained three rows: listing1 listing2 listing3 and a new user viewed the page for listing2 and tried to add it to their watchlist, their watchlist would include all three listings. To confirm it was create() that was causing the problem, I tried this: elif request.user.is_authenticated: watchlist_instance = listing_instance.watchlists.create(user = request.user) which looks (to me) to be basically … -
How to do `SELECT product, min(price) FROM table GROUP BY warehouse` in django ORM
If we have table with columns: warehouse; product; price; How can we do this SQL query SELECT product, min(price) FROM table GROUP BY warehouse How to do that with django orm besides raw query? Can we do it with extra()? -
how can i deliver two values to the django backend in jquery slider?
jquery <script> $(function () { $("#slider-range").slider({ range: true, min: 1910, max: 2019, values: [1950, 2010], slide: function (event, ui) { $("#amount").val(ui.values[0] + "won - " + ui.values[1] + "won"); } }); $("#amount").val($("#slider-range").slider("values", 0) + "won - " + $("#slider-range").slider("values", 1) + "won"); }); </script> html <FORM NAME="myForm" method="GET" action="{%url 'search_result'%}"> <p> <label for="amount">won:</label> <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;" aria-valuemin=""> </p> <input type="submit" value="search" id="search_button"> </FORM> I want to deliver two values to the django backend in GET form. two values are values[0] and values[1]. How to modify the input tag inhtml? -
Django NameError: name 'TypeError' is not defined
I recently started working for a company using and making changes to an existing Django platform. Right now im trying to cache static assets as well as ldap session since there is a bottleneck somewhere that is making my webpage load to slow. When trying to use memcached to cache ldap session I changed my django settings, after reloading the webpage it wouldn't load so I reverted the changes and reloaded apache again but now It's throwing the next exception: [Wed Jan 06 15:15:50.852034 2021] [mpm_event:notice] [pid 533599:tid 140576061348928] AH00493: SIGUSR1 received. Doing graceful restart Exception ignored in: <function Local.__del__ at 0x7fda60831790> Traceback (most recent call last): File "/var/www/deploys/dataforge/staging/current/venv/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fda60831790> Traceback (most recent call last): File "/var/www/deploys/dataforge/staging/current/venv/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message [Wed Jan 06 15:15:51.068359 2021] [mpm_event:notice] [pid 533599:tid 140576061348928] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Wed Jan 06 15:15:51.068387 2021] [core:notice] [pid 533599:tid 140576061348928] AH00094: Command line: '/usr/sbin/apache2' My … -
Django: ERROR: Cannot install -r requirements.txt
I was following the advices stated here How to run cloned Django project? because I have to work on a cloned Django project. The steps I followed are: Clone Create and start a virtual environment Install the project dependencies And here is when I get the following error after running pip install -r requirements.txt : Collecting django-private-chat==0.3.0 Using cached django_private_chat-0.3.0-py2.py3-none-any.whl (23 kB) INFO: pip is looking at multiple versions of django-polymorphic to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-parler to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-mptt to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-model-utils to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-meta-mixin to determine which version is compatible with other requirements. This could take a while. INFO: pip is looking at multiple versions of django-meta to determine which version is compatible with other requirements. This could take a while. … -
Getting Syntax Error when trying to run manage.py
I am getting a Syntax Error when I am trying to run python manage.py runserver I have created my virtual environment and there is no error in the code which I added. The Error message is coming from manage.py and the Django files. I am using Python 3.0.9. I added a new app using python manage.py startapp, but now python manage.py runserver gives me lines of Tracebacks. -
Order a list coming from model's Meta option in a @property
I have this model: class Author(models.Model): class Meta: app_label = 'myapp' surname = models.CharField(max_length=255) firstname = models.CharField(max_length=255) extrainfo = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return u"{0} {1} {2}".format(self.firstname, self.surname, self.extrainfo) @property def alpha_name(self): return u"{0}, {1} {2}".format(self.surname, self.firstname, self.extrainfo) class Meta: ordering = [self.surname] class Source(models.Model): class Meta: app_label = "bassculture" short_title = models.CharField(max_length=255) author = models.ForeignKey("myapp.Author", blank=True, null=True, on_delete=models.CASCADE, related_name="sources") View: def SourceList(request): sources = Source.objects.all() return render(request, 'source/source_list.html', {'sources': sources}) Template: {% for source in sources %} <tr> <td>{{ source.author.alpha_name }}</td> <td>{{ source.short_title }}</a></td> <td>{{ source.date }}</td> </tr> In the template I'd like the alpha_name to be ordered by surname. As you can see I did put the class Meta: ordering = ... in my Author model. Nevertheless, the template renders the list of authors ordered by id (the default ordering, I suppose). How can I order it via the model/view? I know about the |dictsort tag, and I tried to have the same result with that (with no luck, it returns empty). I'd like to have the model or the view sort the ordering anyway, reducing the template's logic to a minimum. -
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 …