Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy label studio on Azure VM?
I want to deploy label studio annotation package to my azure VM. It is based on Django. I know how to deploy Django apps. But I was curious to know if there is any possible way to deploy it more efficiently. I am hesitant to try docker right now because I have one more Django app deployed on the same VM using Apache, and I fear using docker might break it. -
How to deal with nested serializer fields in Djnago rest framework?
I have nested serializer (AmountSerializer). I need field meal_name in one ViewSet. But when this field is nested i don't need it to be seen in endpoint(in MealSerializer). How to exclude field from nested serializer when is it actually nested? serializers.py: class AmountSerializer(serializers.ModelSerializer): ingredient_name= serializers.ReadOnlyField(source='ingredient_name.name') -->#meal_name = serializers.ReadOnlyField(source='meal.name') class Meta: model = IngredientAmount fields = ('ingredient_name','amount','meal_name') class MealSerializer(serializers.ModelSerializer): type_name= serializers.ReadOnlyField(source='type.name') ingredients = serializers.SlugRelatedField(read_only=True, slug_field='name', many=True) amount = AmountSerializer(read_only=True, many=True,source='meal_id') class Meta: model = Meal fields = ('id', 'name', 'type_name', 'recipe', 'photo', 'ingredients','amount') -
Django Admin one field required related on other field
I am using Django admin to save models my model is like bellow: class PurchaseItem(models.Model): product=models.ForeignKey("products.Product",on_delete=models.CASCADE,blank=True,null=True) product_attribute=models.ForeignKey("products.ProductAttribute",on_delete=models.CASCADE,blank=True,null=True) The goal is to save only one of the foreign keys for example : If the product is not null then the product attribute needs to be null Same thing for the product_attribute if its not null then the product must be null Note: product and product_attribute cannot be null at the same time . how to achieve this using the Django admin. -
Django App to read QR code URL and display image on website
I am creating a django that displays different images on a website when their respective QR codes are scanned. Its my first time working with Django and I am unsure how to update the index page to display the image when the QR code is scanned. I would like to add a URL route that should make the image visible when the QR code is scanned but I am unsure how to carry out that logic in django. views.py def index(request: HttpRequest) -> HttpResponse: return render(request, "index.html") # template = loader.get_template('index.html') # return HttpResponse(template.render({}, request)) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ # path('admin/', admin.site.urls), path("", views.index, name="index") ] index.html {%extends 'base.html' %} {% load static %} {% block title %} Home {% endblock %} {% block content %} <div class="grid-container"> <figure class="gallery__item gallery__item--1"> <img id="image1" src="{% static 'theme/assets/img/Freesample.svg' %}" class="gallery__img" alt="Image 1"> </figure> </div> {% endblock %} scripts.js function setImageVisible(id, visible){ var img = document.getElementById(id); img.style.visibility = (visible ? 'visible' : 'hidden'); } -
append the char field in django models
I have a simple choice field in my model which saves present or absent of a student for his/her attendance. However, what I felt is, it will create different object for just a status of his/her attendance. Is there any way to just append present or abset to the same field to save the resource of the database?? My models look like this: class OnlineClass(models.Model): teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) course = models.ForeignKey(Subject,on_delete=models.CASCADE) faculty = models.CharField(max_lenthg=255) students_in_class = models.ManyToManyField(Student) STATUS = ( ('present','present'), ('absent','absent'), ) class Attendance(TimeStampAbstractModel): classes = models.ForeignKey(OnlineClass) student = models.ForeignKey(Student) status = models.CharField(choices=STATUS, max_length=10, blank=True) By using this model, there will be different object of attendance for each student of each course which will be consuming huge resources. Instead what I want is just append present or absent for each day of attendance to the status field just like django-taggit. So that when I call get api, I will be getting like a list of attendances.Is it possible?? -
wanted call store procedure from another store procedure and returning output on HTML page with python django
I have totally 3 store procedures 1)notification_services(email_template_id,execute_date,record_no) passing this parameter I got output having 'script_coloum' which contain another store procedure. 2)sp_get_email_services_project_assigned 3)sp_get_email_services_project_rejected these 2 and 3 store procedure selection depends upon notification_services(email_template_id) if email_template_id=1 call sp_get_email_services_project_assigned if email_template_id=2 call sp_get_email_services_project_rejected According this result should be display on HTML page ############################################################################################## from typing import List from django.db.backends.utils import CursorDebugWrapper from django.http.response import HttpResponse from django.shortcuts import render import os from django.db import connection from rest_framework import generics from demo_sp.serializers import StoredProcedureSerializer #from mysql.connector import MySQLConnection,Error #from python_mysql_dbconfig import read_db_config # def show_details(request):#email_template_id #wk # return render (request,'sp_app/html_template.html')#{'id':email_template_id} #from django.http import HttpResponse def common(self,script=[],request=[]):#self, request=None, print("IN common Function") #assigned if script==[]: #user_name = self.request.GET.get('user_name') print(115) with connection.cursor() as cursor: print(116) cursor.callproc('sp_get_email_services_project_assigned',['user_name','project_name','city_name','toll_free_no','help_desk_email']) #result=cursor.fetchall() data=StoredProcedureSerializer(cursor).data if type(data)==dict and not data: data=[] print("uuuuuuuuuuu=",data) #return data return render(request,'sp_app/html_template.html',{"data":data}) #reject if script=='116': with connection.cursor() as cursor: cursor.callproc('sp_get_email_services_project_rejected') data=StoredProcedureSerializer(cursor).data result=cursor.fetchall() return result #return render(request,'sp_app/html_template.html',{'result':result}) #<-------------------------------------------------------------------------------------------> class gettemplate(generics.ListCreateAPIView): print(1) def get(self, request, *args, **kwargs): print(2) email_template_id = self.request.GET.get('email_template_id') print(email_template_id) execute_date =self.request.GET.get('execute_date') print(execute_date) record_no =self.request.GET.get('record_no') print(record_no) if not email_template_id : raise Exception("Please enter valid template ID") if not execute_date : raise Exception("Please enter valid execute_date") if not record_no : raise Exception("Please enter valid record_no") with connection.cursor() as cursor: cursor.callproc('notification_services',[email_template_id,execute_date,record_no]) data=StoredProcedureSerializer(cursor).data … -
How can I reduce the deep learning model inference inside Django server
I have a Pytorch vision model which takes <4 seconds for performing inference on a image on CPU when calling as a standalone python program or calling from Django as a subprocess, but when the same inference method is called from Django server inside view.py methods, the time for performing inference is >50 seconds. How can I solve this issue. Tried the following inside Django view import sys import subprocess sys.path.append('/home/ubuntu/project/driver/') def process_pool(file_path): return main.process(file_path) def predict(request): file_path = get_path(request) cmd = '/home/ubuntu/project/driver/main.py' print(subprocess.check_output(['python',cmd])) # Method 1 Using python subprocess - Takes 4 seconds to infer the output pr = multiprocessing.Pool() result = pr.map(process_pool,[file_path]) # Method 2 Using multiprocessing - Takes more than 50 seconds to infer the output process_pool(file_path) # Method 3 - Without multiprocessing - Takes more than 50 sec to infer the output The project main.py contains def process(file_path): """ run deep learning code """ return predict(file_path) if __name__ == '__main__': process('/home/ubuntu/a.jpg') -
Django: 'WSGIRequest' object has no attribute 'Post'
Im kinda new to Django and already stuck at some simple POST-problem. Heres the HTML within profile.html: <form action="{% url 'profile' %}" method="post"> {% csrf_token %} <input type="text" placeholder="Weight", name="weight"> <input type="text" placeholder="Reps", name="reps"> <input type="submit"> </form> And heres the correspoding view: def profile(request): if request.method == "GET": return render(request, "userprofile/profile.html") elif request.method == "POST": print(request.Post) return render(request, "userprofile/profile.html") Basically, all I want to do for now, is to print the POST-data dictionary into the Terminal. However, I get the following error: AttributeError at /profile/ 'WSGIRequest' object has no attribute 'Post'. What am I missing? Thanks so much for any help! -
How do I fix no module found error in Django?
I'm reading the Django docs and I'm going through the first project called "mysite" and it has an app called polls This is my file structure : \pythonproject \mysite \mysite \polls \migrations __init.py__ admin.py apps.py models.py tests.py urls.py views.py __init__.py db.sqlite3 manage.py I am in this location : polls\urls.py and I want to import "polls\views.py" So I type in this : from mysite.polls import views And I get the error when I ran: python manage.py test This is the error : No module found "mysite.polls" The error refers to the second line of code in polls\urls.py I am using pycharm and my Django version is "3.2.8" My python version is "3.10" -
why is the form works in "is_valid" but doesn't update objects?
I'm trying to update this field, when I do "forms.is_valid" and print anything into it like print("updated") as you can see below, this print works fine which means that "is_valid()" produce a "True" value, however, nothing is updated in a database then. anyone can help please: views.py def review_membership(request, id=None): roles = str(User.objects.get(email=request.user).roles.get()) membership = MemberShip.objects.get(id=id) user_admin = User.objects.get(roles__id='Admin') forms = MemberShipForm() disable_field = True if request.user.email == membership.ambassador.email: disable_field = False if membership.status == "Pending": if roles == "SubAmbassador": if restrict_see_report(request) == True: field_disabled(forms) if request.method == "POST": if "update" in request.POST: forms = MemberShipForm(request.POST) # print(User.objects.get(email=membership.ambassador)) if forms.is_valid(): forms.instance = request.user print('updated') forms.save() messages.success(request, 'This field has updated') return redirect('index:review_membership', membership.id) forms.py class MemberShipForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name', 'class': 'form-control'})) price = forms.IntegerField(widget=forms.NumberInput(attrs={'value': 0, 'class': 'form-control'})) description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'type a description here...', 'class': 'form-control'})) class Meta: model = MemberShip fields = ['name', 'price', 'description'] models.py class MemberShip(models.Model): name = models.CharField(max_length=20, blank=False) description = models.TextField(blank=False, null=True) price = models.PositiveIntegerField(default=0) ambassador = models.ForeignKey(User, on_delete=models.CASCADE, null=True) sub_ambassador = models.ForeignKey(SubAmbassador, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=20, choices=MEMBERSHIP_STATUS, default='Inactive') def __str__(self): return self.ambassador.email def get_status(self): return self.status -
django-rest-framework-social-oauth2: error 400 - redirect_uri_mismatch
I've been trying to add google login to my django app following this tutorial: https://github.com/RealmTeam/django-rest-framework-social-oauth2 By following exactly the instructions, everything works fine in local. However, when I try to replicate the same on the server, I get the following error on the redirect page of the login: Error 400: redirect_uri_mismatch redirect_uri: http://localhost:8000/auth/complete/google-oauth2/ What is strange to me is, in my google developer console, I have set up the correct redirect url in my app, as follows: https://mydjangoapp.com/auth/complete/google-oauth2/ And I have also put 'mydjangoapp.com' under 'Authorised JavaScript origins'. So my question is, why google keeps telling me that the redirect url is http://localhost:8000/auth/complete/google-oauth2/ which is not the one I have set up in the console? Perhaps there is something obvious that I'm missing here. Thank you! -
Charts not being displayed in django app when using Chart.js 3.6 version
I have a Django application which has charts. They were implement in Chart.js 2.9 version. When I upgraded to Chart.js 3.6 version, I am unable to view the charts. I have check those charts in a standalone HTML page. They work fine there. -
Error 32 when Twitter sign in with Django AllAuth and post tweet with Tweepy
I'm using Django AllAuth for twitter login, and it's working perfectly and saving the token and token secret to the Social Account Tokens table. I'm then trying to use Tweepy to send a tweet on the user's behalf (yes, the scope allows that). But when I try to send the tweet, I get tweepy.error.TweepError: [{'code': 32, 'message': 'Could not authenticate you.'}] Here's the auth code: def auth_tweepy(user): twitter_auth_keys = settings.TWITTER_AUTH_KEYS auth = tweepy.OAuthHandler( twitter_auth_keys['consumer_key'], twitter_auth_keys['consumer_secret'] ) user_auth = SocialToken.objects.get(account__user=user, account__provider='twitter') auth.set_access_token( user_auth.token, user_auth.token_secret ) return tweepy.API(auth) def send_tweet(tweet_content): api = auth_tweepy(user) try: api.update_status(tweet_content) except tweepy.TweepError as error: if error.api_code == 187: print('duplicate message') I dont think the tokens are expired bc I JUST logged in. Any ideas what might cause the 32 error in this case? -
How django + restframework implements the parameter interface through inherited classes
When my RegisterView inherits APIView and cannot display parameters, what should I do to make RegisterView display parameters like LoginViewHow to make register display interface parameters like login. -
Error when connecting to a scss file in django
I am trying to connect to my scss file in static, but I get the following error: sequence item 1: expected str instance, WindowsPath found The error supposedly comes from the following line of code in my base.html: <link href="{% sass_src "css/main.scss" %}" rel="stylesheet" type="text/css" /> When I looked up in the Internet, I read that some say it is a specific error that happens for people using a windows os. Do you guys know why this error is happening, and how to solve this issue so that I could use my scss file for the templates? Please ask me any questions. -
How can I get latest record by queryset. like group by
Data name data1 data2 create_date iron man ia ib 1630000000 hulk ha hb 1630000000 hulk hc hd 1630500000 captain ca cb 1630000000 captain cc cd 1630500000 captain ce cf 1630590000 I want to get latest data each name name data1 data2 create_date iron man ia ib 1630000000 hulk hc hd 1630500000 captain ce cf 1630590000 like this wish_data = [ {'name':'iron man', 'data1': 'ia', 'data2': 'ib', 'create_date':1630000000}, {'name':'hulk', 'data1': 'hc', 'data2': 'hd', 'create_date':1630500000}, {'name':'captain', 'data1': 'ce', 'data2': 'cf', 'create_date':1630590000}, ] I tried... Model.objects.filter(**conditions).values_list('name').annotate(cdate=Max('create_date')) => [('iron man', 1630000000), ('hulk', 1630500000), ('captain', 1630590000)]> but i need to other columns... Q Is it possible with ORM? Or do I have to write the logic with for and if statements? -
How to change Django admin url for rewrite urls
I have Django project, which is deployed to kubernetes, where I need to rewrite the admin url to different endpoint. Currently my admin endpoint is mapped as below: url(r'^admin/', admin.site.urls) Which works fine in local and ingress url when I try to access my it using <BASE_URL>/admin. But now I have to rewrite my service url to different endpoint in Kubernetes for example as below: spec: prefix: /app/sevice/admin/ rewrite: /admin/ After this I'm able to access my admin panel home page with ambassador url <AMBASSODER_BASE_URL>/app/service/admin only when I'm already logged-In to admin and after I click on any of the table listed in admin UI it throws me to <AMBASSODER_BASE_URL>/admin> because I can still see admin UI html href /admin/../... Is there any way to make those href to use relative path rather then full path. I mean just the path after /admin. -
Search Bar Problems showing email
My search bar showing me to give it a email address or it will not accept it. Thanks in advance. for email bar def index(request): if request.method =='GET': email = request.GET.get('email') if email: subscribe(email=email).save() views.py def search(request): q = request.GET.get('q') posts = Post.objects.filter( Q(title__icontains = q) | Q(overview__icontains = q) ).distinct() parms = { 'posts':posts, 'title': f'Search Results for {q}', 'pop_post': Post.objects.order_by('-read')[:9] } return render(request, 'all.html', parms)` base.html : -
Django: How to do full-text search for Japanese (multibyte strings) in Postgresql
It is possible to create an index for searching using SearchVector, but However, Japanese words are not separated by spaces, and the full-text search does not work properly. How can I perform full-text search in Japanese (multi-byte character strings)? I thought about implementing a search engine such as ElasticSearch, but other problems came up. If possible, I would like to do FTS with Postgres. # models.py class Post(models.Model): title = models.CharField(max_length=300) search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["search"])] # update search column Post.objects.update(search=SearchVector('title')) -
Django Show Code in Template if Logged In
In a Laravel Blade template, I can do this to show code only if a user is logged in: @auth <div>Show code only if logged in.</div> @endauth Does Django have a template tag or something similar that does the equivalent? E.g.: {% auth %} <div>Show code only if logged in.</div> {% endauth %} -
Which is better framework Django or Flask? [closed]
I asked this question with my friends but they didn't know about it i am looking for a better framework for Web Development that is coded in Python please help ;/ -
How to add event to multiple dates at the same time in HTMLcalendar
I'm using the htmlcalendar module in Django. When adding an event by setting a period, I want the event to be added at the same time on the relevant date. In the code implemented so far, it is possible to add events only for 1 day. Where do I need to change to get the desired result? models.py class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) leave_date_from = models.DateField(blank=True, null=True) leave_date_to = models.DateField(blank=True, null=True) ----> I just added this field take_over = models.TextField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) utils.py class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(leave_date__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Leave.objects.filter(leave_date__year=self.year, leave_date__month=self.month, is_deleted=False) cal = f'<table border="0" cellpadding="0" … -
Not Found: /socket.io/
Does anyone have any experience with creating a chat in Django using the python-socketio library? When I launch a Docker container, the backend gives the following error on the Get request: "GET /socket.io/?EIO=3&transport=polling&t=NUzXPq6 HTTP / 1.1" 404 2124 Not Found: /socket.io/ -
I keep getting a 403 forbidden error in Django
Problem 1: I made a notes app. I made a login function, that logs in people. I keep getting an error after I log in and try to create a new note, it is saying "403 forbidden error" in the console. But if I dont log in, it works perfectly. Heres the backend code : @api_view(["POST"]) def login_view(request): data = request.data username = data["username"] password = data["password"] if request.user.is_authenticated: return Response("hpr") else: user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response("hpr") return Response("An error occured, please try again later.") this is the login view. I have created a model with a foreign key, that might be the problem too. class Note(models.Model): body = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, related_name="notes", on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] here is the view that creates a note : @api_view(['POST']) def createNote(request): data = request.data note = Note.objects.create( body=data['body'], ) serializer = NoteSerializer(note, many=False) return Response(serializer.data) Problem 2: I also have another doubt. I have a function that gets the notes from the database and displays it. I have made the serialised get all the fields of the note model. But when I try … -
ValueError at /freshleadaction for uploading .csv file in Django
I am stuck on an error in django while uploading a .csv file for fresh leads and I have searched a lot on google for the solution but couldn't find the solution so now decided to upload it so that community can help me. I am displaying the code that I have done so. Models.py: class fresh_leads_model(models.Model): fname = models.CharField(max_length=20) lname = models.CharField(max_length=20) street_number = models.CharField(max_length=20) street_name = models.CharField(max_length=50) state = models.CharField(max_length=50) zip_code = models.CharField(max_length=50) bedrooms = models.CharField(max_length=20) legal_description = models.CharField(max_length=100) sq_ft = models.CharField(max_length=50) address = models.CharField(max_length=50) orign_ln_amt = models.CharField(max_length=50) prop_value = models.CharField(max_length=50) equity = models.CharField(max_length=255) email = models.CharField(max_length=50) cell = models.CharField(max_length=50) submitted_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=True) deleted_date = models.DateField(auto_now_add=True) my views.py file for fresh leads upload: @login_required @allowed_users(allowed_roles=['admin']) def upload_fresh_leads(request): get_type = request.GET['type'] lst = [] if request.method == 'POST': leads = Fresh_leads_Form(request.POST, request.FILES) data = request.FILES.getlist('csv') # data = Fresh_leads_Form(request.FILES) # csv_file = request.GET['csv'] # df = pd.read_csv(csv_file) # return HttpResponse(print(df))) # data = [] # message = 2 # return render(request, 'admin/src/tabs/fresh_leads.html', {'message': message}) if get_type == '1': if leads.is_valid(): # csv = data['csv'] for d in data: # df = pd.read_csv(d, usecols=['Owner First Name']) # return HttpResponse(df.to_string()) df = pd.read_csv( d, dtype='str', usecols=[ 'Owner First …