Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mock googleapiclient in a Django test environment
I'm trying to mock googleapiclient.discovery in a django unittest, I looked at how at this post which shows how to mock googleapiclient.discovery in general, so I tried this: ... @mock.patch("myapp.views.googleapiclient.discovery") def test_get_instances(self, mock_discovery): mock_discovery.build.return_value.service.return_value.instances.return_value.aggregatedList.return_value = {# some mock values} ... This gave a "Module not found error", stating that "myapp.views" is not a package The views.py question is in the standard location for Django apps: mysite/myapp/views.py views.py: ... from googleapiclient import discovery def get_instances(proj_id, servicekey) service = discovery.build('compute','v1', credentials=generate_credentials(servicekey)) request = service.instances().aggregatedList(project=project_id) ... I'm new to mocking so any advice is warmly welcome -
Unable to find root cause of warning message indicated as [django.request:230]
The log file contains warnings about "Unauthorized" access to certain API URLs. The warning's indicator says "[django.request:230]", and I suppose it means the trigger is line 230 of a source code file related to django.request. However, I'm unfamiliar with Django and PyCharm IDE, so I couldn't find out exactly which file. I hope to find out the root cause of this warning message and address it. Any hints will be highly appreciated. Log events: [03/Feb/2021 09:54:07] WARNING [django.request:230] Unauthorized: /api/rest-auth/user/ [03/Feb/2021 09:54:07] WARNING [django.request:230] Unauthorized: /api/products/meta/debt/ [03/Feb/2021 09:54:07] WARNING [django.request:230] Unauthorized: /api/products/meta/reg/ -
Django: object has no attribute 'update'
I want to update first one record of the database. This result can be two or more results. This works. TelegramAppUserConfig.objects.filter(user=user).update(json="hoge") This should result just one result. But this doesn't work. Django: object has no attribute 'update' TelegramAppUserConfig.objects.filter(user=user).first().update(json="hoge") TelegramAppUserConfig.objects.filter(user=user)[0].update(json="hoge") How can I code for that? Thanks. -
Django rest framework router urls is not working
So, I have such viewset. class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() permission_classes = (IsAuthenticated, ) @action(detail=True, methods=['PUT']) def set_description(self, request, pk=None): profile = self.get_object() serializer = DescriptionSerializer(data=request.data) if serializer.is_valid(): profile.description = request.data['description'] profile.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action( detail=True, methods=['post'], serializer_class=ImageSerializer ) def add_image(self, request, pk=None): instance = self.get_object() serializer = self.get_serializer(instance, data=self.request.data) serializer.is_valid(raise_exception=True) image = serializer.save(profile=request.user.profile) image_id = image.id return Response(serializer.data, {'image_id': image_id}) @action( detail=True, methods=['delete'], serializer_class=ImageSerializer ) def delete_image(self, request, pk): instance = self.get_object() instance.delete() return JsonResponse(status=status.HTTP_200_OK) My urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter from . import views from . import viewsets app_name = 'profile_' router = DefaultRouter() router.register('', viewsets.ProfileViewSet) urlpatterns = [ path('', views.ProfileView.as_view(), name='profile'), ] urlpatterns += router.urls And finally there is a couple of available urls (showed by python3 manange show_urls) /profile/<pk>/add_image/ profile_.viewsets.ProfileViewSet profile_:profile-add-image /profile/<pk>/add_image\.<format>/ profile_.viewsets.ProfileViewSet profile_:profile-add-image /profile/<pk>/delete_image/ profile_.viewsets.ProfileViewSet profile_:profile-delete-image /profile/<pk>/delete_image\.<format>/ profile_.viewsets.ProfileViewSet profile_:profile-delete-image /profile/<pk>/set_description/ profile_.viewsets.ProfileViewSet profile_:profile-set-description /profile/<pk>/set_description\.<format>/ profile_.viewsets.ProfileViewSet profile_:profile-set-description I not copied all of them but you can see there is all paths I need provided by default router. So, I trying to change profile's description from JS this.update(`http://127.0.0.1:8000/profile/${this.user_id}/set_description/`, data, 'PUT') Update is a function which getting url, some king of data and a request method (And it works ok, because I … -
How can I optimise requests/second under peak load for Django, UWSGI and Kubernetes
We have an application that experiences some pretty short, sharp spikes - generally about 15-20mins long with a peak of 150-250 requests/second, but roughly an average of 50-100 requests/second over that time. p50 response times around 70ms (whereas p90 is around 450ms) The application is generally just serving models from a database/memcached cluster, but also sometimes makes requests to 3rd party APIs etc (tracking/Stripe etc). This is a Django application running with uwsgi, running on Kubernetes. I'll spare you the full uwsgi/kube settings, but the TLDR: # uwsgi master = true listen = 128 # Limited by Kubernetes workers = 2 # Limited by CPU cores (2) threads = 1 # Of course much more detail here that I can load test...but will leave it there to keep the question simple # kube Pods: 5-7 (horizontal autoscaling) If we assume 150ms average response time, I'd roughly calculate a total capacity of 93requests/second - somewhat short of our peak. In our logs we often get uWSGI listen queue of socket ... full logs, which makes sense. My question is...what are our options here to handle this spike? Limitations: It seems the 128 listen queue is determined by the kernal, and the … -
Optimize code of a function for a search filter in django with variable numbers of keywords - too much code, i'm a beginner
Hello great community, i'm learning django/python development, i'm training myself with development of a web app for asset inventory. i've made a search filter, to give result of (for example) assets belonging to a specific user, or belonging to a specific department, or belonging to a specific brand, model or category (computers, desks, ecc..) now (after a lot) i've done with multiple keyword search (for example) if somebody type in the search box the department and the category and obtain the relative results (for example all desk in a specific department, or all computer of a specific model in a specific department). i've made it in a "if" check form that split the keyword in single words, count it and apply progressive filtering on the results of the previous keys in sequence. but i'm not satisfact of my code, i think it's too much "hardcoded" and instead of creating an IF condition for each number of keyword (from 1 to 3) i wish like to code something that is not so dependent in the number of keyword, but is free. Here's the code of the view, i hope someone can give me the right direction. def SearchResults(request): query = request.GET.get('q') … -
How to display pdf from an HttpResponse in Django after jquery post request?
I am using xhtml2pdf to introduce pdf report downloads on my platform. The intention is to send a dictionary with some data via ajax to the view so that it triggers the render_to_pdf function in utils.py. The problem is that, although everything seems to be working, since the request works and the data is sent, the pdf is not generated. Any idea about this? Thank you in advance! views.py def ViewPDF(request, *args, **kwargs): if request.is_ajax(): print('ajax') else: print('NOT ajax') s_id = kwargs['pk'] customer = request.user search = searches_history.objects.get(id=s_id) product_id = search.product b = Products.objects.get(id=5) if product_id== b: print(b) search1 = ofac_lists.objects.filter(name__contains=search) context = {'id': customer, 'search_id' : s_id ,'nombre_buscado': search, 'results' : search1, 'date': search.date_created } pdf = render_to_pdf('core/reports/free_search.html', context) return HttpResponse(pdf, content_type='application/force-download') else: context = {'id': customer, 'nombre_buscado': search, 'date': search.date_created } pdf = render_to_pdf('core/reports/free_search.html', context) return HttpResponse(pdf, content_type='application/pdf') utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: # Force pdf download response = HttpResponse(result.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=" .pdf"' return response # view pdf in browser # return http.HttpResponse(result.getvalue(), mimetype='application/pdf', content_type='application/force-download') return HttpResponse('We had some errors %s ' % cgi.escape(html)) main.js var url = '/pdf/'+query['s_pk'] $.ajax({ … -
How do i work as a programmer whiteout educational related degree?
I have faced a important question and have not found the complete right answer for it. Actually, I have been graduated from master course of medical engineering, but I'm working as a web developer in my country. Because of this incompatibility of my studying working field, I had to pass 900 hours programming training to be able to receive official Professional technical degree of programming which can be accepted by ILO organization. I'm in the process of immigration to the Germany and want to know weather i would have less income than the workers who have educational computer-related degree. should i maybe one day participate in a computer-related course not to be rejected by big companies ? -
jquery not appending more than 20 times in ajax with django
i am working on blog project, when i click submit post would be created and ajax will live reload the page. its working as i expected but as soon as my post reaches 20 it would stop appending to that perticular div, but the model object is being created correctly,when i go to admin there would 25,35 or 50 model object but only first 20 would be appended? ajax $(document).ready(function(){ // $("button").click(function() { // $("html, body").animate({ // scrollTop: $( // 'html, body').get(0).scrollHeight // }, 2000); // }); $(document).on('submit','#post_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url:"{% url 'create' %}", data:{ message: $('#message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ } }); }); setInterval(function() { $.ajax({ type:'GET', url:"{% url 'comments' %}", success:function(response){ $('.display').empty(); for(var key in response.comments){ if (response.comments[key].name != '{{request.user}}'){ var temp = "<div class='message_area'><p id = 'author'>"+response.comments[key].name+"</p><p id='messagetext'>"+response.comments[key].message+"</p></div><br>" $(".display").append(temp); } if (response.comments[key].name == '{{request.user}}'){ var user_temp = "<div class='message_area_owner'><p id='messagetext_owner'>"+response.comments[key].message+"</p></div><br><br><br>" $(".display").append(user_temp); } } }, error:function(response){ console.log("no data found") } }); }, 500); }); html {% if request.user.is_authenticated %} <div class="display"> </div> <div class="input"> <form id="post_form"> {% csrf_token %} <input type="text" id="message" name = 'message' autocomplete="off" onfocus="this.value=''"> <button type="submit" id="submit" onclick="scroll()">SENT</button> </form> </div> {%else%} <a class="btn btn-danger" href="{% url 'login' %}" style="text-align: center;">login</a> <a class="btn btn-danger" href="{% … -
unexpected EOF while parsing Django form function
I'm following this tutorial , after adding this function in views.py to render a paypal form i get this error "unexpected EOF while parsing" def subscription(request): if request.method == 'POST': f = SubscriptionForm(request.POST) if f.is_valid(): request.session['subscription_plan'] = request.POST.get('plans') return redirect('process_subscription') else: f = SubscriptionForm() return render(request, 'ecommerce_app/subscription_form.html', locals() -
Django Template rendering from for loop
I have a simple form with a field names as company_name, location, country and few more which I am rendering from views.py as {'form':form}. The usual way to call the form on the template is {% for field in form %} which is rendering the fields in the order of field attribute in the form.py file. Another way to add special classes and styles to each field I am calling every field with name as {{ form.company_name }}. I have a another for loop which only contains the names of the form fields {% for element in fieldnames %}. I want to render the form field as per the order in the fieldnames. I tried allot with the below example but not working. Please suggest... {% for element in fieldnames %} {{ form.element }} {% endfor %} Why cant we render like above using for loop but if I replace element name with the field name like {{ form.company_name }} its working -
DRF Two factor authentication based on user's device on new device only
I have Django backend server with JWT based authentication, and I'm trying to implement two factor authentication for better protection (with user's email or phone as the 2nd step). I saw that there are various of packages to handle Two factor authentication. but there are no information about getting user's device info or the ability of using 2FA with NEW devices only. What is the best way to solve this issue? can I use data from the request? should I ask additional data from the FRONT? Thanks! -
How to redirect ?page=1 to / in Django paginations?
I am a little confused why my view code does not work. I need to redirect whenever /?page=1 to just / My view: blogs = models.BlogPost.objects.filter(is_active = True).order_by('-pub_date') paginator = Paginator(blogs, 12) page_number = request.GET.get('page') #THIS IS THE PART THAT DOES NOT WORK# if page_number == 1: redirect('blog:blog', permanent=True) try: page_obj = paginator.page(page_number) except PageNotAnInteger: paginator.get_page(1) except EmptyPage: raise Http404('<h1>Page not found</h1>') If I enter domain.com/?page=1 it should redirect to domain.com/ But it stays domain.com/?page=1 I don't see what I am missing, can someone help me please? -
Django unsupported operand types
I'm getting an error TypeError: unsupported operand type(s) for /: 'str' and 'module' [09/Feb/2021 16:26:28] "GET / HTTP/1.1" 500 61800 while connecting client to the server. When I'm not connected all runs fine. Problem lies somewhere in my file views.py where i get error source code looks like this: I've tried multiple of possibilities of concatenating two parts of the HttpResponse, always resulted in either problem with str and module or str and function. I know it just looks like a poor laziness but I swear I was trying to resolve the issue for the last 40 minutes and got a strong headache from that. So be kind, please. Thanks for any help, promise I'll respond to any feedback after I take a Aspirin. -
How to filter draft contents from django website?
I have two options for my articles in my django website: "draft" and "published" I wrote sth that helps me show only the articles that are on "published" status in admin page. But the code doesn't work. when I click on the specified category for each article, even the draft ones show up. How can I fix it? ################# #models.py from django.db import models from django.utils import timezone # my managers class ArticleManager(models.Manager): def published(self): return self.filter(status='Published') # Create your models here. class Category(models.Model): title = models.CharField(max_length=300, verbose_name="Category Topic") slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address") status = models.BooleanField(default=True, verbose_name="Do you want to show?") position = models.IntegerField(verbose_name="position") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['position'] def __str__(self): return self.title class Article(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) title = models.CharField(max_length=300) slug = models.SlugField(max_length=100, unique=True) category = models.ManyToManyField(Category, verbose_name="Category", related_name="articles") description = models.TextField() thumbnail = models.ImageField(upload_to="images") publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES) class Meta: ordering = ['-publish'] def __str__(self): return self.title def category_published(self): return self.category.filter(status=True) objects = ArticleManager() ############ #Views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from .models import Article, Category # Create your views … -
Generate Random String for Model Field in Django
I am using DRF and have a couple models where I want to generate unique numbers separate from ID's. For example, one model would have a number like PRJ023400 and another would be TSK2949392. I created a utility function to generate random numbers and as the field and attempted to use this function as the default. number = models.CharField(max_length = 10, blank=True, editable=False, default='PRJ'+create_new_ref_number()) The problem I am facing is that this only generates a new string when running a migration. What would be the best approach to make this work? Cheers! -
transfer to a different url from xmlhttprequest post call
I am having a xmlhttprequest method like this which gets data authenticated from google sign-in successfully and after that I need to post the data to the login view. Using python and django on the server side. function onSignIn(googleUser) { // Useful data for your client-side scripts: var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); var id_token = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); alert("Token*"+id_token); //this gets executed var xhr = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; xhr.open('POST', '/login'); xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { console.log('Signed in as: ' + xhr.responseText); alert("*******Token*"+id_token) try { xhr.send('idtoken=' + id_token); } catch (e) { alert("*"+e.toString) console.log('send() error: ' + e.toString()); return false; } views.py in the views i have defined a login method() def login(request): if request.method=='POST': #process the request and send the data to another page with some additonal parameters role=user_role email=user_email fullname=user_name return render(request, 'ba/dashboard.html', {'role':role,'email':email,'fullname':fullname}) After the post request is completed the page does not get transferred to the dashboard.html … -
How to generate and return access and refresh tokens on user registeration with DRF simpleJWT?
I have declared 2 methods for generating access and refresh tokens on my user's model like this: # models.py from rest_framework_simplejwt.tokens import RefreshToken class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(...) date_joined = models.DateTimeField(...) is_active = models.BooleanField(...) is_staff = models.BooleanField(...) ... ... def refresh(self): return str(RefreshToken.for_user(self)) def access(self): return str(RefreshToken.for_user(self).access_token) Now, in my RegistrationSerializer, I'm trying to make use of these methods with SerializerMethodField like this: (trying to get only the access token below to summarize) class RegistrationSerializer(serializers.ModelSerializer): confirm_password = serializers.CharField(style={'input_type': 'password'}, write_only=True) access = serializers.SerializerMethodField('get_access_token') def get_access_token(self, account): return account.access class Meta: model = Account fields = ['email', 'password', 'confirm_password', 'access'] extra_kwargs = {'password': {'write_only': True}} And I encounter AttributeError: 'collections.OrderedDict' object has no attribute 'access' error. What am I doing wrong? -
positional argument follows keyword argument issue in Django ORM query
user=kwargs['user'] Emp.objects.filter(country="England",Q(euser=user)|Q(muser=user),dep="sample").order-by('-date') Throwing the error positional argument follows keyword argument issue in Q(euser=user)|Q(muser=user) -
How to create subscription service using Django
I am working on a Django application. I need to include subscription service in the application. I am using the fields is_subscribed, subscription_start and subscription_end in the user profile models. I am using Razorpay for the payment integration. After successful payment I am updating the subscription status as follows: UserProfile.objects.filter(user=request.user).update(is_subscribed=True,subscription_start=datetime.datetime.now(),subscription_end=datetime.datetime.now()+datetime.timedelta(days)) How to update the UserProfile automatically as soon the subscription_end is less than the current time. I want the model to be updated as is_subscribed as False as soon as the time is over. As of now, whenever a user visits any url, I am checking whether the user's subscription is valid. If not , then I am updating the model in this way user = UserProfile.objects.filter(user=request.user).values() use1 = UserProfile.objects.filter(user=request.user,subscription_end__gte=datetime.datetime.now()).values() if not use1[0]['is_admin']: UserProfile.objects.filter(user=request.user).update(is_subscribed=False,joined=[]) . what is the correct way to update as soon as the subscription ends. -
How would you run a Postgres Server in production?
I am currently using Django and Postgres with Docker. When trying to go into production, would I keep my current setup, with a local Postgres database server running alongside my django? -
Convert queryset to dictionary with native data types?
I have a Stocks model and I'm using values as such: Stock.objects.values("ticker", "stock", "exchange__exchange_code", "earnings_yield", "roic") The earnings_yield and roic values are stored in my db as decimal, and Django returns their type as such: {'ticker': 'AAPL', 'stock': 'Apple', 'exchange__exchange_code': 'NASDAQ', 'earnings_yield': Decimal('0.0000'), 'roic': Decimal('0.0000')} How can I convert the 'roic': Decimal('0.0000') and get back 'roic': 0.0000 instead? -
Django Docker Image Recreation
As I have created DOCKERFILE file and docker-compose file. DOCKERFILE FROM python:3.7-slim-buster RUN apt-get update && apt-get install -y \ libcurl4-openssl-dev \ libssl-dev COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /code EXPOSE 8080 WORKDIR /app CMD ["python /code/manage.py runserver"] docker-compose.yml version: '3' services: postgres: image: postgres:12 volumes: - dbdata:/var/lib/postgresql/data ports: - "5432:5432" django_app: build: . tty: true ports: - "8080:8080" volumes: - .:/app links: - postgres depends_on: - postgres volumes: dbdata: Once I am making any changes in django requirements file then all the time I have to delete all the images from my system then I have to recreate the whole images by downloading and installing ubuntu images rather be only installing the requirements. Currently I am using this command to run the docker docker-compose -f docker-compose.yml up. Please help me to understand where I am doing wrong in the process. -
Django Channels - Unable To Message Channel Directly When A Member Of A Group
I have a requirement within my application to be able to message both individual channels and groups of channels depending on the situation. I have come across the issue however, that if I add my channels to a group, I am no longer able to message them directly. Here are some examples: (Unable to send to a single channel): class NonWorkingExampleConsumer(WebsocketConsumer): def connect(self): self.group_name = 'group' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def receive(self, text_data): async_to_sync(self.channel_layer.send)( self.channel_name, { 'type' : 'test', 'message' : 'Hello World!' } ) def test(self, event): self.send(text_data=json.dumps({ 'message' : event['message'] })) (Able to send to a single channel): class WorkingExampleConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): async_to_sync(self.channel_layer.send)( self.channel_name, { 'type' : 'test', 'message' : 'Hello World!' } ) def test(self, event): self.send(text_data=json.dumps({ 'message' : event['message'] })) So, My question is: Is this a bug or am I simply doing something wrong? I was considering opening a ticket on Django Channels GitHub, but it suggested checking on StackOverflow first to make sure it was definitely a bug and not user error (which is a real possibility!) I am using Django version 3.1 ,Django Channels version 3.0.2 and … -
how to extend User Model in using OnetoOneField in django Rest_framework
i want to create an api to extend the django userModel thereby allowing users to create a profile after signup but i'm getting an django.db.utils.IntegrityError: NOT NULL constraint failed: schProfile_profile.user_id error below are my codes ###models.py class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=255, unique=True, db_index=True) password = models.CharField(max_length=100) created = models.DateField(auto_now=True) timestamp = models.DateTimeField(auto_now=True) role = models.CharField(max_length=5) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomManager() class Profile(models.Model): user = models.OneToOneField(CustomUser,related_name='profile', on_delete=models.CASCADE) school_name = models.CharField(max_length=255) address = models.TextField() badge = models.ImageField(upload_to='assets/badge', blank=True, null=True) gender = models.CharField(max_length=20, choices=Gender) @receiver(post_save, sender=CustomUser) def create_school_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() ##apiView class CreateProfileView(generics.CreateAPIView): parser_classes = (MultiPartParser,) serializer_class = schoolProfileSerializer queryset = Profile.objects.all() ##serializer class SignUpSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=128, min_length=8, write_only=True, ) profile = schoolProfileSerializer(required=True) class Meta: model = CustomUser fields = ('email', 'username', 'password', 'profile') def create(self, request, validated_data): user = CustomUser.objects.create( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'] ) school_profile = validated_data.pop('profile') profile = Profile.objects.get(user=request.user) return user class schoolProfileSerializer(serializers.ModelSerializer): parser_classes = (MultiPartParser, FormParser, ) id = serializers.IntegerField(source='pk', read_only=True) email = serializers.CharField(source='user.email', read_only=True) username = serializers.CharField(source='user.username', read_only=True) badge = Base64Imagefield(max_length=None, use_url=True) class Meta: model = Profile fields = ( 'email', 'id', 'username', 'school_name', 'address', 'badge', 'gender', 'motto') my aim is to have …