Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files always returning 404 179
I have been trying every video or post I can possibly find on the internet none of that seems to work unless a run on the insecure mode. I'm using Django 3.0.10 At the moment I'm working locally to after deploy on Cpanel. But even after I tried to deploy the problem is the same. They always return 404 179 for every static file even that I can go through the files and see they are all there. The only anomaly that I have when working locally is that my username contains spaces. I follow each step on the docs and still didn't work. I change the collectstatic folder and where to find the files I want know if there is something I'm doing wrong. I even add to the urlpatterns += staticfiles_urlpatterns and also add the project name to the INSTALLED_APPS. STATIC_ROOT = os.path.join(BASE_DIR, 'app\static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Thank you in advance! -
How to add a button using bootstrap
I'm new to Django and bootstrap and currently working on a project. Basically my question is purely on html and css. I want to insert a button on the right side of the box. I use the following code: <div class="col-md-12 text-right"> <a href="{% url 'listing' listing.id %}" class="btn btn-info">More Info</a> </div> However i get: As you can see there is a gap because of the button, how can i put this button without this gap. Thank you -
Django: How do I delete one Address instance out of many based on current user using APIView
I have an Address model which can have multiple instances per user. I am using APIView to delete one out of many instances but I can't figure out how do i chose the one instance for the logged in user. My view: class AddressView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): ... def put(self, request): ... def get(self, request, format=None): ... def delete(self, request, format = None): id = request.GET.get('id', '') address = get_object_or_404(Address, id = id) address.delete() return Response({"message": "Address has been deleted."}) I have defined a plain URL that handles GET, POST and PUT along with this DELETE: path('address/', AddressView.as_view(), name='user_address'), I understand it has many flaws but every time I run this, I get this error: ValueError: Field 'id' expected a number but got ''. How should be the right view to delete an Address instance for the logged in user? -
Django form - user url attr to fill automatically the form - RelatedObjectDoesNotExist
I'm still stuck with my issue. So I've found a new way to do it. Better I think Your help will be really appreciate. path('new/<seller>/', CreateChannelSellerView.as_view(),name="channel_to"), Assume I got .../new/fredo/ -> fredo is the username of the seller. I want to catch it. But I got an issue: Exception Type: RelatedObjectDoesNotExist Exception Value: Channel has no seller. Trace: form.instance.seller.add(existed_seller) "%s has no %s." % (self.field.model.name, self.field.name) views.py class CreateChannelSellerView(CreateView): model = Channel form_class = CreateSellerChannelForm template_name = 'channel_seller_new.html' def form_valid(self, form): form.instance.consumer = self.request.user seller_field = self.kwargs['seller'] current_seller = User.objects.filter(username=seller_field) if current_seller.count()<1: raise forms.ValidationError('Username does not exist') else: existed_seller = User.objects.get(username=seller_field) form.instance.seller.add(existed_seller) form.save() return super(CreateChannelSellerView, self).form_valid(form) def get_success_url(self): return reverse_lazy('channel:channel_home') models.py class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super().save(*args, **kwargs) def __str__(self): return self.name forms.py class CreateSellerChannelForm(forms.ModelForm): class Meta: model = Channel widgets = { 'name':forms.TextInput(attrs={'class':'','style':'','placeholder':'First group'}), } fields = [ 'name', ] -
Django FileField: cómo devolver solo el nombre de archivo (en la plantilla)
Tengo un campo filefield para subir archivos en una ruta establecida desde mi modelo files = models.FileField(upload_to="files/%Y/%m/%d") Pero cuando desde mi html lo muestro, en lugar de aparecer solo el nombre del archivo me aparece la ruta completa {% for item in Anexo %} <a href="{{ item.files.url }}"><br/> {{ item.files }}<br/></a> {% endfor %} Encontre informacion aqui pero es de 2008 y no me funciona la solucion. -
Django loaddata fails: models.DoesNotExist
I try to works with fixtures which are normally simple but got an error I do not understand I've made a fixture using dumpdata command I flush my database and try to load (loaddata) my fixture but got an error: raise self.model.DoesNotExist( parameters.models.DoesNotExist: Thesaurus matching query does not exist. so I can "resolve" this error iby changing the line that raise error but I want to understand what is wrong Is it related with admin form? class RandomisationSecoursFormAdmin(forms.ModelForm): LIBELLE = Thesaurus.options_list(3,'fr') ***<- line that raise error*** bra_lib = forms.ChoiceField(label="Libellé du bras", widget=forms.Select, choices=LIBELLE) ... if I change line that raise error with the code below, it works if Thesaurus.objects.filter(the_ide = 3).exists(): LIBELLE = Thesaurus.options_list(3,'fr') else: LIBELLE = [] -
how to use any() and all() function in django templates without custom templates tag
i have some situation where i got python dict as data which i want to check if any( any(dict.values) ) value exist or not.. but not sure how to use any() or all() function in django templates. is there any built in filter ?? {% if search_result.result.show_more.values %} <tr class="header"> <th colspan="4">{% trans 'Charges Info' %}</th> </tr> {% endif %} if any value exist in showmore dict the i want to display header. -
How can I make Django user logout without a new url page?
For logout I am using ready django.contrib.auth.LogoutView and everyone in their tutorials are creating a new url for example '/logout' and my question is how can I use that view without a new url page and html template? Plese use some code for views.py in your answers ;) -
Can I edit the datetime field before saving in database in django?
I am uploading an excelsheet in which date is in format 08-10-2020(DD-MM-YYYY). When it's saved in the database, it becomes, Oct. 8,2020 8:50 p.m. But I want the date to be saved in YYYY-MM-DD format. Is this posssible? My models.py looks like this: from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() bday = models.DateTimeField(auto_now_add=True) year = models.IntegerField() def __str__(self): return self.name -
Where to put 'allow_empy_files` in a Django form?
I currently have this form and I want to allow the user to upload empty files but I'm not sure on where to add allow_empty_files. class FileUploadForm(forms.ModelForm): class Meta: model = Uploaded fields = ( 'name', 'description', 'file', 'usertags', ) -
Is there way to add Q objects in django?
I am passing multiple values in a list and I want to filter my queryset with this values. I know about Q object but I don't know how to add filters together. I thought of something like: categories = ['1','3','4'] for category in categories: Q+= Q(id = category) and after that I would filter my queryset queryset.filter(Q) -
Django Templates Configuration
hello everyone I am beginner in this industry I am not for long installed django 3 for python 3 on kali linux I put inside settings.py/TEMPLETES my file name but its not works I am looking for over 5 days from internet but I can not find answer pls help me -
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 %}