Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Errors deploying my web application with elastic beanstalk and django
First time using aws and elastic beanstalk. My Django site works fine when I host it locally. I've followed the instruction on deploying a Django application using eb on the aws guide. I think my issues are related to my virtual environment. Can someone take a look at these screenshots and see if there are any obvious issues I am missing? command line pycharm elastic beanstalk errors -
Compress to zip file and add a password
I compress the csv file and returned the zipped file as follows in a Django project def get_csv_file(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="member.zip"' users = User.objects.all() file_path = os.path.join(tempfile.gettempdir(), 'member.csv') f = open(file_path, 'w') file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL) for user in users: file_writer.writerow([user.username, user.email]) f.close() z = zipfile.ZipFile(response, 'w') z.write(file_path) z.close() return response Is there any way to add a password protection to the files? I tried with pyminizip but dont know how to return it as a response object -
Make calculations for records inside pagination, django
I want to calculate the sum of two records but only inside the pagination. class MacaListView(ListView): model = Maca paginate_by = 20 def get_context_data(self, *, object_list=None, **kwargs): context = super(MacaListView, self).get_context_data(object_list=None, **kwargs) maca = Maca.objects.all() for i in range(0, maca.count()): maca = Maca.objects.get(maca[i].id) maca.number = maca.number + 1 maca.save() This will go to every single record and do the logic. I want the logic to be executed for only records in pagination (do calculate for only 20 records) -
import sqlparse ModuleNotFoundError: No module named 'sqlparse'
I have installed pip install sqlparse pip3 install sqlparse conda install sqlparse But still getting sqlparse module Why is that? -
JQuery Tablesorter: How to add changing icons to table column headers?
I'm trying to create a weather data website as my first project using django and bootstrap. Wanting to implement table sorting to sort the weather data table I happened upon this JQuery Tablesorter. I have implemented the sorting feature but how do I add the sorting icons to my column headers and have them change based on how the column is sorted? I have little to no experience with JavaScript. -
How to trim whitespaces from inside of string with min_length and max_length validation?
How to trim whitespace from inside of string with min_length and max_length validation? name = serializers.CharField(min_length=18, max_length=18, trim_whitespace=True, allow_blank=True, allow_null=True, required=False) test_string_that_should_be_invalid = "1111111111111111 1" test_string_valid = "111111111111111111" -
Can't access django url (page not found)
I have models like this : class Region(models.Model): region_parent = models.ForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) title = models.CharField(max_length=255) description = RichTextField() description_on_list = RichTextField(blank=True) thumbnail = models.ImageField( upload_to="thumbnail-region", blank=True, max_length=255) sidebar = RichTextField(blank=True) ad_manager = models.TextField(blank=True) meta_keywords = models.TextField(blank=True) logo_on_navbar = models.ImageField( upload_to="logo-on-navbar/", blank=True, max_length=255) display_on_navbar = models.BooleanField(default=True) slug = models.SlugField(unique=True) def get_absolute_url(self): if self.region_parent is not None: return reverse('vineyards:region', kwargs={'parent': self.region_parent.slug, 'region': self.slug}) else: return reverse('vineyards:region-without-parent', kwargs={'region': self.slug}) class Vineyard(models.Model): name = models.CharField(max_length=255) text = RichTextField() rating = models.FloatField() custom_overlay = models.ImageField( upload_to="custom-rating/", blank=True, max_length=255) google_map = models.TextField() wine_rg_url = models.URLField(blank=True) wine_rg = models.CharField(max_length=255) wines_url = models.URLField(blank=True) wines = models.CharField(max_length=255) size = models.CharField(max_length=255) grapes = models.CharField(max_length=255) owner_url = models.URLField(blank=True) owner = models.CharField(max_length=255) visits = models.CharField(max_length=255) region = models.ForeignKey(Region, on_delete=models.CASCADE) regions = models.ManyToManyField( Region, blank=True, related_name="regions") cover = models.ImageField(upload_to="vineyard/", max_length=255) sidebar = RichTextField(blank=True) ad_manager = models.TextField(blank=True) meta_keywords = models.TextField(blank=True) top_slider = models.BooleanField(default=False) cover_slider = models.BooleanField(default=False) hide_rating = models.BooleanField(default=False) slug = models.SlugField(unique=True) def get_absolute_url(self): if self.region.region_parent is not None: return reverse('vineyards:detail', kwargs={'parent': self.region.region_parent.slug, 'region': self.region.slug, 'slug': self.slug}) else: return reverse('vineyards:detail-without-parent', kwargs={'region': self.region.slug, 'slug': self.slug}) And this is my urls.py: app_name = 'vineyards' urlpatterns = [ path('<str:parent>/<str:region>/<slug:slug>/form/', rr_form, name="detail-form"), path('<str:region>/<slug:slug>/form/', rr_form, name="detail-without-parent-form"), path('<str:parent>/<str:region>/', vineyard_region, name="region"), path('<str:region>/', vineyard_region, name="region-without-parent"), path('<str:parent>/<str:region>/<slug:slug>/', … -
Passing a variable to python using Ajax method
I want to pass a variable using Ajax from a JS function to a python function in my Django project. I am able to call the python function. Using the ajax method, I know this because the print function in the python function runs. However how to I pass my variable through this ajax call? I just want to pass the local variable so it can be printed by the python function. JS function calling (){ var local = 25 $.ajax({ type:'GET', url:'printsome/', success: function(response){ console.log('success'); console.log(local); }, error: function (response){ console.log('error'); } }); } python def print_some(request): from django.http import JsonResponse print('this python function was called') return JsonResponse({}) -
Django : Page Not Found when trying to access static files
I know there are already several threads on the topic. I've been through most of them (especially all the troubleshooting listed in this one) but I can't figure out my issue. I am trying to use a Bootstrap template in my Django project, and I'd like to simply start by accessing the files in the /static/ directory. My project directory looks like this : Whenever I try to load the page http://localhost:8000/static/theme/assets/css/style.css it returns a Page not found error (and obviously no CSS/JS content appears on my index). Here are my settings: I have debug = True ÌNSTALLED_APPS contains django.contrib.staticfiles settings.py looks like this : STATIC_URL = "/static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) But I still can't access anything from the /static/ directory. I tried to access the CSS and JS files in base.html this way : {% load static %} ... <link href="{% static 'theme/assets/css/style.css' %}" rel="stylesheet"> I really have no clue how I could solve this. Thanks in advance for your help ! -
if am searching something iam getting the result from post but when i press next button it is going to get function to get data
#here when i search button iam getting data i want from post but when i used pagination to go to the next page it is again visiting to get function pls help me to class CrawlMonitorOverall(View): ELEMENTS_PER_PAGE = 1 def get(self, request: HttpRequest) -> HttpResponse: print("get") print(request) form = SearchButtonForm() execution_queryset = CrawlRuleExecutionModel.objects.all().order_by('-id') context_data = self._get_execution_data(request, execution_queryset, form) return render(request, 'crawl_monitoring/overall_view.html', context_data) def post(self, request: HttpRequest) -> HttpResponse: print("post") form = SearchButtonForm(request.POST) if form.is_valid(): execution_queryset = self._get_execution_queryset(form) context_data = self._get_execution_data(request, execution_queryset, form) return render(request, 'crawl_monitoring/overall_view.html', context_data) def _get_execution_queryset(self, form: SearchButtonForm) -> QueryType[CrawlRuleExecutionModel]: print(1) crawl_execution_name = form.cleaned_data["crawl_execution_name"] if crawl_execution_name: execution_queryset = CrawlRuleExecutionModel.objects.filter( crawl_rule__name__contains=crawl_execution_name).order_by('-id') else: execution_queryset = CrawlRuleExecutionModel.objects.all().order_by('-id') return execution_queryset def _get_execution_data(self, request: HttpRequest, execution_queryset: QueryType[CrawlRuleExecutionModel], form) -> \ Dict[str, Union[Paginator, Any]]: print(2) paginated_data = self._get_paginated_data(request, execution_queryset) execution_data = GenCrawlMonitorOverallContext().get_context(paginated_data) print(execution_data) context_data = { "execution_data": execution_data, "form": form, "paginator": paginated_data } return context_data def _get_paginated_data(self, request, query_set: QueryType[CrawlRuleExecutionModel]) -> Page: print(3) paginator = Paginator(query_set, self.ELEMENTS_PER_PAGE) page_number = request.GET.get('page') paginated_data = paginator.get_page(page_number) return paginated_data -
Hello design option : React + Django
I need your help on a design best option please, I am working on an app, the front is using react and the back is on Django. This is more a general question on how one should think when designing models! Should I rely on my front representation or what I personally think better is to align to objects normalization and abstraction. Here as an example: Let's say you two objects Company and Investment. A company could have many investments but an investment is linked to only one company. So you would add a foreign key to investment and in API level you would be able to list investment by companies like this : /api/company/id/investments Now this will return a list of investments per company. Now in front side I have only one investment to display, because only one investment/company could be active at a time (business rule). Here is my question, if let's say I filter by active= True /api/company/1/investments/?active=True I will get an array but this array will be always holding one investment. Is this a good design? Is there a way to force django to make an API filter response a json object instead of an array? … -
a technique for live updates other than firebase push notification fro my mobile flutter app
I was using the fcm push notification to get the real time updates(the update in my device,ie. whether the lights are manually off or on in the device etc..)get happen in the mobile application.But the push notifications are sometimes found missing and my app started showing sync issues to the real time. It could be very helpfull for me if anyone can suggest a better method to implement this process. I had heard about enabling a socket connection but dont know much about that. Thankyou -
Django Which model field to add an text editor when clicking on it?
I have my Django model and would like to add a text editor field. This text editor is representing like an Icon and when clicking on it, user must see it open and write any comment. I am not talking about django text input field where user can directly add comment in the form. I want something like that (in red circle). -
Why the login_requried decorator doesn't work after I log out from the account?
Working on a project using Django 3.2, I have been added new features to the project by adding a login/register page for the user. To do that, I used which I used this library provided by Django from django.contrib.auth.models import User, and as well in the views I used from django.contrib.auth import authenticate, login, logout library. After I finished the login/register successfully I decided to do the authenticate the home page for the reason that the user without an account can't have access to the home page. To do that I used the decorators from django.contrib.auth.decorators import login_required, and I used it on every view that I want to authenticate for the unregistered user. To understand it better will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def … -
Django nested serializers not returning what I want
I'm relatively new to Django and I'm working on an application that has me scratching my head. I have two models defined as follows: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(_('name'), max_length=50, blank=False) surname = models.CharField(_('surname'), blank=True, max_length=50) phone_number = models.CharField(validators=[phone_validator], max_length=16, blank=True) class History(models.Model): hist_id = models.AutoField(primary_key=True) user = models.ForeignKey( User, on_delete=models.CASCADE ) timestamp = models.DateTimeField(auto_now=False, auto_now_add=False) actions = models.JSONField(default=dict) traces = models.JSONField(default=dict) I would like to obtain a list of all users, and for each user I want all the History objects as a list. Here is the View I've created: class HistoryQuery(ListAPIView): serializer_class = HistorySerializer def get_queryset(self): return User.objects.all() and here is the serializer that I'm trying to use: class HistorySerializer(serializers.Serializer): class HistorySummarySerializer(serializers.Serializer): class Meta: model = History fields = ['hist_id', 'user'] history = HistorySummarySerializer(many=True, read_only=True) class Meta: model = User fields = ['history'] With this setup, I'm getting an array with length equal to the number of users that I have in my database, but each of its elements is empty. I cannot figure out what I'm doing wrong, so any help is appreciated. Should I reverse my logic and query the History model instead? If it is relevant, there are around … -
How to reverse filter based on latest entry in Django
I have a customer table and customer order table as below class Customer(models.Model): name = models.CharField() class CustomerOder(models.Model): customer = models.ForiengKey(Customer) item = models.CharField() datetime_of_purchase = models.DateField() Sample database entry Table: Customer id name 1 A 2 B 3 C Table: CustomerOder id customer item datetime_of_purchase 1 A item_3 2021-11-10 10:00:00 2 A item_2 2021-11-11 10:00:00 3 B item_1 2021-11-11 10:00:00 4 A item_1 2021-11-12 10:00:00 5 B item_2 2021-11-12 10:00:00 6 C item_1 2021-11-13 10:00:00 Suppose i need to filter customer whose latest purchase is 'items_1' so the sample after filtering should get only Customer 'A' and 'C' whose latest purchase is 'item_1' Sample: <QuerySet [<Customer: A>, <Customer: C>]> -
Django Rest Framework NoReverseMatch not a valid view function or pattern name
First some context : Models class : class Property(models.Model, AbstractUsagesLinked, AbstractErrorsFinder, InsurableMixin): type = models.ForeignKey(PropertyType, verbose_name=_('type de lot'), null=True, blank=True, related_name='properties_set', on_delete=models.CASCADE) # other fields Serializers class : class PropertySerializer(serializers.HyperlinkedModelSerializer, FlexFieldsModelSerializer): type = serializers.HyperlinkedRelatedField(view_name="api:propertytype-detail", read_only=True) # add hyperlink reference # others fields class Meta: model = Property fields = [field.name for field in model._meta.fields] expandable_fields = { 'type': (PropertyTypeSerializer, {'many': False}), # others fields } class PropertyTypeSerializer(serializers.HyperlinkedModelSerializer, FlexFieldsModelSerializer): class Meta: model = PropertyType fields = [field.name for field in model._meta.fields] Views class : @permission_classes((Check_API_KEY_Auth, )) class PropertyDetail(RetrieveAPIView): queryset = Property.objects.all() serializer_class = PropertySerializer pagination_class = CustomPagination @permission_classes((Check_API_KEY_Auth, )) class PropertyTypeDetail(RetrieveAPIView): queryset = PropertyType.objects.all() serializer_class = PropertyTypeSerializer pagination_class = CustomPagination Urls : api.urls.py : urlpatterns = [ # lots of path path('property/', views.PropertyList.as_view(), name="property-list"), path('property/<int:pk>/', views.PropertyDetail.as_view(), name="property-detail"), path('propertytype/', views.PropertyTypeList.as_view(), name="propertytype-list"), path('propertytype/<int:pk>/', views.PropertyTypeDetail.as_view(), name="propertytype-detail"), main.urls.py : urlpatterns = [ # lots of path url(r'^api/', include((api.urls, 'api'), namespace='api')), ] When i request property i get : django.urls.exceptions.NoReverseMatch: Reverse for 'propertytype-detail' not found. 'propertytype-detail' is not a valid view function or pattern name. django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "propertytype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on … -
Populate single dropdown from two tables in django python sqlite
I am new to Django, Please provide me any method to do this. Thanx in Advance. -
Missing Django core translations
I am trying to translate django core strings which for my language are untranslated in the original .po file. When I add them to my own .po file and translate them, the system works fine. The problem comes every time I use the makemessages command, since the generator interprets that those text strings have been deleted and comments them in the .po file. Can I hand generate a file that contains the translations and is not affected by the makemessages command? On the other hand, is it possible to tell him not to comment on the deleted lines? -
Django ORM: How to filter on many-to-many relation without filtering related objects
I have some Django models like following: class Film: genre = models.ManyToManyField("Genre", blank=True) class Genre(TimeStampedModel): name = models.CharField(max_length=50, blank=False) slug = AutoSlugField(max_length=55, unique=True, populate_from="name") Now, I want to select all films which are associated with the genre "Theatre" and get a list of all their associated genres: In [1]: from apps.base.models import Film, Genre In [2]: qs = Film.objects.filter(genre__slug='theatre') In [3]: set(qs.values_list("genre__slug", flat=True)) Out[3]: {'theatre'} However, this is not the result that I want. Looking at the genres of the first film returned as part of the queryset, we can see more genres: In [4]: set(qs[0].genre.all().values_list("slug", flat=True)) Out[4]: {'dance', 'education', 'theatre', 'video-recording'} How can I efficiently filter the films to those associated with the genre "Theatre" and retrieve their associated genres? -
What is the best way to embed videos with Google amp-story player in django
Am currently working on an app that i would want to add google Amp-story player to embed videos, but somehow the google amp play wont render the video or images from the database but rather when i pass a link to the video source which is not from my data base it works. I have tried writing custom template tag and filter to handle the the images but still I find it a challenge to get it to work. Is there a possible way to go out this. {% load ampimage_tag %} <head> <script async src="https://cdn.ampproject.org/amp-story-player-v0.js" onload="initializePlayer()" ></script> <link href="https://cdn.ampproject.org/amp-story-player-v0.css" rel="stylesheet" type="text/css" /> <script> // JS let player; function events() { console.log( "iframes", document .querySelector("amp-story-player") .shadowRoot.querySelectorAll("iframe") ); player.addEventListener("storyEnd", (data) => console.log("storyEnd", data) ); player.addEventListener("amp-story-player-close", () => { console.log("Close button clicked"); }); } function initializePlayer() { player = window.document.querySelector("amp-story-player"); if (player.isReady) { // Player loaded. Run e.g. animation. console.log("isready"); events(); return; } player.addEventListener("ready", () => { // Player loaded. Run e.g. animation. console.log("ready"); events(); }); } function show(story) { player.show(story); } function nextStory() { player.go(1); } </script> </head> <body> <button onclick="console.log( 'iframes', document.querySelectorAll('amp-story-player iframe') );" > add story </button> <button onclick="show('https://merci-handy.my.join-stories.com/collection-la-bouche-avis-kQoT9uov/',false)" > First story </button> <button onclick="show('https://webstoriesinteractivity-beta.web.app/arts-quizzes.html',false)" > Second story </button> … -
Integrate OAuth 2.0 prompt property with Django MS Graph
I'm using Microsoft Graph to manage Azure authentication on my django app. The thing is that it automatically logs the user if he previously used an account in his browser, so I want to use the property "prompt=select_account" from OAuth 2.0 but didn't find any doc on how to integrate this. Currently the app works with a slightly modified version of MS Graph tutorial with the following yml settings file: app_id: "xxxxxx" app_secret: "xxxxxx" redirect: "http://localhost/callback" scopes: - user.read authority: "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxx" I tried to add it as an option in this yml file : prompt: "select_account" Also tried in the authority url : authority: "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxx&prompt=select_account" Any link to follow or direct answer would be greatly appreciated, Thanks ! -
How to solve problem with admin panel when using gunicorn
How I can solve problem with django admin panel when using gunicorn. My admin panel doesn't support static files Here what i have in terminal web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/css/fonts.css web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js -
Django Rest Api - Password does not change
I use the built-in methods to change the Password of a user via a POST from the frontend, but the password does not update when calling the view. I do get an http 200 back though. Any advice ? views.py from rest_framework import status from rest_framework import generics from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import ChangePasswordSerializer from rest_framework.permissions import IsAuthenticated class ChangePasswordView(generics.UpdateAPIView): serializer_class = ChangePasswordSerializer model = User permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { 'status': 'success', 'code': status.HTTP_200_OK, 'message': 'Password updated successfully', 'data': [] } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Create your views here. serializers.py from rest_framework import serializers from django.contrib.auth.models import User class ChangePasswordSerializer(serializers.Serializer): model = User old_password = serializers.CharField(required = True) new_password = serializers.CharField(required = True) -
"post_save_user_model_receiver" is not defined
"post_save_user_model_receiver" is not defined I'm un able to use post_save_user_model_receiver do help me to solve the below problem