Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to value Selected When edit form in Django?
I am updating my form, and it's succesfully updating, but I am selecting multiple values when i am editing the form, and my values are storing in database in this format 1,2,3,4 , Please let me know how i can display these values as selected in my html form. Here is my code... <select name='days' multiple> <option value='1' {% if datas.days == 1 %}selected{% endif %}>Day 1</option> <option value='2' {% if datas.days == 2 %}selected{% endif %}>Day 2</option> <option value='3' {% if datas.days == 3 %}selected{% endif %}>Day 3</option> <option value='4' {% if datas.days == 4 %}selected{% endif %}>Day 4</option> <option value='5' {% if datas.days == 5 %}selected{% endif %}>Day 5</option> </select> -
Django Full image is not loading
I am doing the Tango with Django tutorial. I am using Django version 3.1.1. I was able to get my image to load on the local link 'http://127.0.0.1:8000/static/images/rango.jpg' I am not getting it to load on to the index.html the code is <!DOCTYPE html> {% load static %} <html> <head> <title> Rango</title> </head> <body> <h1>Rango says...</h1> <div> hey there partner! <br /> <strong>{{ boldmessage }} </strong><br /> </div> <div> <a href="/rango/about/">About</a><br /> <img src="{% static 'images/rango.jpg' %}" alt="Picture of Rango" /> </div> </body> </html> I did try removing the "alt=" in html but that didn't work. I do not think the problem is my settings.py, but I'll share some parts of the settings.py anyway. TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # this is the file path for templates STATIC_DIR = os.path.join(BASE_DIR,'static') # this is the file path for static STATICFILES_DIRS = [STATIC_DIR,] ... #At the very bottom... STATIC_URL = '/static/' Any help is appreciated. -
How can I run Scrapy on AWS with django_crontab?
I am trying to run a scheduled cron job on AWS. I already try other Django scripts and it works well. I can start Scrapy with Django-Template and it works well. Cron.py from .models import Spiders import importlib from first_bot.start import startallSpiders def scheduled_spider(): all_class = [] spiders = Spiders.objects.all() for spider in spiders: spider_name = spider.spider_name name = 'first_bot.first_bot.spiders.'+spider_name i = importlib.import_module(name) class_ = getattr(i, spider.spider_class) all_class.append(class_) startallSpiders(all_class) Here I am getting all spider names and spider class' to start crawling same function works with Django-Template and view. start.py from scrapy.crawler import CrawlerProcess, CrawlerRunner, configure_logging, Crawler from scrapy.utils.project import get_project_settings from crochet import setup import importlib import time import logging import datetime setup() def startallSpiders(all_Class): now = datetime.datetime.today() now_time = now.strftime("%d-%m-%y") for class_ in all_Class: configure_logging(install_root_handler=False) logging.basicConfig( filename='scrapy-log-'+now_time+'.txt', format='%(levelname)s: %(message)s', level=logging.INFO ) runner = CrawlerRunner(get_project_settings()) runner.crawl(class_) Here I am crawling all class' that I sent from view.py or cron.py have startallSpiders function and it works well with Django view. settings.py CRONJOBS = [ ('35 11 * * *', 'Bot.cron.scheduled_spider') ] I already try another function in cron.py it works well again but I couldn't figure out why the scrapy not start. 01_cron.config files: "/etc/cron.d/cron_process": mode: "000644" owner: root group: … -
Trying to override a get_queryset in a view
class OwnerList(generics.ListAPIView): serializer_class = OwnerDetailSerializer # queryset = Person.objects.filter(customuser__userrole__role__name='OWNER').distinct() permission_classes = [IsAuthenticated] filter_backends = [DjangoFilterBackend] def get_queryset(self): return super(OwnerList, self).get_queryset() I have this simple view and i am trying to over ride the get_queryset. The issue is that when this view is used i get : return super(OwnerList, self).get_queryset() File "C:\Users\kdalipaj\PycharmProjects\LTC SYSTEM\venv\lib\site-packages\rest_framework\generics.py", line 63, in get_queryset assert self.queryset is not None, ( AssertionError: 'OwnerList' should either include a queryset attribute, or override the get_queryset() method. Why is this happening? -
creating a serializer for OneToOne
I'm new to django. I need to write a serializer for OneToOne related models Models.py class AbstractUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', ) email = models.EmailField(_('email address'), blank=True) created = models.DateTimeField(_('date joined'), default=timezone.now) class Participant(models.Model): user = models.OneToOneField(AbstractUser, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField( _('first name'), max_length=50 ) last_name = models.CharField( _('last name'), max_length=50, ) device_reg_token = models.TextField( _('text mobile token'), ) is_participant = models.BooleanField( _('participant status'), default=True ) I wrote a serializer but it only displays fields of the participant model Serializers.py class AbstractUserSerializer(serializers.ModelSerializer): class Meta: model = AbstractUser fields = ('phone_number', 'email', 'password') class ParticipantSerializer(serializers.ModelSerializer): abstractUser = AbstractUserSerializer(read_only=True) class Meta: model = Participant fields = ('first_name', 'last_name', 'device_reg_token', 'abstractUser') def create(self, validated_data): participant = Partner.objects.create_participant( phone_number=validated_data['phone_number'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], device_reg_token=validated_data['device_reg_token'], password=validated_data['password'], ) participant.save() return participant How can I display all fields of the Abstract and Participant models. ReadOnly throws an error when removed Views.py class CreateUserView(generics.CreateAPIView): queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ParticipantSerializer -
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 …