Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to use Django flash message in thread?
I have a view that triggers a long execution time function, at the end of this function I need to notify the user via flash message of the execution result. The function is in a thread. This is my code... from threading import Thread from django.contrib import messages def long_time_view(request, pk): def thread_func(): #stuff if success: messages.success( request, "Hurrah.", ) else: messages.error( request, "Upss.", ) messages.info(request, "Started Work.") thread = Thread(target=thread_func) thread.start() return redirect(request.GET.get("return_to", "/")) The Problem The message that notifies the user that the job has started is displayed but the results are not, even after the page is reloaded. So my question is how to show the results to the user from the thread. -
Django methodSerializer doesnt return absolute image url
Serializer.py class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ('id', 'post', 'post_img') class PostSerializer(serializers.ModelSerializer): postimg_set = serializers.SerializerMethodField('get_postimg_set') editor = UserSerializer() class Meta: model = Post fields = ('id', 'title', 'content', 'editor', 'postimg_set', 'created_at') def get_postimg_set(self, obj): a = PostImage.objects.filter(post = obj.id) print(a[0].post_img) return PostImageSerializer(a, many=True).data models.py from django.db import models import os, uuid, datetime from apps.account.models import * from django.utils import timezone def img_upload(instance, filename): ext = filename.split('.')[-1] now = datetime.datetime.now() path = "media/static/post/{}".format(instance.post.id) format = uuid.uuid4().hex + "_" + filename return os.path.join(path, format) class Post(models.Model): title = models.CharField('제목', null=False, blank=False, max_length=40) content = models.TextField('내용', null=False, blank=False) editor = models.ForeignKey(User, default = 1, null=False, blank=False, verbose_name="작성자", on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.localtime()) class Meta: verbose_name = '게시글' verbose_name_plural = '게시글' def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) post_img = models.ImageField(upload_to=img_upload) class Meta: verbose_name = "게시글 이미지" verbose_name_plural = "게시글 이미지" def __str__(self): return str(self.post.title) + "이미지" Guess postimg_set = serializers.SerializerMethodField('get_postimg_set') is not return absolute URL for the images. When I use UserSerializer(), it returned absolute image url of User's profile image. Looking for help. Thank you -
Reverse for 'user_logout' with no arguments not found
On localhost it is working but when I apply this on website.. it showing me this error.. Can someone help me to find this error. 1.Base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta name="google-site-verification" content="BsNTKCunl4MclRtIE86x1ldHNv2umlZuzPmJV_B-tCc" /> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/firstpage.css' %}"> <title>My Website</title> </head> <body> <!-- Header --> <section id="header"> <div class="header container"> <div class="nav-bar"> <div class="brand" > <a href="#hero" id = "main"><img src = "{% static 'css/lasso4.png' %}" class= "logo"></a> <a href="#hero"><h1><span>C</span>are for <span>A</span>LL</h1></a> </div> <div class="nav-list"> <div class="hamburger"><div class="bar"></div></div> <ul> <li><a href="#hero" data-after="Home">Home</a></li> <li><a href="#services" data-after="Service">Services</a></li> <li><a href="#projects" data-after="Blogs">Blogs</a></li> <li><a href="#about" data-after="About">About</a></li> <li><a href="#contact" data-after="Contact">Contact</a></li> {% if user.is_authenticated %} <li><a href="{% url 'careforallapp:user_logout' %}" data-after="Logout">Logout</a></li> {% else %} <li><a href="{% url 'careforallapp:user_login' %}" data-after="login">Login</a></li> {% endif %} </ul> </div> </div> </div> </section> <!-- End Header --> <!-- Hero Section --> <section id="hero"> <div class="hero container"> <div> <h1>Happy <span></span></h1> <h1>Republic Day, <span></span></h1> <h1>INDIA<span><img src = "{% static 'css/ind.jpg' %}"></span></h1> <p align = "justify">"Every indian should now forget that he is a Rajput, a Sikh or a Jat. He must remember that he is an Indian." - Sir, Sardar Patel<span></span></p> </div> </div> </section> <!-- End Hero Section --> <!-- Service … -
upload multiple files asynchronously before submit form Django?
Intro: I have Django web app where users are allowed to create posts. Each post has multiple images that are associated with that post. What I want to do: I want such that when the user uploads each image to a form. I want to use Filepond javascript library for remove image, add more image and previews of selected images. The issue: The code below is getting error NOT NULL constraint failed: core_filemodel.post_id I want to add multiple images to a django form asynchronously before form submit.I have the Javascript code for uploading of the images on the client side and asynchronously adds it to my server. All I need to do is give it a endpoint, which is a simple url I have a rough idea of how I plan to achieve this. How can i pass NewsCreateViews instance = post_image_create? I would be grateful for any help. MODELS class FileModel(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE) file = models.FileField(upload_to='stories', blank=True, null=True) VIEWS def post_image_create(request): if(request.method == "POST"): for f in request.FILES.getlist('file'): FileModel.objects.create(file=f) class NewsCreateView(CreateView): form_class = FileForm template_name = 'news/news_create.html' success_url = '/' def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post_image_create(request=self.request, post=post) # This function is defined above … -
How to render redirect a URL with an int: parameter in Django views.py?
I'm trying to make a form in Django that displays errors when the form isn't filled out properly under a specific account. I want it to reroute to the same page as the form, and the url has to have an int: parameter. For my urls.py, I have 'edit/int:user_id>, views.edit. Where I'm struggling is how do I pass the render redirect in the views.py? I've tried render redirect('/edit/int:user_id'), ('/edit/int:user.id'), ('/edit/{user.id}'), etc, and NOTHING is working. Every time I just get 'path not found.' How do I write a redirect in views.py with an int parameter, based on what I have for my urlpatterns? -
using method on a manager pylint thinks class is an undefined variable
I have a class called Passengers in my models.py class Passenger(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) flights = models.ManyToManyField(Flight, blank=True, related_name="passengers") def __str__(self): return f"{self.first} {self.last}" In views.py I'm defining this view where I am finding the passenger id from the submitted form data and at the same time finding the passenger based on the id using .objects.get. def book(request, flight_id): if request.method == "POST": flight = Flight.objects.get(pk=flight_id) passenger = Passenger.objects.get(pk=int(request.POST["passenger"])) passenger.flights.add(flight) return HttpResponseRedirect(reverse("flight", args=(flight.id))) The problem is that Passenger is not recognised as a class but rather as an undefined variable. enter image description here -
How to embed this python code into a simple HTML website?
I am working on a website which will take input and do some calculations and give output. I need to write this calculation code in python. But since this will be used by other users, I want it to be in form of a website so I can deploy it. Just like we can embed JavaScript code into a html page, can we do the same thing with python?? the code will be very simple, around 5-10 calculations. I know there are ways to do this with Flask or Django, but I was wondering if there was an easier way by just embedding python code in the HTML file. Would it be better if I just create a Tkinter GUI web-app & turn it into an executable file? below is the type of code I'll use on the website. Of course, the real code will be a little more complex and longer. But basically ill be asking for input and do calculations with it & then print the output Example Python code Length = input(int("Insert the Length")) Width = input(int("Insert the Width")) Print("area of this rectangle is: "+ Length * Width) -
Django How to Add Base Form Template Context Processer
In my navbar I have a newsletter button that pops up a modal. In the modal there is a form that I can use to get the email and do some form manipulation. Since this modal is in the base template, the form must be available for all urls. I have added 'blog.context_processors.email_form' in the settings, and a context_processer.py file with the below info: from .forms import EmailForm def email_form(request): return { 'email_form': EmailForm() } In my forms.py I have: from django import forms from .models import Email class EmailForm(forms.ModelForm): email = forms.EmailField(label='', widget=forms.EmailInput (attrs={'id': 'emailInput', 'class': 'article-search', 'placeholder': 'Enter yorffreur email here...', 'type': 'text'})) class Meta: model = Email fields = ['email'] def clean_email(self, *args, **kwargs): email = self.cleaned_data.get('email') qs = Email.objects.filter(email__iexact=email) if qs.exists(): raise forms.ValidationError('This email already exists.') return email In the base templates I have included the form as {{ email_form }}. But I do not know where to add the form manipulation. Usually I add it in the views but I'm new so I am an unsure how to do this. -
Django associate form values to user
I'm very new to Django but I started to create a project and I need some help. My question is very basic but I can't find the right answer. I made a questionnaire that works fine but I don't know how to do that if a logged in user adds his answers Django associate the answers to the user. Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import loader from .models import Stressz_teszt from .forms import StresszForm from django.forms import ModelForm def stressz_item(request): form = StresszForm(request.POST or None) if form.is_valid(): form.save() return redirect('stressz/login.html') return render(request, 'stressz/stressz-form.html', {'form':form}) Urls.py from . import views from django.urls import path from django.forms import ModelForm urlpatterns = [ path('', views.index, name='index'), path('login/', views.login, name='login'), #stressz teszt form path('add', views.stressz_item, name='stressz_item'), path('<int:item_id>/', views.detail, name='detail'), Forms.py from django import forms from django.forms import ModelForm from .models import Stressz_teszt class StresszForm(forms.ModelForm): class Meta: model = Stressz_teszt fields = ['stressz_v01', 'stressz_v02', 'stressz_v03', 'stressz_v04', 'stressz_v05',] ... Models.py from django.db import models from django.contrib.auth.models import User class Stressz_teszt(models.Model): def __str__(self): return self.stressz_name user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) stressz_name = models.CharField(max_length=200) stressz_company = models.CharField(max_length=300) stressz_v01 = models.IntegerField() stressz_v02 = models.IntegerField() stressz_v03 = models.IntegerField() stressz_v04 = models.IntegerField() stressz_v05 = … -
Django killed suddenly after runserver on M1
I have couple of project on Django and after hi runserver terminal shows : [1] 23857 killed python3 manage.py runserver I had update all library for working on Apple M1 and everything was good. after couple of day I tried to run and everything is crushed. my requirments.txt is : boto3==1.15.6 botocore==1.18.6 Django==3.1.1 django-cors-headers==3.5.0 django-debug-toolbar==3.1.1 django-storages==1.10.1 django-summernote==0.8.11.6 docutils==0.16 gunicorn==20.0.4 jmespath==0.10.0 Pillow==8.1.0 pipupgrade==1.7.4 psycopg2-binary==2.8.6 python-dateutil==2.8.1 pytz==2020.1 s3transfer==0.3.3 six==1.15.0 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==5.2.0 python3 version is 3.9.1 and when I run the code in PyCharm shows: /Users/username/python/myProject/.venv/bin/python3.9 /Users/username/python/myProject/myApp/manage.py runserver 8000 Process finished with exit code 137 (interrupted by signal 9: SIGKILL) I read maybe the problem of SIGKILL is about memory but half of my ram is free ~5GIG used 3GIG free -
Django returns NoReverseMatch instead of Updating the div with Ajax
Description I am creating a like button for a comment that was made on a post. When the user clicks on the like button, Django gives a NoReverseMatch and the page doesn't update automatically. After I refresh the page, it shows that the like was updated in the database, despite the NoReverseMatch error. What I tried? Initially, the issue was with the csrf_tokens. So, I added the csrf_exempt decorator, so it is definitely not the issue. I played a lot with the urls, and tried adding the comment id to the parameter, but it doesn't seem to help. Question How can I resolve the NoReverseMatch error and make it so that AJAX automatically changes the button from like to dislike. urls.py path('post/<int:pk>/like-comment', like_comment, name="like_comment") view.py @csrf_exempt def like_comment(request, pk): comment = get_object_or_404(Comment, id=request.POST.get('id')) liked = False if comment.likes.filter(id=request.user.id).exists(): comment.likes.remove(request.user) liked = False else: comment.likes.add(request.user) liked = True context = { 'comment': comment, 'is_liked': liked, 'total_likes': comment.likes.count() } if request.is_ajax(): html = render_to_string('blog/like_section_comment.html', context, request=request) return JsonResponse({'form': html}) main.js $(document).ready(function(event){ $(document).on('click', '#like-comment', function(event){ event.preventDefault(); var pk1 = $(this).attr('value'); // comment id var pk = $(this).attr('data-value'); // post id $.ajax({ type: 'POST', url: "like-comment", data: {'id': pk1, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: … -
duplicate key value violates unique constraint "photo_photo_user_id_key" DETAIL: Key (user_id)=(102) already exists
I receive the error above whenever users want to change their already existing profile. This is the views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.db import transaction from .models import Photo from .forms import PhotoForm Create your views here. @login_required @transaction.atomic def upload(request, pk=None): instance = Photo.objects.get(pk=pk) if pk else None context = dict(save_pk=pk or "") if request.method == 'POST': # Only backend upload should be posting here context['backend_form'] = form = PhotoForm(request.POST, request.FILES, instance=instance) if form.is_valid(): # Uploads image and creates a model instance for it context['posted'] = form.save(commit=False) context['posted'].user = request.user context['posted'].save() instance = Photo.objects.get(pk=pk) if pk else None else: # Form demonstrating backend upload context['backend_form'] = PhotoForm(instance=instance) return render(request, 'photo/upload.html', context) from the stack trace, the problem is coming from this line context['posted'].save() How do I go about it? I want the users to be able to change their profiles without trying to create a new instance afresh. This is the HTML template <main class="mt-5 pt-5 container"> <!--A standard form for sending the image data to your server --> <div class="mt-5 pt-5 container bg-white"> <h3 class="text-center">Upload</h3> <div class="mb-3"> <div class="mb-auto p-2 bd-highlight"> <form action="{% url 'upload' %}" method="post" enctype="multipart/form-data" class="text-center mt-5 "> {% csrf_token … -
How to push single file in git
I want to push a single or few files to my website in git. I do it everytime by following way - git add (file) git commit -am "make it better" git push heroku master The problem is that git push heroku master also changes other things on my website by replacing it with old one, for example - "replacing admin objects with old one which is in django server". Is there any way to push it for only single file ? -
Celery is not loading tasks from one app out of five
I'm using autodiscover in my celery.py file for gathering tasks. Which up until a recently picked all of the app.tasks.py up, I'm not sure why but my config.tasks.py function are no longer being picked up, but all the other apps are. If I from "config.tasks import *" there are no errors and I can run the tasks manually through shell. ive tried using force=True on autodiscover which had no effect, and a number of other solutions, none of which seem to have any effect, does anyone have any ideas on what to check next? Thanks Structure: -config --apps.py --views.py --models.py --tasks.py -monitoring --apps.py --views.py --models.py --tasks.py -app --apps.py --settings.py --celery.py celery config from __future__ import absolute_import, unicode_literals import os, django from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') django.setup() # This is key app = Celery("app") app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() if __name__ == '__main__': app.start() settings.py CELERY_TIMEZONE = 'Europe/London' ENABLE_UTC = True CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_TIME_LIMIT = 540 INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'haystack', 'django_tables2', 'django_filters', 'django_celery_beat', 'config.apps.ConfigConfig', 'monitoring.apps.MonitoringConfig', 'storages', 'stdimage', 'simple_history', 'crispy_forms', 'rest_framework', 'rest_framework.authtoken', ) tasks.py from __future__ import absolute_import, unicode_literals … -
Faster query than distinct in django
I am using Django and PostgreSQL, and I have query like below model.objects.filter(field=str(field)).exclude(tr__in=['some','some1']).distinct( 'field1','field2') In my model, I have 1 milion rows. The query above is so slow (It takes around 5-6 secs to fetch). I need alternative and faster way to implement it. Any ideas how to do? -
UnicodeDecodeError while loading .sav file
Trying to open .sav file in views.py using pickle. But throws me an error. Views.py : def result_india(request): model = pickle.load(open('finalmodel.sav', 'rb'), encoding='latin1') ans = model.piechart() return render(request, 'result_india.html', {'ans': ans}) Urls.py : urlpatterns = [ path('admin/', admin.site.urls), path('',views.home ), path('result_india/', views.result_india, name = 'result_india') ] Also, I have a function in my original py file that I have tried accessing in my views.py. Function : def piechart(): vaccines = ['Pfizer', 'Moderna', 'Oxford/AstraZeneca', 'CNBG', 'Covaxin', 'Sinopharm', 'Sinovac', 'Sputnik V'] data = [sum_pfizer, sum_moderna, sum_oxford, sum_cnbg, sum_covaxin, sum_sinopharm, sum_sinovac, sum_sputnik] fig = plt.figure(figsize=(8, 8)) plt.pie(data, labels=vaccines, rotatelabels=90) piechart = plt.show() return piechart piechart() Full error : UnicodeDecodeError at /result_india/ 'utf-8' codec can't decode byte 0x81 in position 5: invalid start byte Request Method: GET Request URL: http://127.0.0.1:8000/result_india/ Django Version: 3.1.5 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0x81 in position 5: invalid start byte Unicode error hint The string that could not be encoded/decoded was: ffff4�@