Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to customize the Django Admin page?
How do you customize the Django Admin Page, using your own custom page? I haven't tried anything yet, still using the default page -
Django Rest Framework send queryset to serializer try SlugRelatedField
Hi i am trying to send ordered query to my parent serializer try slug related field but i am getting "Object of type Supplier is not JSON serializable". i have also tried to make a "serializers.SerializerMethodField()" but i am getting the same error. is there a way to do something similar? in my model i am ordering it by name so i need to do another query so that i can order it by last visited. Should i make new model serialzier and make query there and pass it to parent serializer? models.py last_visited = models.DateTimeField(auto_now_add=True, null=True) class Meta: ordering = ["name"] @property def last_4_visited(self): return Supplier.objects.order_by('last_visited')[3] serializer.py suppliers = serializers.SlugRelatedField(slug_field='last_4_visited', many=True, read_only=True) -
Why I can not display two listviews in one template?
I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site. So I made listviews for listing the two HeroListView and NotificationListView for that. But the second one is not appearing in the page. Please tell me how to solve this issue. This is the models.py file from django.db import models class Hero(models.Model): image = models.ImageField(upload_to="heros/") class Notification(models.Model): notification = models.CharField(max_length=200) This is the views.py file. from django.views.generic import ListView from .models import Hero, Notification class HeroListView(ListView): model = Hero template_name = "home.html" context_object_name = "hero_list" class NoticficationListView(ListView): model = Notification template_name = "home.html" context_object_name = "notification_list" this is the app/urls.py file from django.urls import path from .views import HeroListView, NoticficationListView urlpatterns = [ path("", HeroListView.as_view(), name="home"), path("", NoticficationListView.as_view(), name="home"), ] this is the project/urls.py file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path("", include("heros.urls")), path("", include("products.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) {% extends '_base.html' %} {% block title %}Home{% endblock title %} {% block content %} {% load static %} <div class="container mt-4"> <div id="carouselExampleControls" class="carousel … -
How to use signed url to upload a file GCS using python/django (and possibly requests)
There are many examples to upload a file to Google Cloud Storage (GCS) using frontend/browser/js as below. However, I haven't seen much examples for uploading a file to GCS using python / django in the backend side. How can I modify the following code so it will use the signed url to upload a file to GCS. def Put(self, path, content_type, data): """Performs a PUT request. Args: path: The relative API path to access, e.g. '/bucket/object'. content_type: The content type to assign to the upload. data: The file data to upload to the new file. Returns: An instance of requests.Response containing the HTTP response. """ md5_digest = base64.b64encode(md5.new(data).digest()) base_url, query_params = self._MakeUrl('PUT', path, content_type, md5_digest) headers = {} headers['Content-Type'] = content_type headers['Content-Length'] = str(len(data)) headers['Content-MD5'] = md5_digest return self.session.put(base_url, params=query_params, headers=headers, data=data) -
Django app on docker. Problem with travis and logger
yestarday i added logging module to my django app. My app is running locally fine. The problem is with Travis CI. Travis is failing with building giving the error FileNotFoundError: [Errno 2] No such file or directory: '/electronic_shop/_logs/data.log': Travis building. As i understand, travis have problem with finding the _logs/data.log file. Firstly i thought adding new command to my docker file is enough (mkdir /electronic_shop/_logs), but i was wrong. So the question is, what can i do, to force travis to run my image? Docker is creating _log folder inside my image, so there should not be any error. Any ideas? Should i have to create files need for logger manually (in docker file)? Here is my docker file: FROM python:3.10-alpine EXPOSE 8000 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /electronic_shop RUN mkdir /electronic_shop/_logs WORKDIR /electronic_shop COPY . /electronic_shop RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -u 5678 --disabled-password --gecos "" user && chown -R user /electronic_shop RUN chown -R user:user /vol/ RUN chmod … -
django.core.exceptions.ImproperlyConfigured: The included URLconf 'notes.urls' does not appear to have any patterns in it
I get this error in the root directory, not in an app. The code in urls.py of this root directory is: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('write_notes.urls')) # write_notes is the name of my app. ] What is the error and how do i fix it? -
Why is my django-crontab cronjob not executing?
I have a django-project with an app called app that has a file called cron.py with a function called main_routine(). I want the main_routine() function to be called every minute. In my django-project/django-project/settings.py I have this: INSTALLED_APPS = [ 'django_crontab', ... ] ... CRONJOBS = [ ('*/1 * * * *', 'app.cron.main_routine') ] My django-project/app/cron.py looks like this: from app.models import SomeModel from django.utils import timezone def main_routine(): object = SomeModel.objects.get(name='TestObject1') object.updated = timezone.now() object.save() Of course I ran : python3 manage.py crontab add And the terminal printed: adding cronjob: (someHash) -> ('*/1 * * * *', 'app.cron.main_routine') To be safe I run: python3 manage.py crontab show And the terminal prints: Currently active jobs in crontab: someHash -> ('*/1 * * * *', 'app.cron.main_routine') To check if evrything works I run: python3 manage.py crontab run someHash Then I take a look at the admin page and see that TestObject1 has an updatet datetime of just now. (so far everything seems to be gooing smoothly) The main issue: No matter how long I wait the job will not be executed automatically. What am I doing wrong? -
I need to convert below sql query to django orm
This my SQL query, I need to convert this to django ORM SELECT ld.post_id, min( (ld.created AT TIME ZONE c.tz)::date ) as date, count(*) as post_booked FROM marketing_post ld INNER JOIN clinics_post c ON (ld.post_id = c.id) WHERE ld.post_id IS NOT NULL -- Only look for patient leads; AND ld.type = 'P' GROUP BY ld.post_id -
How does Django rest fremakework verify the secondary password?
I'm not using auth, I've added a re_password field to my serializer, I think it only does a consistency check with the password field when a POST request comes in. But the problem is that if re_password and password are write_only, then PUT and PATCH requests must also pass in these 2 fields. I guess the consistency validation of re_password and password is reasonable for user registration, but it is not so necessary for updating user information. What can I do to make re_password and password only required for POST requests? class UserSerializer(serializers.ModelSerializer): re_password = serializers.CharField(write_only=True, min_length=6, max_length=20, error_messages={ "min_length": "Password at least 6 digits", "max_length": "Password up to 20 characters", }) class Meta: exclude = ("is_delete",) model = models.User extra_kwargs = {**CommonSerializer.extra_kwargs, **{ "password": { "write_only": True, "min_length": 6, "max_length": 20, "error_messages": { "min_length": "Password at least 6 digits", "max_length": "Password up to 20 characters", } }, }} def validate_password(self, data): return hashlib.md5(data.encode("utf-8")).hexdigest() def validate_re_password(self, data): return hashlib.md5(data.encode("utf-8")).hexdigest() def validate(self, validate_data): if validate_data['password'] != validate_data.pop('re_password'): raise exceptions.AuthenticationFailed("password not match") return validate_data def create(self, validate_data): instance = models.User.objects.create(**validate_data) return instance def update(self, instance, validate_data): password = validate_data.get("password") validate_data["password"] = hashlib.md5( password.encode("utf-8")).hexdigest() for key, val in validate_data.items(): setattr(instance, key, val) instance.save() … -
Expected view to be called with URL keyword "pk" added "pk" to urls.py
Getting the error: AssertionError at /update_profile/ Expected view UpdateProfileView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_fieldattribute on the view correctly. when I try to update a user profile. Here is my urls.py path('update_profile/', views.UpdateProfileView.as_view(), name='update_profile'), My UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): # permission_classes = [permissions.IsAuthenticated] # authentication_classes = (TokenAuthentication,) # lookup_field = 'username' queryset = User.objects.all() serializer_class = UpdateUserSerializer @action(detail=True, methods=['put']) def perform_update(self, serializer): serializer.save(user=self.request.user.id) UpdateUserSerializer class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) class Meta: model = User #add 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name'] def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): user = self.context['request'].user if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] # instance.profile.city = validated_data['city'] # instance.profile.country = validated_data['country'] # instance.profile.bio = validated_data['bio'] instance.save() return instance I added the URL argument pk to my urls.py path('update_profile/<int:pk>', views.UpdateProfileView.as_view(), name='update_profile') This returns the error page not found at update_profile -
django messages framwork returning None when printed
I am new to django, i have stuck into an obvious issue which i cant unfold, at the form successful submission i have, put a message on the main home page where the user will be redirect to, the issue is its not returning the message.see below view: def service(request): form = GetStartedForm(request.POST or None) if form.is_valid(): form.save() x = messages.success(request, 'We have recorded your request and we will contact you soon!') print(x) print('Form Successfull!') return HttpResponseRedirect(reverse_lazy('home')) context = {'form': form} return render(request, 'bluetec/service.html', context) form: class GetStartedForm(forms.ModelForm): class Meta: model = GetStarted fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'size': 5, 'class': 'form-control', 'placeholder': 'Enter your name:'}) self.fields['phone_no'].widget.attrs.update({'size': 5, 'title': 'Phone No', 'class': 'form-control', 'placeholder': 'Enter your phone no:'}) self.fields['email'].widget.attrs.update({'size': 10, 'title': 'Email', 'class': 'form-control', 'placeholder': 'Enter your email:'}) self.fields['description'].widget.attrs.update({'size': 10, 'title': 'description', 'class': 'form-control', 'placeholder': 'Enter your projects description:'}) and the html is <body> <div id="wrapper" > {% include 'bluetec/messages.html' %} <!-- header begin --> <header class="{% block class %} header-light transparent scroll-light {% endblock class %}"> <div class="container"> <div class="row"> the messages.html file is {% if messsages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}" id="msg" role="alert"> {{ message }} </div> … -
Cpanel - I am trying to install pillow module on my python django web.. but is not installing
domain: www.snatchupjobs.com when I remove pillow modules lines from my website then my website run perfectly but when I do not remove the pillow lines from my website then my website stops working.. it shows an error "no module name pillow". actually, my application depends on this library. the flow of my website is that users can create a CV and also users can download it; on downloading processing time I used pillow module which will convert html to png then png to pdf file... so kindly help me to solve this code here is the lines I am getting from cpanel terminal when I run this command pip install pillow.. cpanel terminal error during the module installing time -
Replace NA value with "na"
class CardRecommendation(models.Model): sign_up_bonus_special_category_spend_threshold = models.IntegerField(null=False, default=None) sign_up_bonus_special_category_spend_time_threshold = models.IntegerField(null=False, default=None) annual_fee_description = models.CharField(max_length=1024, null=False, default=None) annual_fee_amount_first_year = models.IntegerField(null=False, default=None) annual_fee_amount_second_year_onwards = models.IntegerField(null=False, default=None) purchase_intro_apr_description = models.CharField(max_length=1024, null=False, default=None)`enter code here` In this model field I am inserting data from CSV to Database. In case if I get "NA" value from CSV i have to enter "na" in database in both case either it is CharField or IntegerField. Please help how can I do this. -
How do you retrieve request.user in Django rest framework in CORS?
How do you get request.user and check if the user is authenticated or its username or so on in DRF in CORS environment? I'm new to the field of SPA, single page application. For a SPA app it's common to use DRF I heard, so I now want to utilize it to authenticate the user to return a different response. For example, simply when the user is an authenticated user w/ username then returns his username to the json response, or returns empty "" response when not his is logged-in. When it's a same-domain environment e.g. client: localhost:8000 -> api: localhost:8000/api/requested_user ; DRF can retrieve its user state well. But when it's a different domain e.g. client: localhost:8080 -> api: localhost:8000/api/requested_user ; , DRF cannot retrieve the data that checks if the user is logged-in. Example, when I have the following urls.py that handles API requests, # urls.py class RequestedUserView(APIView): permission_classes = [] def get(self, request, *args, **kwargs): return Response(data={ "is_authenticated": request.user.is_authenticated, "id": request.user.id, "username": request.user.username, }) def post(self, request, *args, **kwargs): pass urlpatterns = [ path('api/requested_user', RequestedUserView.as_view()), ] the former same-domain request (e.g. :8000 -> :8000) gives something similar to {is_authenticated: true, id: 7, username: 'ami'} when the client … -
module 'django.db.models' has no attribute 'EmbeddedField'
New to python, and getting the above error writing a simple model. I am developing on VSCode if that matters. Below are my packages, installed in venv. asgiref==3.5.0 Django==4.0.3 djongo==1.3.6 dnspython==2.2.1 Pillow==9.0.1 pymongo==4.0.2 pytz==2022.1 sqlparse==0.2.4 Just a simple model to test... from django.db import models class ItemSku(models.Model): ProductSku = models.CharField(max_length=10) class ItemsCollection(models.Model): ProductName = models.CharField(max_length=30) ProductDescription = models.CharField(max_length=300) ProductFeatures = models.CharField(max_length=300) ProductCategory = models.CharField(max_length=300) ProductCountryOfOrigin = models.CharField(max_length=30) ProductSkus = models.EmbeddedField(ItemSku) One other thing, is that I can connect to mongodb using djongo, and am able to makemigrations and migrate and view in Django admin without the 'EmbeddedField', I am just not able to create an embedded document. I hope this makes sense. Any help is greatly appreciated. -
Does prefetch or select_related help when using a model @property
I have a model like this: class Order(Model): ... @property def all_shipments_shipped(self): return all([shipment.is_shipped for shipment in self.shipments.all()]) class Shipment(Model): ... order = ForeignKey(Order, related_name='shipments', on_delete=SET_NULL, null=True) @property def is_shipped(self): return (calculate if shipped based on tracking status) and a viewset like this: @action(methods=['GET'], detail=False, url_path='num_not_shipped') def num_not_shipped(self, request): qs = self.request.user.orders.all() num_orders_not_shipped = len([i for i in qs if not i.all_shipments_shipped]) return Response(num_orders_not_shipped, status=status.HTTP_200_OK) Would adding a qs = qs.select_related('shipments') help being as that the shipment is used in the model property and not in the viewset? Thanks for the help -
How to get period per user using Django template or queryset
The history is recorded whenever the teacher (person in charge) is changed. The result of the code below is nicely tabled. [html] {% for h in research.history %} {% ifchanged h.teacher %} Teacher: {{h.summary_json.field_summary.teacher}} Changed Date: {{h.changed_date}} {% endifchanged %} {% endfor %} The amount is too large to upload the entire code, so please understand that I am uploading only the above code first. I want to get the duration for each Teacher, but is there a way to implement the result below in template or queryset or python? Teacher Changed_date None -> who 2021-04-12 who -> Yeri/Halen 2021.05.12 Yeri/Halen -> Yeri 2021.09.23 Yeri-> Yeri/Halen 2021.10.12 Yeri/Halen -> Yeri/Sophia 2022.02.25 the final result I want. Yeri: 289(day), Halen: 270(day), Sophia: 34(day) -
Python program to get the count of happening Largest straight
Seems like my future depends on answering this question I'm completely new to Numpy can someone give me code for this question You are rolling 5 dice at a time. When the dice come out as 1-2-3-4-5 or 2-3-4-5-6, then it is called a largest straight. Write a python program to get the count of happening largest straight when we simulates rolling five dice 10000 times. -
Django not accounting for Daylight Savings Time
The issue is pretty simple, but I can't for the life of me find any information on it. Based on my internet searches, it seems like this should be a non-issue; Django should be doing this automatically. My issue is that ever since DST began, Django has been converting times to displays on the webpages 1 hour before the times should be. I say converting to because I've enabled "USE_TZ" in settings, so the times are being saved to the database in UTC, but the times are incorrectly converted to EST as they are one hour behind. What could be causing this? -
How to get one value (clicked one) from for loop in JS addEventListener Django project
Im trying connect JS inside my Django project I got message in console that HTMLCollection(2) [p.currency-one, p.currency-one] HTMLCollection(2) [input.amount-one, input.amount-one] app.js:21 Uncaught TypeError: c1.addEventListener is not a function at app.js:21:4 (anonymous) @ app.js:21 JS file const c1 = document.getElementsByClassName("currency-one"); const c2 = document.getElementById("currency-two"); const amount1 = document.getElementsByClassName("amount-one"); const amount2 = document.getElementById("amount-two"); const swap = document.getElementById("swap"); const theRate = document.getElementById("rate"); console.log(c1,amount1) function calculate() { const curr1 = c1.innerHTML; const curr2 = c2.innerHTML; const rate = parseInt(amount1.value) / parseFloat(amount2.innerHTML); theRate.innerText = `You can buy maximum -> you wallet money ${amount1.value} ${curr1} = ${rate} ${curr2}`; } // THIS PART OF THE CODE does not know how to get two pieces of information from one //class, how to get through it ? c1.addEventListener("change", calculate); amount1.addEventListener("input", calculate); c2.addEventListener("change", calculate); amount2.addEventListener("input", calculate); swap.addEventListener("click", () => { const flash = c1.value; c1.value = c2.value; c2.value = flash; calculate(); }); view.py def a(request,crypto_name, fiat_currency=None): buttons = [ {"currency_type": "USD", "active": "", "display_text": "USD"}, {"currency_type": "EUR", "active": "", "display_text": "Euro"}, {"currency_type": "CNY", "active": "", "display_text": "Chinese Yuan"}, {"currency_type": "JPY", "active": "", "display_text": "Japanese Yen"}, ] for button in buttons: if button['currency_type'] == fiat_currency: button['active'] = 'active' crypto_detail_view = load_detail_crypto(crypto_name,fiat_currency) user_purchased_currencies = UserPurchasedCurrencies.objects.filter(user = request.user) user_walet_info_amount_and_name = [x for i … -
Django MEDIA not accessible
My Django app is unable to see MEDIA directory. When I run one of my views I need to open a file. The scenario is to: take a record with requested id from data base get the file path to a file send the file to external server for OCR purposes models.py from django.db import models from django.contrib.auth.models import User class Homework( models.Model): title = models.CharField(max_length = 200, default = None) image = models.FileField(upload_to='user_scans/') author = models.ForeignKey(User, default=None, on_delete = models.CASCADE) latex = models.TextField(default = "No LaTeX Here") settings.py: from pathlib import Path from django.conf.urls.static import static BASE_DIR = Path(__file__).resolve().parent.parent ... DEBUG = True ... STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = "/media/" views.py import requests import json from django.shortcuts import render, get_object_or_404 from .models import Homework def create_homework(request): if request.method == 'GET': #some GET stuff if request.method == 'POST': homework = Homework() homework.title = title homework.image = image homework.author = author homework.save() id = homework.id json_to_mathsnip(id) .... def json_to_mathsnip(id): homework = get_object_or_404(Homework, pk=id) f = open(homework.image.url, "rb") ... some later stuff ... Unfortunately I'm constantly running into an error: FileNotFoundError at /homework/new [Errno 2] No such file or directory: '/media/user_scans/kwa.png' My … -
wsgi_mod fails to host Django with python3.10 on CentOs
My goal is to host Django app on CentOs 7 with python3.10 I've manage to download and configure Python, sqlite to work with manage.py runserver but it dosn't work when i try to host it with apache. Apache throws error: ImportError: /usr/local/lib/python3.10/lib-dynload/_sqlite3.cpython-310-x86_64-linux-gnu.so: undefined symbol: sqlite3_trace_v2 Installed Versions System: CentOs 7 Python: 3.10.4 sqlite: 3.28.0 mod_wsgi: 4.9.0 Apache: 2.4.6 Apache .conf WSGIScriptAlias / /var/www/portal/portal/wsgi.py WSGIPythonPath /var/www/portal/:/var/www/venv/lib/python3.10/site-packages <VirtualHost *:80> ServerName 192.168.1.25 Alias /static /var/www/portal/static/ DocumentRoot /var/www/portal <Directory /opt/portal/static> AllowOverride All Require all granted Allow from all </Directory> <Directory /var/www/portal/portal> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Full Traceback: Traceback (most recent call last): File "/var/www/portal/portal/wsgi.py", line 22, in <module> application = get_wsgi_application() File "/var/www/venv/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/venv/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/var/www/venv/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/var/www/venv/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from … -
Gallery Field in django
I want to implement extra images for my products in a Django webstore. I want to know if there is any fields,(or alternatively ways) to have an unknown number of images stored under a certain name in Django models -
How do i write the django query filter when multiple joins are involved in Django?
I would like to translate the below SQL query for the schema shown in the snapshot into Django. How do I accomplish this? select * from purchase inner join customer on customer.id = purchase.customer_id inner join seller on seller.id = purchase.seller_id inner join manager on seller.id = manager.seller_id -
Bypassing Cloud Run 32mb error via HTTP2 end to end solution
I have an api query that runs during a post request on one of my views to populate my dashboard page. I know the response size is ~35mb (greater than the 32mb limits set by cloud run). I was wondering how I could by pass this. My configuration is set via a hypercorn server and serving my django web app as an asgi app. I have 2 minimum instances, 1gb ram, 2 cpus per instance. I have run this docker container locally and can't bypass the amount of data required and also do not want to store the data due to costs. This seems to be the cheapest route. Any pointers or ideas would be helpful. I understand that I can bypass this via http2 end to end solution but I am unable to do so currently. I haven't created any additional hypecorn configurations. Any help appreciated!