Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django orm filtering by month or day doesn't work with MySQL
I am using PostgreSQL for development. I need to filter some model by day so that I write that orm method. from django.utils import timezone now = timezone.now() today_count = Count( "id", filter=Q( created_at__year=now.year, created_at__month=now.month, created_at__day=now.day, ), ) Model.objects.aggregate(today=today_count) Also, I set USE_TZ to True in settings. This code works correctly with PostgreSQL but since we are using MySql on production, Always today_count returns 0. How can I handle this situation? -
Django App for Production Server using nginx and Gunicorn
I am trying to build a Django dashboard app for a production server using Nginx and Gunicorn. The app is running on the Nginx server. The login and authentication page is also working fine. I am using the default SQLite. The dashboard will retrieve sensor data and display on the dashboard in the form of charts on the dashboard. The user can reboot and power off the server from the Dashboard. There will be additional features too. Problem: I am trying to build the reboot and power off functionality using javascript (I am a newbie and learning through multiple coding attempts ) but I am unable to find a script. most of the suggestions on the internet is directing towards node.js. So please suggest me if there is a way in making these functionalities through javascript or shall I start learning node.js. If someone has already built a similar project and its available on Internet kindly share the link. Thanking everyone in anticipation. -
Serialization Django
There are three models: production, track, artist. Artists are foreign keyed to production, tracks are foreign keyed to artists. How to serialize the tracks inherent in the artists in specific production? I thought I need to change only the first argument of TrackSerializer in function get_tracks, but it actually returns 'tracks': [] def get_tracks(self, instance): serializer = TrackSerializer(Track.objects.filer(author=instance.artists.name), many=True, context=self.context) return serializer.data -
Django: Transfer multiple data into next template
Good day, I'm asking myself, if it's possible to transfer multiple informations as primary-keys inside my template!? For example, when clicking on a link inside my table... In this case im transfering the item-id: <tbody> {% for item in dataset %} <tr> <td> <a href="{% url 'Examplepage' item.id %}">Item-Name</a> </td> </tr> {% endfor %} </tobdy> Now I want to transfer the id and - let's say - the name! Is something like this even possible? <tbody> {% for item in dataset %} <tr> <td> <a href="{% url 'Examplepage' item.id item.name %}">Item-Name</a> </td> </tr> {% endfor %} </tobdy> And if it's possible, do I have to chage something inside my urls.py? Right now it's looking like this: path('index/<str:pk>', views.example, name="Example"), Thanks for all your help and a great day! -
Which is the best way to configure auth between two apis using Django rest framework?
I'm using DRF for developing an API and I want to consume this API with another API and with an app. For the second API, how can I develop an API authentication? I think that using JWT is not good because I'll need to save the token on the consumer Api and keep refreshing it. -
Django continue with next object in for loop when if statement applies
My Django application needs to have a transaction refund function. therefor I created the following snipped at admin.py: def mark_refunded(modeladmin, request, queryset): for transaction in queryset.all(): if transaction.status == 2: messages.error(request, 'Trx. ' + str(transaction.trx_id) + ' has already been refunded, skipping.') if transaction.fee: messages.error(request, 'Trx. ' + str(transaction.trx_id) + ' cannot be refunded as fees are not refundable!') elif do XYZ with the transaction ... return request Now I want my for loop to continue with the next item in the loop as soon as one of the above mentioned if statements do apply, who can that be accomplished? Currently it seems that the object(s) gets processed anyways, even when my if statement applies which also makes sense to me as I don't have "return request" at my if statement. But how can I then process all objects in my queryset? As soon as one transaction object in my queryset hits one of the if statements the for loop breaks Thanks in advance -
DataError .........timestamptz
I'm creating a movie store, on my localhost it works perfectly fine, but in heroku it gives me a syntax error, apparently heroku is confusing a models.DecimalField field with a DateTimeField. it does not allow me to migrate for the same error. heroku error it is the heroku error say DataError at /checkout/checkout invalid input syntax for type integer: "0.00" LINE 1: ... '2020-10-08T12:52:50.548680+00:00'::timestamptz signals.py the signals send date to models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from .models import OrderLineItem @receiver(post_save, sender=OrderLineItem) def update_on_save(sender, instance, created, **kwargs): """ update the order fields by signals """ print(instance.order.update_total()) instance.order.update_total() @receiver(post_delete, sender=OrderLineItem) def update_on_delete(sender, instance, **kwargs): """ update the order fields by signals """ view.py import uuid from django.db import models from django.db.models import Sum from django.conf import settings from catalog.models import Movies from django.db.models.signals import post_save, post_delete from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.conf import settings from .forms import OrderForm from catalog.models import Movies from .models import order, OrderLineItem from bag.mymovies import my_movies import stripe # This is your real test secret API key. # Create your views here. def checkout(request): stripe_public_key = settings.STRIPE_PUBLIC_KEY stripe_secret_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': bag … -
How to get matplotlib image from python called from Javascript
I have a Django web app which will be a dashboard to track the location of ISS using data from (http://api.open-notify.org/iss-now.json). I am having trouble looping the javascript to get the new image and update the src in the tag every 5 seconds. you can see the javascript is using setInterval to loop every 5 seconds. can someone help how i can call python function plot to get the uri to pass to the src in place of the dummy function urls.py from django.urls import path from . import views app_name = "appdjando" urlpatterns = [ path("", views.index, name="index"), path("plot", views.plot, name="plot") ] views.py where the returned uri variable is basically a base64 encoded buffer image saved from matplotlib PNG file. calling the plot function again or (a=TrackerISS(), def plot(request): home_name = 'Modena' a = TrackerISS() b = BasemapPlot(home_name, home_lat, home_lon) uri = b.plot_location(a.get_speed_iss_pos()) return render(request, "helloiss/plot.html", {'data':uri}) plot.html {% extends "helloiss/layout.html" %} {% block body %} <script type="text/javascript"> setInterval(function(){ document.getElementById("getMapImage").src = dummyFunction(); }, 5000); </script> <section id="two"> <div class="inner"> <h1 align="center">ISS location</h1> <p><br>Python chart here</p> <img id="getMapImage" src="data:image/png;base64,{{ data }}" alt="" height="400", width="700"> </div> </section> {% endblock %} -
Configure two virtual hosts with django and apache
Im trying to modify my existing stack to allow users to access two different versions of django app on one host. Due to internal DNS issues i can only work with domain corpnet.com/abc/ I tried to add two virtual hosts in abc.conf <VirtualHost *:443> WSGIScriptAlias /abc/prod /var/www/abc/abc-django/abc/wsgi.py ServerName corpnet.com/abc/prod DocumentRoot /var/www/abc/abc-django/abc ... </VirtualHost> <VirtualHost *:443> WSGIScriptAlias /abc/test /var/www/abc/abc-django-test/abc/wsgi.py ServerName corpnet.com/abc/test DocumentRoot /var/www/abc/abc-django-test/abc ... </VirtualHost> Apache seems to understand this configuration as apache2ctl -S returns: *:443 is a NameVirtualHost default server corpnet.com/abc/prod (/etc/apache2/sites-enabled/abc.conf:7) port 443 namevhost corpnet.com/abc/prod (/etc/apache2/sites-enabled/abc.conf:7) port 443 namevhost corpnet.com/abc/test (/etc/apache2/sites-enabled/abc.conf:43) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex watchdog-callback: using_defaults Mutex rewrite-map: using_defaults Mutex ssl-stapling-refresh: using_defaults Mutex ssl-stapling: using_defaults Mutex ssl-cache: using_defaults Mutex default: dir="/var/run/apache2/" mechanism=default PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="www-data" id=33 Group: name="www-data" id=33 Yet /abc/prod path works, while /abc/test returns 404 What am i missing? -
Does the UserCreationForm in Django automatically update itself to fit the custom user model or do you have to create a custom forms.py form
So my project has a complicated User-base setup which I'm hoping will work well using Django's custom user model but I'm curious whether or not I can use Django's built in UserCreationForm to render the custom fields in my custom user model or if I need to create a form in forms.py to render the new fields out myself. -
Check for unique constraint inside the save method
I have a model on which the unique_together parameter is not working. The reason is that most of the times the "client_repr" variable is set on the save() method. If someone creates a task with the same ('client_repr', 'task_type'... ) combination the model won't detect it because the "client_repr" value is null until the end of the save() method. How can i call for a unique constraint verification inside the save() method? class Task(models.Model): client = models.ForeignKey(Client, related_name = 'tasks', on_delete = models.CASCADE) b_client = models.ForeignKey(BClient, related_name = 'tasks', on_delete = models.CASCADE, null = True, blank = True) client_repr = models.CharField(max_length = 100, null = True, blank = True) task_type = models.CharField(max_length = 100) task_description = models.CharField(max_length = 100) department = models.ForeignKey(Department, related_name = 'tasks', on_delete = models.CASCADE) extra_fields = models.ManyToManyField(ExtraField, blank = True) spot = models.BooleanField(default = False) class Meta: unique_together = (('client_repr', 'task_type', 'task_description', 'department'), ) def __str__(self): return ' | '.join([f'{self.client_repr}', f'{self.task_description}', f'{self.task_type}']) def save(self, *args, **kwargs): if not self.b_client: self.client_repr = str(self.client) else: self.client_repr = str(self.b_client) super().save(*args, **kwargs) I know i could just make a search (ex: if Task.objects.get(...): ) but is it the most django-pythonic way? -
how to loop through a list of strings and print in Tabula form
am practicing python I have this issue here, I have a list of three teams,teams = ['manu','spurs','roma'] just looping through the index 0 i was able to print the outcome teams = ['manu','spurs','roma'] for m in teams[0]: print(m,'\t') ` but can I print all the teams in a tabula form like help out -
How to configure Editor js in Django?
I am currently making a blogging site in python and django and for blog editing a saw many text editing plugins for django like ckeditor but the one. I liked is Editor.js Can anyone tell me how to can I put the editor.js in Django the safest method possible? -
How to write manager class which use filter field as computed field not as a part of model fields?
have a model Student with manager StudentManager as given below. As property gives the last date by adding college_duration in join_date. But when I execute this property computation is working well, but for StudentManager it gives an error. How to write manager class which on the fly computes some field using model fields and which is used to filter records. The computed field is not in model fields. still, I want that as filter criteria. class StudentManager(models.Manager): def passed_students(self): return self.filter(college_end_date__lt=timezone.now()) class Student(models.Model): join_date = models.DateTimeField(auto_now_add=True) college_duration = models.IntegerField(default=4) objects = StudentManager() @property def college_end_date(self): last_date = self.join_date + timezone.timedelta(days=self.college_duration) return last_date Error Django gives. django.core.exceptions.FieldError: Cannot resolve keyword 'college_end_date' into field. Choices are: join_date, college_duration -
ImageField > height and width field type as PositiveIntegerField?
I am currently creating an ImageField and wonder what's the right type for image_height & image_width. I chose models.PositiveIntegerField(). Is that a good choice? I couldn't find any recommendations online yet. image = models.ImageField( verbose_name=_("Image"), height_field="image_height", width_field="image_width" ) image_height = models.PositiveIntegerField() image_width = models.PositiveIntegerField() -
Openedx mobile rest
Can anyone help with How can I set up open edx ios app I have followed the offical documentaion but I get only edx.org app what files should I change -
How download image from URL to django?
enter image description here I want to load an image by URL, but only the URL itself is saved to the model, how can I specify the path to save to the media folder, and how do I save it at all? -
django channles base64 encoded pdf too large, how to handle
async def receive(self, text_data): pdf_base64 = text_data['message'] ... I encoded pdf to base64 and uploaded to server, but the file is too large, how to read the text_data as a stream and I could decode the data using iterator in server side, thanks! -
Can BaseRenderers be cached?
I am returning huge CSV and PDF files with DRF (https://www.django-rest-framework.org/api-guide/renderers/). Is it possible to cache the responses? I have already @method_decorator(cache_page(60 * 60 * 24)) on dispatch method of the viewset, but it does not cache renderers. What can I do? -
Why does Django recreate the DB tables on each docker-container restart?
I am running Django with PostgreSQL in a docker-compose setup for development. Each time I restart the application container, the database is empty, even though I do neither restart the DBMS container nor do I drop the DBMS's data volume. It seems that Django is dropping all tables upon restart. Why? My setup closely follows the description here. That is, my compose file looks as follows (simplified): version: '3.8' services: db: image: postgres environment: - POSTGRES_DB=db_dev - POSTGRES_USER=dev - POSTGRES_PASSWORD=postgres volumes: - type: volume source: app-data target: /var/lib/postgresql/data app: build: . command: python manage.py runserver 0.0.0.0:8888 container_name: app environment: - DATABASE_URL - PYTHONDONTWRITEBYTECODE=1 - PYTHONUNBUFFERED=1 volumes: # Mount the local source code folder for quick iterations. # See: https://www.docker.com/blog/containerized-python-development-part-3/ - type: bind source: . target: /code ports: - target: 8888 published: 8888 depends_on: - db env_file: - ./dev.env volumes: app-data: external: true The Django application is started by means of an entrypoint.sh: #! /bin/sh if [ "$DATABASE" = "postgresql" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi doMigrate=${DB_MIGRATE:-false} if [ "$doMigrate" = true ] ; then python manage.py flush --no-input python manage.py migrate fi exec "$@" In the … -
Is there a way to make a django template variable variable into a for loop
I have this in my model: tank0 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank0') tank0MQTT = models.BooleanField(default = False) tank1 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank1') tank1MQTT = models.BooleanField(default = False) tank2 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank2') tank2MQTT = models.BooleanField(default = False) tank3 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank3') tank3MQTT = models.BooleanField(default = False) tank4 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank4') tank4MQTT = models.BooleanField(default = False) tank5 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank5') tank5MQTT = models.BooleanField(default = False) tank6 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank6') tank6MQTT = models.BooleanField(default = False) I would like in my template to make a for loop to generate the html and set the variable with the i in the for loop like this: {% for i in "0123456" %} <div class="row" style="margin-top:10px"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> Tank # {{forloop.counter}} </div> <div class="card-body"> <div class="row"> <div class="col-lg-2 col-md-3 col-sm-4 align-self-center"> <label><b>Serial:</b></label> <a href="#" id="{{obj.serial}}_tank{{i}}">{{obj.tank{{i}}.serial}}</a> <small id="{{obj.tank{{i}}.serial}}_serial_ts" class="form-text text-muted">{{obj.tank{{i}}.timeStamp}}</small> </div> </div> </div> </div> </div> </div> {% endfor %} Is there anyway way to do this ? -
How To Create Dynamic Routes in Django Rest Framework Based off a Model Column?
I am trying to create dynamic routes for django rest framework that filters based off a model's specific column value. There are different chefs who all have a specialty. I am trying to make it so I can go to localhost:8000/chef/< specialty >/ and it will only have chefs with that specialty listed. I've tried searching but I can't find any answers or even questions related to this. I've tried following the tutorial here on rest framework's website as well. I keep getting 404 errors or AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. models.py: class Chef(models.model) name = models.CharField(max_length=200) specialty = models.CharField(max_length=200) urls.py router = routers.DefaultRouter() router.register('chef/(?<specialty>.+)/$', views.ChiefModelViewSet()) url_patterns = [ path('', include(router.urls)), ] views.py class ChefModelViewSet(viewsets.ReadOnlyModelView): # it is ReadOnly because I only want it to be read only serializer_class = ChefModelSerializer def get_queryset(self): specialty = self.kwargs['specialty'] return Chef.objects.filter(specialty=specialty) -
Django Model.objects.get(...) case-insensitivity
I am developing a dictionary application and I have an Expression model defined as follows: class Expression(models.Model): expression = models.CharField(max_length=64, unique=True) In one of my views, I am using Expression.objects.get_or_create(expression=expression) to either get an Expression with expression "expression" or create it if it does not exist. Importantly, I want the comparison between "expression" and all existing Expression objects in my database to be case-insensitive. In other words, even though this is not valid syntax, I would like the logic of my search to be: Expression.objects.get_or_create(expression.lower()=expression.lower()) How can I achieve that? -
Django-rest-auth and allauth registration
I am self-learning Django auth and had a question about the django-rest-auth package. In the demo app of this package, both the endpoints /account/signup/ and /rest-auth/registration/ provide the same functionality (allow new users to sign up). Is there a way to only enable /rest-auth/registration/ and disable signing up via the /account/signup endpoint. I cannot completely get rid of the /account/ related urls because /rest-auth/registration/ uses the /account/confirm-email/Mw:1kQVfP:MxaGSypA88IVpvtwhFGHalSMUoO1Px4fJ5tBGpJVppk/ for email verification when I set the email verification related variables in the settings file. ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True -
TypeError: '<=' not supported between instances of 'decimal.Decimal' and 'dict'
I'm not sure how to resolve this issue. I tried to convert highest_bid to a float: highest_bid = float(Bid.objects.filter(id=bid_item.id).aggregate(Max('bid_input'))) but that also produced an error because a dict cannot be converted to a float in that way. So I'm not sure how to resolve this. I'm trying to build an auctions site and I would like the bid that a user places to be rejected if it is less than the listing start price and less than the highest of all the bids that have been placed. error Internal Server Error: /listing/2/bid Traceback (most recent call last): File "C:\Python\Python385\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python\Python385\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sarah\Desktop\commerce\auctions\views.py", line 157, in placebid if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid: TypeError: '<=' not supported between instances of 'decimal.Decimal' and 'dict' [08/Oct/2020 13:59:48] "POST /listing/2/bid HTTP/1.1" 500 62598 views.py def placebid(request, id): listing_bid = get_object_or_404(Listing, id=id) highest_bid = Bid.objects.filter(id=id).aggregate(Max('bid_input')) listing = Listing.objects.get(pk=id) if request.method == "POST": bidform = BidForm(request.POST) if bidform.is_valid(): if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid: return render(request, "auctions/listingPage.html", { "listing": listing, "error": "Make sure your bid is greater than the start price and current highest bid" …