Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Content-Security-Policy to disable header " X-Frame-Options: deny "?
I created a website in Django that I deployed on heroku. I am trying to display this website from an html page using an iframe. However, when I load my html page, I get the error: gkwhelps.herokuapp.com refused the connection. And when inspecting the page I get the following message:Refused to display 'http://gkwhelps.herokuapp.com/' in a frame because it set 'X-Frame-Options' to 'deny'. To solve this problem, I modified my settings.py like this: MIDDLEWARE = [ ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def ok_to_load_in_a_frame(request): return HttpResponse("This page is safe to load in a frame on any site.") and I updated my site. But despite this, I still get the same error when I reload my page. I don't know why yet I updated my site. -
Aggregate by another table after annotate
I have next annotate qs.annotate( goods_with_sales=Count('goods', filter=Q(goods__history__sales__gt=0)), ) Same goods_with_sales_percent=goods_with_sales / sum_sales * 100 I need get percent of goods_with_sales to sum of all goods__history__sales. I try it with Window but not happiness... This is raw sql query: SELECT "wb_brand"."created", "wb_brand"."modified", "wb_brand"."id", "wb_brand"."name", COUNT("wb_good"."id") FILTER ( WHERE "wb_stockshistory"."sales" > 0 ) AS "goods_with_sales" FROM "wb_brand" LEFT OUTER JOIN "wb_good" ON ( "wb_brand"."id" = "wb_good"."brand_id" ) LEFT OUTER JOIN "wb_stockshistory" ON ( "wb_good"."id" = "wb_stockshistory"."good_id" ) GROUP BY "wb_brand"."id" Also I tried this with CTE, but not happiness also. How can I solve it with Django ORM (prefer) or with SQL ? P.S. Also must be CASE/WHEN condition for divisizon by zero if sum_sales == 0. -
HTMX not working when using paginate with infinite-scroll
I have a product card in my Django Application, when clicked, adds to cart. I'm using infinite-scroll and django-pagination. The issue is with the pagination, however. The first page of results works wonderfully with HTMX. However, the second page and all pages beyond does not work on click. Upon inspecting the page, the html does appear to be rendered properly and I can see the hx-get call with the proper url. But upon clicking, nothing happens. Maybe I'm missing something obvious here, but any help would be appreciated! HTML <div class="container" data-infinite-scroll='{ "path": ".pagination__next", "append": ".product-card", "history":"false"}'> {% block content %} {% include 'includes/cards.html' %} {% include 'includes/sidebar.html' %} {% endblock content %} </div> <ul class="pagination mt-50 mb-70"> {% if products.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ products.previous_page_number }}"><i class="fa fa-angle-left"></i></a></li> {% endif %} <li class="page-item"><a class="page-link" href="#">{{ products.number }}</a></li> {% if products.has_next %} <li class="page-item"><a class="pagination__next" href="?page={{ products.next_page_number }}"><i class="fa fa-angle-right"></i></a></li> {% endif %} </ul> views.py def shop(request): anabanner = AnaBanner.objects.all() gender = Gender.objects.all() categories = Category.objects.all() colors = Color.objects.all() materials = Material.objects.all() query = request.GET.get('query','') products = Product.objects.all().order_by('-pk') if query: products = products.filter( Q(name__icontains=query)| Q(sub_name__icontains=query) ).distinct() paginator = Paginator(products, 8) page = request.GET.get('page') products = paginator.get_page(page) context = {'products':products,'categories':categories,'gender':gender,'anabanner':anabanner,'colors':colors,'materials':materials} … -
I am trying to run "python manage.py runserver" for Django project
1 This is the error I got I tried changing the SQLite version Still it does not work -
Handling repetitive content within django apps
I am currently building a tool in Django for managing the design information within an engineering department. The idea is to have a common catalogue of items accessible to all projects. However, the projects would be restricted based on user groups. For each project, you can import items from the catalogue and change them within the project. There is a requirement that each project must be linked to a different database. I am not entirely sure how to approach this problem. From what I read, the solution I came up with is to have multiple django apps. One represents the common catalogue of items (linked to its own database) and then an app for each project(which can write and read from its own database but it can additionally read also from the common items catalogue database). In this way, I can restrict what user can access what database/project. However, the problem with this solution is that it is not DRY. All projects look the same: same models, same forms, same templates. They are just linked to different database and I do not know how to do this in a smart way (without copy-pasting entire files cause I think managing this … -
What does "DEFAULT_PERMISSION_CLASSES will only work for the views or objects that don't have permissions explicitly set." mean?
I was reading below mentioned blog which is about Built-in permissions in DRF Source: https://testdriven.io/blog/built-in-permission-classes-drf/ In this blog there is statement: DEFAULT_PERMISSION_CLASSES will only work for the views or objects that don't have permissions explicitly set. You don't necessarily need to use built-in classes here. You can use your own custom classes as well. Question: What does set permissions explicitly means? -
How to pass data from request body in unit test django
I have modified get_queryset() method that looks like this: def get_queryset(self): type_of_review = self.request.data['type_of_review'] queryset = Reviews.objects.filter(type_of_review=type_of_review).order_by('-id')[:3] return queryset It sorts my models according to the type_of_review field, orders them and retrieves 3 last. When I was trying to write a unit test to it, I ran into a problem that I cannot find a reliable or working way to pass filter argument into my get_queryset() method. I tried doing it like this: def test_list_three_review(self): self.data = [ReviewsFactory.create() for i in range(10)] response = self.client.get(self.url2, type_of_review='Team') self.assertEqual(response.status_code, status.HTTP_200_OK) But got an error: test_list_three_review - KeyError: 'type_of_review' Can somebody explain to me what am I doing wrong? Will gladly provide any additional information. Thanks anyway! -
How to easily transform a series of formatted text to SQL?
I am building a simple Question-Answer system about checking attendance of students with Django. I hope that when I input a question like 'Did student xxx attend the course in xxx Date',it can query the database and return the correct answer. How can I transform the input into SQL easily without using complex AI technology? Thanks very much. Here's part of my database: enter image description here -
Static files not loading using nginx and docker
I'm having approximately the same error as in this question, as concerning Django, all my pages are loaded correctly but not my static files. I guess it has something to do with an error in my configuration files, however even though I've been searching for quite some time, I couldn't find anything to solve my problem. Here is my Django Dockerfile : FROM python:3.10.5-alpine RUN pip install --upgrade pip RUN wget https://upload.wikimedia.org/wikipedia/commons/b/b9/First-google-logo.gif -O media/media.gif COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./src /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] nginx.conf upstream django { server django_gunicorn:8000; } server { listen 80; server_name 127.0.0.1; location / { proxy_pass http://django; } location /static/ { alias /static/; } location /media/ { alias /media/; } } nginx Dockerfile FROM nginx:1.19.0-alpine COPY ./nginx.conf /etc/nginx/conf.d/nginx.conf docker-compose.yml version: '3.7' services: django_gunicorn: volumes: - static:/static - media:/media env_file: - env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static - media:/media ports: - "80:80" depends_on: - django_gunicorn volumes: static: media: And I get errors like that : testapp-django_gunicorn-1 | testapp-django_gunicorn-1 | 9771 static files copied to '/app/static'. testapp-django_gunicorn-1 | [2022-07-21 12:27:36 +0000] [9] [INFO] Starting gunicorn 20.1.0 testapp-django_gunicorn-1 | [2022-07-21 12:27:36 +0000] … -
How to run background task with Django?
I'm looking to run heavy tasks (more than 5 minutes) in the background with django. When a heavy task is launched, django stops responding and it becomes impossible for users to navigate between pages until the task is finished. For me a solution would be to run these heavy tasks in the background or in parallel in order to allow the user to be able to navigate between the pages in the meantime. Do you know how I can do this ? -
How can I increase size of item in form?
So I have captcha form in django project and it seems kinda small. I wan't to make it bigger. Forms.py from django import forms from captcha.fields import CaptchaField class MyForm(forms.Form): captcha=CaptchaField() views.py from django.shortcuts import render from .forms import MyForm # Create your views here. def home(request): if request.method=="POST": form=MyForm(request.POST) if form.is_valid(): print("success") else: print("fail") form=MyForm() return render(request,"captcha_project/home.html",{"form":form}) home.html <!DOCTYPE html> <html> <head> </head> <body> <form method="POST" novalidate> {% csrf_token %} {{ form.captcha }} <input type="submit" value="submit"> </form> </body> </html> So, basically I just want to make captcha form bigger -
How do i add custom fields to UserManager in Django
I am trying to create a user profile, i followed through a tutorial which has registration for only username, email and password but i want to be able to add other custom fields. What i did: Models.py: class UserManager(BaseUserManager): def create_user(self, username, email, password=None,): if username is None: raise TypeError('User should have a userame') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username , email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('User should have a password') user=self.create_user(username,email,password) user.is_superuser = True user.is_staff = True user.save() return user class User(models.Model): dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE) name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=True) customerId = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) @property def energy_data(self): energydata = EnergyData.objects.filter(customerId=self.customerId).first() return energydata Serializers.py: class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length = 68, min_length=6, write_only = True) class Meta: model=User fields=['email','username','password','name','address','customerId', 'dso', 'roleId'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not len(username) >= 4: raise serializers.ValidationError('Username must be morethan 4 letters or characters') return attrs def create(self, validated_data): return … -
How to access token after signin with google dj_rest_auth
When I visit this url https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<CALLBACK_URL_YOU_SET_ON_GOOGLE>&prompt=consent&response_type=token&client_id=&scope=openid%20email%20profile it redirect to me http://127.0.0.1:8000/accounts/google/login/callback/#access_token=tokonkey&token_type=Bearer&expires_in=3599&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20openid%20https://www.googleapis.com/auth/userinfo.email&authuser=0&prompt=consent in response I got "success" But I want to get access_token that shown in url,just like { "token":tokenkey } can someone tell me how to do that? And my code look likes In urls.py from users.views import GoogleLogin,GoogleRedirect path('auth/google/', GoogleLogin.as_view(), name='google_login'), path('accounts/google/login/callback/', GoogleRedirect.as_view()) in views.y class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client class GoogleRedirect(APIView): def get(self, request): return Response("success") ''' -
Expo React native fetch requests twice
import React, { useState } from 'react'; import { Text, View, StyleSheet, Image } from 'react-native'; import Constants from 'expo-constants'; // You can import from local files import AssetExample from './components/AssetExample'; // or any pure javascript modules available in npm import { Card } from 'react-native-paper'; import * as FileSystem from 'expo-file-system'; export default function App() { let data = new FormData(); let url="https://uploadfilesserver.eugenevolkov.repl.co/upload" data.append("content",{type:'image/jpeg', uri:'https://snack-code-uploads.s3.us-west-1.amazonaws.com/~asset/201a148e3d40baa81d8ef06e316b5ca2', name:'ball.jpg'} ) function upload(){ fetch(url, { method: "post", headers: { "Content-Type": "multipart/form-data", }, body: data, }) .then(res => {res.json() // console.log('res',res) } ) .then(final => { console.log( "Success")} ) // .catch(err => { // console.error("error uploading images: ", err); // }); } upload() return ( Image to upload <Image source={require('./ball_1.jpg')}/> ); } i am new to react native. The fecth always results in two uploads (two POST reqests). There is no OPTIONS request. In the backend (Django) upload folder there are always 2 'ball.jpg' files. The same issue happens after building app. -
Django pre-save function not removing group and users permissions from user model in django signal
I am trying to write a signal function as below: def on_user_deactivation(sender, instance, **kwargs): if not instance.is_active: instance.team_set.clear() instance.groups.clear() instance.user_permissions.clear() ``` -
Can I use Django to make non-web python apps as a data scientist?
I'm a data scientist, and I make apps using python. Where I make a lot of connections with databases, build and deploy my code on the cloud and I use models training and visualization. My question is: Is Django useful for making non-web apps? if not are they any other frameworks? (similar to spring-boot for java) Best regards -
UnicodeDecodeError - Django Upload file
I'm using Django Rest Framework, and with a simple form on the frontend I upload some data, and attachments to a model in Django. I store the files at AWS S3, and I'm using Django S3 Storage. When I upload a file I get an UnicodeDecodeError as follows. (See bottom for trace) My file model class JourAttachment(models.Model): jourreport = models.ForeignKey(JourReport,related_name="jourattachments", on_delete=models.CASCADE) file = models.FileField(null=False) View class JourReportListView(APIView): serializer_class = JourReportListSerializer permission_classes = (IsAuthenticated, ) parser_classes = (MultiPartParser,) def post(self,request,*args, **kwargs): user_making_request = request.user if not user_is_admin(user_making_request): return UserNotAdminResponse() attachments = request.FILES.getlist('attachment', None) serializer = JourReportCreateUpdateSerializer(data=request.data,partial=True,context={'attachments': attachments}) valid = serializer.is_valid(raise_exception=True) if valid: report = serializer.save() status_code = status.HTTP_201_CREATED #send_mail_with_jourreport(report) return SuccessfulResponse(data=request.data, message="Jour report successfully registered!" ,status_code=status_code) return ErrorResponse() Serializer class JourReportCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = JourReport fields = ('apartment_number', 'address', 'tenant_name','tenant_phone', 'debit_tenant','worker','total_hours', 'additional_workers','defect_description','actions_made','actions_to_be_made') def create(self, validated_data): users = [] attachments = self.context['attachments'] if "additional_workers" in validated_data: users = [w.id for w in validated_data["additional_workers"]] del validated_data["additional_workers"] report = JourReport.objects.create(**validated_data) for a in attachments: JourAttachment.objects.create(file=a,jourreport=report) # Add attachments to instance if(len(users) > 0): report.additional_workers.add(*users) return report The model is correctly added and all files are stored, but either way I get an 500 response with UnicodeDecodeError Trace Traceback (most recent call last): File … -
Django sterilizer update method validated_data convertion
I am trying to update an instance of my model via the serializer update method. This modal have many to many connection to another model. my models: class GPX(models.Model): name = models.CharField(max_length=255) created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now=True) trail_types = models.ManyToManyField(TrailTypes, blank=True) class TrailTypes(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name I want to get has input a list contain trail_types names instead of their ids. The problem is that Django converts the data objects of trail_types and then pass it as validate_data to the update method under the seralizer. How can I do the conversion before? or is there another way to specify to Django to create trail_type objects by its name. @transaction.atomic def update(self, instance, validated_data): gpx: GPX = super().update(instance, validated_data) return gpx thanks in advanced -
How can I customize drf-yasg endpoints's example response?
on my Django project, I'm using DRF and drf-yasg. At some endpoint, the example response body shows the incorrect example. like the following example: But some of them don't show the correct example response body. This endpoint actually returns access_token and refresh_token, doesn't return the email and password. It's wrong information for the front-end devs. Is there any way to change this? -
Django registration & authentication via def
Pls help me with my problem. I need register user with some additional fields (phone, adress). Form without username field. Auth throut email. Prefer using def. I add model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField('phone ', null=True, blank=True) country = models.CharField('country ', max_length=100, null=True, blank=True) city = models.CharField('city ', max_length=100, null=True, blank=True) adress = models.CharField('adress', max_length=300, null=True, blank=True) zip_code = models.IntegerField('zip_code', null=True, blank=True) birth_day = models.DateField('birth_day', null=True, blank=True) avatar = models.ImageField('avatar', upload_to='avatar', null=True, blank=True) agreement = models.BooleanField('agreement', default=True) comment = models.TextField('comment', max_length=3000, null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() def admin_display(self): return self.user.last_name + ' ' + self.user.first_name And add two forms: class ProfileForm(forms.ModelForm): class Meta: model = Profile exclude = ('comment', 'register_date', 'avatar', 'password', ) widgets = { 'phone': forms.NumberInput(attrs={'placeholder': '9XXXXXXXXX', 'class': 'form-control', 'id': 'phone'}), 'country': forms.TextInput(attrs={'placeholder': 'Россия', 'class': 'form-control', 'id': 'country'}), 'city': forms.TextInput(attrs={'placeholder': 'Москва', 'class': 'form-control', 'id': 'city'}), 'adress': forms.TextInput(attrs={'placeholder': 'Ленина 25', 'class': 'form-control', 'id': 'adress'}), 'zip_code': forms.TextInput(attrs={'placeholder': '101000', 'class': 'form-control', 'id': 'zip_code'}), 'agreement': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexSwitchCheckChecked'}), 'birth_day': DateInput(attrs={'class': 'form-control', 'id': 'birth_day'}), } class UserForm(forms.ModelForm): class Meta: model = User fields = '__all__' widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'Иван', 'class': 'form-control', 'id': … -
Django model validation in clean or in separate validators?
I am pretty new to Django and I was wondering what is the best method to validate your models in Django? Are there any advantages to using clean vs adding validators to your models? By validators I mean when you do declare the field, populating the validator=[] list. I find the models to be easier to read with the validators in another package, and declared in the field list. Also, I try to validate the data before in services, before initializing the models. What do you think / prefer? Thanks a lot. -
Can't render django template to pdf: UnsupportedMediaPathException
I have a Django template rendered by a DetailView, I want to turn that template to PDF using a different view and this library: django-easy-pdf My view: class ServizioPDFView(PDFTemplateView): template_name = 'hub/anteprima.html' base_url = 'file://' + settings.MEDIA_ROOT download_filename = 'anteprima.pdf' def get_context_data(self, **kwargs): ctx = super(ServizioPDFView, self).get_context_data( pagesize='A4', title='Anteprima Offerta', **kwargs ) r = self.request.user.referente ctx['referente'] = r ctx['hub'] = r.hub ctx['servizio'] = Servizio.objects.get(pk=self.kwargs.get('pk')) return ctx My Urls path('servizi_offerti-pdf/<int:pk>', ServizioPDFView.as_view(), name='servizio-detail-pdf'), I get the error: UnsupportedMediaPathException at /servizi_offerti-pdf/7 media urls must start with media_root/ or /static/ I followed the usage tutorial of the library and tinkered with static and media root in my settings.py but without success. Any help is greatly appreciated. -
module 'django.http.request' has no attribute 'session'
I created a class to generate a token when the user logs in. I would like to create a session when the user logs in. Here is the error I am getting: "module 'django.http.request' has no attribute 'session'" Thank you for helping me. Voici l'extrait de mon code. class TokenObtainLifetimeSerializer(TokenObtainPairSerializer): permission_classes = (permissions.AllowAny,) authentication_class = [CsrfExemptSessionAuthentication] def validate(self, attrs): loginInfo = [] # loginInfo[0] -> identifiant ||| loginInfo[1] -> password data = super().validate(attrs) for values in attrs.values(): loginInfo.append(values) if data : user = auth.authenticate(request, identifiant=loginInfo[0], password=loginInfo[1]) auth.login(request, user) refresh = self.get_token(self.user) data['lifetime'] = int(refresh.access_token.lifetime.total_seconds()) return data class CustomTokenObtainPairView(TokenViewBase): serializer_class = TokenObtainLifetimeSerializer -
Duration matching query does not exist
Traceback (most recent call last): File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/ahmed/SavannahX/app/views.py", line 1352, in yearly_subscription_plans duration = Duration.objects.get(name="yearly") File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/``` django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ahmed/SavannahX/venv/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /yearly/subscriptions/ Exception Value: Duration matching query does not exist. -
Dynamic data not getting extended
I making a shopping website and I am using extend tag of html to extend a table into another page. Below is the table in shoppingpage.html enter image description here When I click on any of the categories(blue in color in the image above), only 'Our Products' comes and without the remaining table enter image description here Below are the codes that I have tried shoppingpage.html <body> <h1>Hello, welcome to shopping page!</h1> <ul> <a class="lynessa-menu-item-title" title="Our Products" href="/allproducts">Our Products</a> <div class="submenu megamenu megamenu-shop"> <div class="row"> {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="{% url 'polls:category' result.id %}" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in result.subcategories_set.all %} <ul class="listitem-list"> <li> <a href="{% url 'polls:subcategory' ans.id %}" target="_self">{{ans.sub_categories_name}}</a> </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} </div> </div> </ul> {% block content %}{% endblock %} </body> category.html {% extends "polls/shoppingpage.html" %} <h1>Hello,to categorybase world!</h1> {% block content %} <ul class="row products columns-3" id="appendproducts"> {% for product in products %} <li class="product-item wow fadeInUp product-item rows-space-30 col-bg-4 col-xl-4 col-lg-6 col-md-6 col-sm-6 col-ts-6 style-01 post-24 product type-product status-publish has-post-thumbnail product_cat-chair product_cat-table product_cat-new-arrivals product_tag-light product_tag-hat product_tag-sock first instock featured shipping-taxable purchasable product-type-variable has-default-attributes" data-wow-duration="1s" …