Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.0: Page not found at /polls/1/{url 'polls:vote' question.id}
I'm stucked at Django's official tutorial (see Writing your first Django app, part 4). I get the following error: In this Django project, inside the poll app I'm making, we're supposed to make a vote() view in views.py which should process the POST request data of the poll and redirect us to the results() view (there's no template for the vote()view, it's just in charge of processing the data we send through the poll). At first I thought I had a typo error, but I then copy-pasted everything directly out of the documentation tutorial (which I linked at the beginning of this question) and the error persisted. My directory structure looks like this for the app: (nevermind the errors, VSCode doesn't recognize Django'S ORM queries that's it) My urls.py file looks liket his: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] my views.py looks like this: from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Choice, Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, … -
Django: Object attribute not saving/updating
I have following model: class Device(models.Model): #more_code supplier = models.ForeignKey( Supplier, on_delete=SET_NULL, blank=True, null=True, related_name="devices" ) I need a Patch endpoint to change the supplier from a Device. Everything in the view looks to work, only the device.save() doesn't update the state of the object This is my view: def patch(self, request, site_pk): """ PATCH the device's supplier info of the site. """ all_device_token = False if request.data.get("device") == "ALL": all_device_token = True arguments = {} else: device_pk = request.data.get("device") arguments = {"id": device_pk} devices = Device.objects.filter(site_id=site_pk, **arguments).all() if not devices.exists(): raise PermissionDenied("The device does not belong to the site.") if all_device_token: serializer_class = self.get_serializer_class() serializer = serializer_class( devices, many=True, data=request.data, partial=True, ) serializer.is_valid(raise_exception=True) new_supplier = get_object_or_404(Supplier, pk=request.data.get("supplier")) for device in devices: device.supplier.id = new_supplier.pk device.supplier.name = new_supplier.name device.save() else: device = devices.first() serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True,) serializer.is_valid(raise_exception=True) if "supplier" in self.request.data: new_supplier = serializer.validated_data["supplier"] device.supplier.id = new_supplier.pk device.supplier.name = new_supplier.name device.save() # serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) My serialiser is returning the correct info to. Do I see something overhead? -
Django 2 models 1 from
I am creating a project and I will have multiple pdfs per timeline, so I have created these following models: As a beginner to Django, I am confused as to how to upload the pdf file (that will be uploaded by the user). When I display it on forms, it shows me a field that resembles the one displayed for CHOICES. If I try for one file, it works perfectly but for 2 it doesn't. Question is: How can I display the FileField from the pdf model? class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) pdfs = models.ForeignKey(Pdf, on_delete=models.CASCADE) This is my forms.py file: class TimelineForm(forms.ModelForm): class Meta: model = Timeline fields = ('header', 'age') class PdfForm(forms.ModelForm): class Meta: model = Pdf fields = ('pdf',) This is my view.py class: def upload_timeline(request): form = TimelineForm() return render(request, 'upload_timeline.html', { 'form': form }) -
How to use variables in django url path?
I am developing and Django website, and I have an array of some str values(parts of url).When user is redirect to: https://www.example.com/something/name/ how can system system knows that that is part of that arry. I alredy have this: urlpatterns = [ path(r'<name1>, views.example) ] And Array: arr = [name1,name2,name3, ....namen] Thank you in advance. -
How to reach and add new row to web server database which made in Django framework?
I am trying to create a web server which has Django framework and I am struggling with outer world access to server. While saying outer world I am trying to say a python program that created out of Django framework and only connects it from local PC which has only Internet connection. I can't figured it out how can I do this. I am building this project in my local host, so I create the "outer world python program" outside of the project file. I think this simulation is proper. I am so new in this web server/Django field. So maybe I am missing an essential part. If this happened here I'm sorry but I need an answer and I think it is possible to do. Thanks in advance... -
ModuleNotFoundError: No module named 'django_cleanup' while setup django application on Heroku
This is the first time when I try to setup my app on Heroku but I got error like in title. I checked almost everything, recreate requirements many times but it doesn't help. Someone has any idea how to solve this issue? #requirements asgiref==3.2.5 certifi==2019.11.28 chardet==3.0.4 dj-database-url==0.5.0 Django==2.2.10 django-cleanup==4.0.0 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 psycopg2==2.8.4 pytz==2019.3 requests==2.23.0 sqlparse==0.3.1 stripe==2.43.0 urllib3==1.25.8 whitenoise==5.0.1 -
Location of settings.py for Django project in an anaconda virtual environment
I am following this tutorial for Django : https://www.youtube.com/watch?v=F5mRW0jo-U4&t=881s and when he talks about the settings.py file, he has it in the src folder in his virtual environment. I have the anaconda version of python on my windows 10 machine, so I installed Django using the following steps in the anaconda command prompt: conda create -n djangoenv python=3.7 anaconda conda activate djangoenv conda install -c anaconda django However, when looking for the setting.py file in C:\Users\billbrad\Anaconda3\envs\djangoenv, there is no src folder, and I cannot find the settings.py folder anywhere. Did I set up the env incorrectly, or am I just looking in the wrong place? -
Redirecting a user when payment is completed in an django e commerce website
I want to Redirect a user when payment is completed in an django e commerce site .IAM using a payment gateway that sends a json object on the submitted webhook that contains payment status. -
Ajax like button doesn't work on django posts list
I create my first site with django and i'm trying to make the Ajax like button works on the listing posts page but actually I have to reload the page to have +1 ... My views : def likes_post(request): post_id = None if request.method == 'GET': post_id = request.GET['post_id'] like = 0 if post_id: post = Post.objects.get(id = int(post_id)) if post: like = post.likes + 1 post.likes = like post.save() return HttpResponse(like) My HTML TEMPLATE : {% for post in posts %} <div class="post-favourite"> <a href="#" data-posts-id="{{post.id}}" class="like text-danger">J'aime <i class="fa fa-heart-o likes_count"aria-hidden="true"> {{ post.likes }}</i></a> </div> {% endfor %} and the Ajax function : <script type="text/javascript"> $('.like').click(function(){ var ps_id; ps_id = $(this).attr("data-posts-id"); $.get('/likes_post/', {post_id: ps_id}, function(data){ $(this).prev().find('.like_count').html(data); }); }); </script> (The Ajax button for the post detail page works good with simply replace by : $('.like_count').html(data); at the last line) Could you please help me ? Thank you in advance for your help ! -
Edit result of annotate in a Django queryset
I have a queryset queryset = BigTable.objects.values('field1__code', 'field2__code').annotate(Sum('field3')) the resulting value field3__sum = "1234567" is an integer and is very long for my template. How can I divide it by 1000 (for example) and get out it a decimal like "1234,5" ? Thank you -
How to make a background script with Django which check regularly on an InfluxDB database?
Context I'm designing a vizualisation application (like Grafana) with Django. The data come from multiples sensors (temperature etc..) and are stored in an InfluxDB database. I'd like to have a front-end where the user can see all his past data. To achieve this i plan to fetch the data in python with the InfluxDB API and plot them in Javascript (with plotly.js for example) when the user click a button or something similar. The really big trend in IoT is to be able to receive an alert when a data, for example temperature, reachs a certain threshold. So i'd like to give the user the opportunity to set custom threshold and to receive mail alert for example when the criteria is met. Problem In a Django environment, python code is executed once you reach a certain ressource, so how i can create a Python code which would run complelty in background (the user can close his browser), and checks periodically if a certain field in the database goes above a certain threshold ? Moreover this threshold needs to be updated dynamically if the user wants to change it. Solution envisaged When the user sets a threshold, Django writes in a … -
Reverse for 'authorize' not found. 'authorize' is not a valid view function or pattern name
CODE - urls.py from django.contrib import admin from django.urls import path, include from django.contrib.admindocs.urls import urlpatterns import oauth2_provider.views as oauth2_views from django.conf import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from DESKTOP.CORE_INDEX import index_urls from DESKTOP.CORE_INDEX import about_urls from DESKTOP.CORE_INDEX import privacy_urls from DESKTOP.CORE_INDEX import roules_urls from DESKTOP.CORE_INDEX import contacts_urls from typing import List from rest_framework.schemas import get_schema_view schema_view = get_schema_view(title="API_DESKTOP") schema_view = get_schema_view(title="API_MOBAPP") urlpatterns: List[path] = [] urlpatterns += [ path('index/', include(index_urls)), path('about/', include(about_urls)), path('privacy/', include(privacy_urls)), path('roules/', include(roules_urls)), path('contacts/', include(contacts_urls)), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ERROR: django.urls.exceptions.NoReverseMatch: Reverse for 'authorize' not found. 'authorize' is not a valid view function or pattern name. [23/Mar/2020 18:13:57] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 170378 I tried to understand what's going on but I can't. It's always giving me the same mistake. Above is the code for the part that is constantly giving me an error and I can't find the error. Can help me? -
Django filter by ForeignKey-attribute as User
I'm using a Django framework to make a database-application. I have a my database structure as classes. A "Horse"-class that have a ForeignKey relationship with a "Rider"'-class, which in turn have a ForeignKey relationship with the User. It's all working, but I want to filter the horses so only the horses that are connected to the current User will show. file: models.py from django.contrib.auth.models import User class Horse(models.Model): name = ... ... owner = models.ForeignKey('Rider') class Rider(models.Model): name = ... ... user = models.ForeignKey(User) So when I render my html-page, I want to filter the horses accordingly: file: views.py from .models import Horse def Horses(request): horses = { 'horses': Horse.objects.filter( ??????? ) } return render(request, 'stable/horses.html', horses) So if I'm logged in as "Admin", how do I pass this into the filter, so all horses that have a relationship with a rider that have a relationship with this user will show? Seems to be something different when referring to a ForeignKey-object instead of just an attribute that I can't figure out. -
is it possible to run celery, celery beat and celery flower from one command?
I have installed celery, celery beat and celery flower all on one container, im using rabbitmq as the broker and Redis as the backend. settings below: app = Celery('itapp', broker='amqp://lcl_rabbit:5672', backend='redis://lcl_redis:6379', include=['itapp.tasks']) im trying to run all three of these on startup of one container, I have the command below, but it looks like its only running celery and flower and skipping beat. as I aren't seeing any scheduled tasks run celery flower -A itapp -l info --beat --scheduler django_celery_beat.schedulers:DatabaseScheduler --port=5555 is this not possible or not avisable? ideally im just looking to see the results of the tasks that have been scheduled with beat, I can see their being run as the last run timestamp is incrementing and I can see them being sent to a worker in the terminal. but not sure where I can see all the results and came across flower... Thanks -
Session handling in django
I have created web-app in django. App doesn't require any login logout activity. But, I used session variable and I am not deleting session. will it harm my site database? -
Adding a single field into group django admin
I'd like to know how to add a single field to a group of fields in a fieldset in DjangoAdmin. I've got this: class SecretarioAdmin(UserAdmin): model=Secretario def get_fieldsets(self, request, obj=None): fieldsets = list(super(UserAdmin, self).get_fieldsets(request, obj)) # update the `fieldsets` with your specific fields fieldsets.append(('Administrar', {'fields': ('administrar')})) return fieldsets That's my model: class Secretario(Usuario): administrar = models.OneToOneField(CentroEducativo, on_delete=models.CASCADE, null=True) And this is the error I'm getting: Unknown field(s) (i, a, r, s, m, d, t, n) specified for Secretario. Check fields/fieldsets/exclude attributes of class SecretarioAdmin. -
Change the Language that Django retrieves in timezone.now
So, Im running this code where I save the current time in the database when the field is created,however, It saves the time as "March 23,2020,4:11 pm", and I wanted to show it in Portuguese if possible. Can you explain me how I do it? This is the code, thanks: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): titulo=models.CharField(max_length=100) conteudo=models.TextField() data_publicacao=models.DateTimeField(default=timezone.now) autor=models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titulo -
Python/Django filtering posts by its categories
Trying to filter the posts by using anchor tag in template <a href="{% url 'post_list' %}?school=SchoolA&category=CategoryA">GO to POSTS</a> url of above is http://127.0.0.1:8000/post/?school=SchoolA&category=CategoryA For some reason this doesn't work and shows all posts no matter what category they have. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') posts = VideoPost.objects.all() if school_slug: posts.filter(school=school_slug) if category_slug: posts.filter(category=category_slug) posts = posts.order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) This works somehow, but I can't filter the posts by either one of them only. def post_list(request): school_slug = request.GET.get('school') category_slug = request.GET.get('category') posts = VideoPost.objects.all().filter(school=school_slug).filter(category=category_slug).order_by('-date_posted') return render(request, 'stories/browse.html', {'posts': posts}) It seems like there's some problem with if statement I assume, but I was not able to figure out. Any help would be much appreciated. -
Django ratelimit - how to display used limit in template?
on my website the user has the option to trigger a specific event 5 times a day, now I want to display the user how many times of today he has already triggered this action e.g.: "used: 2/5 times today". So how can I display the users ratelimit key in a django template? I found nothing at the documentations so far. https://django-ratelimit.readthedocs.io/en/stable/index.html thanks for reading -
Django: query to select model instances in a ManyToMany relation using set() method in serializer
I have a model for article tags: class Tag(models.Model): tag_name = models.CharField(max_length=10) additional_info = models.CharField(max_length=80) My Article model has ManyToMany relation with Tag model. class Article(models.Model): tag = models.ManyToManyField('Tag') When writing a article, writer gets to select as many tags as is available. Now, for the serializer to work, I have to use the set() method in the serializer class. My difficulty is in writing the query to fetch the tags selected while writing the article. I tried this but it's taking all the tags insted of only the selected ones: def update(self, instance, validated_data): instance.tag.set(Tag.objects.all()) What should be the query to fetch the tags selected during writing the blog only. -
Save large file AWS S3 django redis queue
Currently, a user is able to upload files, but large files* take too long. So far, I've been looking at solutions to upload the file async through the backend (django/python). For example a redis queue job that uploads (saves) the file. Is this a smart solution? If not, what could be another solution to upload large files without the user having to wait on the same page for the upload to be finished? Tech stack: vuejs django 2.2 python 3.5 AWS S3 bucket (file storage) *large files are considered files with a size from 10mb till 1gb. -
How can I run a python program with cooperation of a web server?
I want to launch a program from a local pc and connect it to a web server for some database operations such as creating a new user, creating a user list, listing all users who accessed the web server earlier. But I don't have information how to do it. I think Django can help me out in somewhere but I'm not sure. How can I do it, with which technologies or modules or methods? Thanks in advance... -
How to log django-kronos tasks with logging module?
I have switched from celery to dramatiq and celery beat to django-kronos and now I am stuck - I am not able to figure out, how to make tasks run by kronos to log using the logging module. Is it even possible or what is the best practice to log progress of django-kronos tasks? -
Django/Apache2 Context variables not availables
i'm a Django/Apache novice. following lots of tutorial i was able to build my small app for Home Domotic. Nevertheless i'm now experiencing a new problem. In Django app i have some templates that i call with views passing some CONTEXT variables. When i load the page with the internal Django Web Server (RUNWEBSERVER) the variables values are printed on the screen, but when i load the page with Apache the variables values are missing. Can somebody help me ? Thank you. Ciao. g -
PATCH doesn't save the new object state
I'm making a PATCH endpoint. It works almost fine.. but it doesn't save the endstate of the object when returning it to my test class. So in my serializer/view everything is updated but when I return serialiser.data to my test, it seems like my self.device is not updated. This is my code: view: def patch(self, request, site_pk, device_pk): """ PATCH the device's supplier info of the site. """ site_device = Device.objects.filter(site_id=site_pk, pk=device_pk) if not site_device.exists(): raise PermissionDenied("The device does not belong to the site.") device = site_device.first() serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True,) serializer.is_valid(raise_exception=True) if "supplier" in self.request.data: new_supplier = serializer.validated_data["supplier"] device.supplier = new_supplier device.save() serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) serializer: class AdminDeviceInfoSerializer(AdminDeviceSerializer): site = serializers.SerializerMethodField() owner = serializers.SerializerMethodField() country = serializers.SerializerMethodField() class Meta(AdminDeviceSerializer.Meta): fields = AdminDeviceSerializer.Meta.fields + [ "site", "owner", "country", "disk_space", "supplier", ] @staticmethod def get_site(device): #somecode @staticmethod def get_owner(device): #somecode @staticmethod def get_country(device): #somecode def to_representation(self, device): data = super().to_representation(device) if not device.supplier: data["supplier"] = None data["supplier"] = SupplierSerializer(device.supplier).data return data class AdminSiteDevicePatchSerializer(AdminDeviceInfoSerializer): class Meta(AdminDeviceInfoSerializer.Meta): fields = AdminDeviceInfoSerializer.Meta.fields test class: def test_change_supplier_devices_site(self): new_supplier = SupplierFactory(name="STWEB") self.client.force_login(self.admin_user) url = reverse( "admin-site-device-detail", kwargs={"site_pk": self.site.pk, "device_pk": self.device_1.pk}, ) response = self.client.patch(url, data={"supplier": new_supplier.pk}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_supplier.pk, self.device_1.supplier_id)