Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the original purpose of Django apps? What are the use cases of Django apps?
I'm building a website that'll use a Bootstrap template similar to the image shown below. I intend to add an authentication and authorization functionality using OAuth 2. The main menu will consist of: Homepage link Statistics app link NLP app link Computer vision app link Contacts page link Login button Without using Django, the homepage would just be index.html, the Statistics app would be a statistics.html page which interacts with the backend to show some plots, the NLP app would be an nlp.html page which interacts with the backend to display some NLP processed text and so on. When using Django, how am I supposed to structure it? Should I create a separate NLP Django app, and a separate Statistics Django app and a separate Homepage Django app? I'm already surprised that I had to create an app just to be able to have a homepage, and then had to add path('', include('homepage.urls')), to urlpatterns to redirect / to the homepage app. If I use the Bootstrap template for the homepage app, then how would I share the JS files, the CSS files and other boilerplate files of the template with the other apps of my website? Once the user … -
how to trigger an event of web socket (Django Channels) whenever new object of model has been created via django signals
This is my signal @receiver(post_save, sender=ChannelGroup) def channel_list_signal(sender, instance, created, **kwargs): try: print("signals") channel_layer = get_channel_layer() print(channel_layer) channel_layer.group_send( "channellist", { 'type': 'send_notification', 'message': "Done", }) print("return 'Done'") return "Done" except Exception as e: raise Exception(f"Something went wrong in channel_list signal {e}") This is my consumer class ListChannelConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.group_name = "channellist" self.channel_layer = None self.msg = None self.channels = [] # self.connected = False async def connect(self): user_id = self.scope["url_route"]["kwargs"]["user_id"] is_user_present = await check_user(user_id) print(self.channel_layer) # group_id = sender + receiver if is_user_present: self.user_name = is_user_present.username await self.channel_layer.group_add( "channellist", "temp" ) await self.accept() channel = await get_channels(is_user_present.username) await self.send(text_data=json.dumps({ "payload": "connected", "Channels": channel }, default=str)) else: raise Exception(f"User not present in database or private chat does not exists") async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def send_notification(self, event): print(event) event_data = QueryDict.dict(event) channels = event_data.get('message') # Send message to WebSocket self.channels = await get_channels(self.user_name) await self.send(text_data=json.dumps({ "Success": "channels", "message": channels })) What i am trying to achieve is i want to trigger send_notification event whenever i create new channel in my db but when i tried so it is not working actually i try to check the what … -
Map should count distance as per current Address in Django
I am new to Django, and I want to check if the entered address should not be far more than 2 hours from the current location using Map. I am sharing the screenshot of the UI. After adding the complete address I want to check if the entered address is how much far from the current address. and gave alert if addrees is far than 2 hours. I have tried this but not working. from django.contrib.gis.measure import Distance p2 = Event.objects.get(id=3).position for event in Event.objects.all().exclude(id=3).annotate(distance=Distance('position', p2)): print('{0} - {1}'.format(event.id, event.distance.m)) -
Why this ValidationError occur when deleting objects in Django model?
As far as I know, there are two ways to delete an object in the Django admin panel: delete one by one from the screen of each record -> Screen Transition delete items selected with check boxes from the record list screen -> Screen Transition The following ValidationError occurs only when trying to delete with the second way and the object cannot be deleted. (see image below) Please tell me how to fix this error. ValidationError at /admin/my_app_name/schedule/ ['“Oct. 2, 2022” value has an invalid date format. It must be in YYYY-MM-DD format.'] Below is the code that seems relevant. # models.py from django.db import models from django.utils.timezone import now class ScheduleType(models.Model): choices = ( ('normal', 'normal'), ('am', 'am'), ) schedule_type = models.CharField(max_length=32, choices=choices, primary_key=True) start_time = models.TimeField() end_time = models.TimeField() class Schedule(models.Model): choices = ( ('type1', 'type1'), ('type2', 'type2'), ) date = models.DateField(default=now, primary_key=True) is_working = models.BooleanField(default=True) schedule_type = models.ForeignKey(ScheduleType, on_delete=models.SET_NULL, null=True) service1_type = models.CharField(max_length=32, choices=choices) offer_service2= models.BooleanField(default=True) offer_service3= models.BooleanField(default=True) info = models.CharField(max_length=128, default='This is a normal day.') def __str__(self): return str(self.date) -
TypeError: unsupported operand type(s) for | [closed]
I'm getting the following linting error using Django Q objects: TypeError: unsupported operand type(s) for | The below is my code (it does work but not sure why I'm getting this linting error). Also the error disappears when I remove the third Q object. if request.GET: if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search critera") return redirect(reverse('products')) queries = Q( name__icontains=query) | Q(description__icontains=query) | Q( excerpt__icontains=query) products = products.filter(queries) -
Django + React Ecommerce project [Stripe payment connecting problem]
I've got a problem with Stripe connecting to my e-commerce website based on Django + React. I've got an e-commerce website in that I want to connect Stripe as a payment system. My website has about 200 products so I want to create a system when [Order.TotalPrice] is taken to Stripe (ofc. from the server side) and Payment is done. I care about the most trivial version of the code, because I want to add it to my website. I'aint a professionalist, so I really care of simplicity because of my skills. Thanks.! Thanks, dudes a lot! -
Django Signals pick up instances and choose the right one
I need a custom function based on date for calculations. I want to use signals for that, Plan is, When user updates a date, then the signal looks for everything what has the range of that date and uses the instances within the date range -
How can I get the data from a POST request using regular function. Django
I have this code from my views.py that working well, getting the data from my raspberry. from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def overview(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) return render(request, 'myhtml') now, I'm trying to use this code in another py file, regular function in my graph. py but it's not working. It's not showing any error and not printing any. def update_extend_traces_traceselect(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) I think the request is not working in a regular function. Is there another way to get the data? -
Reverse for "" not found. "" is not a valid view function or pattern name
I am a beginner in django and while I learnin dajngo from youtube I got this problem note that I do every thing like course step by step and I searched on solution to this problem for hours and I didn't find anything. when I pass url dynamically it causes a problem "Reverse for 'room' not found. 'room' is not a valid view function or pattern name." home.html {% extends "main.html" %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h3>{{ room.id }} -- <a href="{% url 'room' room.id %}">{{ room.name }}</h3></a> </div> {% endfor %} </div> </div> {% endblock %} room.html {% extends 'main.html' %} {% block content %} <h1>Room Page </h1> <h1>{{ room_r.name }}</h1> {% endblock content %} views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. rooms = [ {'id': 1, 'name': 'lets learn python!'}, {'id': 2, 'name': 'Desgin with me'}, {'id': 3, 'name': 'Frontend developer'}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def room(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'room_r': room} return render(request, 'base/room.html',context) urls.py from django.shortcuts import … -
Django: Perform GROUP BY over a view queryset
I need to perform group by over a queryset of objects already filtered by standard django filters in order to filter by how many objects in queryset are related to same foreign key object. My code now (does not work): class CustomerTicketsViewSet(AbstractViewSet): queryset = CustomerTicket.objects.all() serializer_class = CustomerTicketSerializer def filter_queryset(self, queryset): queryset_initial = queryset queryset = super().filter_queryset(queryset) tr2smp = int(self.request.GET.get('tickets_related_to_same_topic_gte', False)) if self.action == "list" and tr2smp: queryset = queryset.values('topic_id').annotate(tickets_to_same_topic=Count('topic'))\ .filter(tickets_to_same_topic__gte=tr2smp).distinct() return queryset If I filtered over all objects, I could have used CustomerTicket.objects.values('measuring_point_id').annotate(Count('measuring_point_id')) but how can I do the same thing with QuerySet? -
Django doesn't group by if I omit order_by() clause
I was trying to find an answer for this question in documentation but I unfortunately did not succeed. In documentation it states that if I want to group my objects and Count them I should use the following: MyObject.objects.values('field_to_group_by').annotate(Count('field_to_count')) However it doesn't work. But when I add simple order_by it does: MyObject.objects.values('field_to_group_by').annotate(Count('field_to_count')).order_by() Any idea why is that? They didn't mention that in documentation. -
Create Django Team / Player where order does matter
I'm creating a database of all races that are won by Athletes of our club. Goal is to have an overview of all the races that are won, but also a per_athlete count of the wins. A person in the database can be either be an athlete or a coach, or both, but not during the same race. A race can be with 1, 2,4 or 8 persons and the order of the athletes does matter, so I therefore think that a ManyToMany field is not working (only showed up to 4). I now solved it with 8 OneToOneField's. There must always be 1 athlete, so the first cannot be blank. class Person(models.Model): letters = models.CharField(max_length=10, blank = False) name = models.CharField(max_length = 100, blank = True) tussen = models.CharField(max_length = 50, blank = True) lastname = models.CharField(max_length = 100, blank = False) starting_year = models.IntegerField(blank = True) class RaceWin(models.Model): name = models.CharField(max_length =100, blank = False) year = models.IntegerField(blank = False) month = models.IntegerField(blank = True, null = True) athlete_1 = models.OneToOneField(Person, on_delete = models.CASCADE, related_name='athlete1', blank = False) athlete_2 = models.OneToOneField(Person, on_delete = models.SET_NULL, related_name='athlete2', blank = True, null = True) athlete_3 = models.OneToOneField(Person, on_delete = models.SET_NULL, related_name='athlete3', … -
Border not rendering properly in xhtml2pdf django
Unable to render borders properly in xhtml2pdf. It is applying to individual elements. Here is invoice template for rendering:- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SRS Mess | Invoice</title> <style> @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Merriweather&display=swap'); body{ font-family: 'Poppins', sans-serif; user-select: none; } /* Keeping paragraph together */ p{ margin: 0; -pdf-keep-with-next: true; } *, ::after, ::before { box-sizing: border-box; } @media (prefers-reduced-motion: no-preference) { :root { scroll-behavior: smooth; } } .container{ --bs-gutter-x: 1.5rem; width: 100%; padding-right: 7.5rem; padding-left: 7.5rem; margin-right: auto; margin-left: auto; } .text-center { text-align: center !important; } .mt-3 { margin-top: 1rem !important; } .mt-2 { margin-top: 0.5rem !important; } .text-danger { color: rgba(220, 53, 69, 1) !important; } </style> </head> <body> <div class="container mt-2 mb-2" style="background: rgb(237, 237, 255); border-top: 2px solid black; border-bottom: 2px solid black; border-left: 2px solid black; border-right: 2px solid black; border-radius: 1rem;"> <div class="text-center mt-3"> <img src="{{ST_ROOT}}/logo.png" alt="" height="200" width="200"> <p class="mt-2" style="font-size: 1.5rem; color: orange;">SRS Mess</p> <br> <p style="font-family: 'Merriweather', serif; font-size: 2rem; text-decoration: underline;">INVOICE</p> <p style="font-size: 1.5rem; font-weight:bold; color: green;">Monthly Mess subscription of Rs. {{amount}} /- </p> </div> <br> <div class="details"> <p><strong>Name: </strong>{{name}}</p> <p><strong>Email: </strong>{{email}}</p> <p><strong>Mobile: </strong>{{mobile}}</p> <p><strong>Hostel: </strong>{{hostel}} {{room}}</p> <p><strong>Branch: </strong>{{branch}}</p> <p><strong>Date: </strong>{{date}}</p> <p><strong>Time: </strong>{{time}}</p> </div> <br> <div class="subscriptions … -
What is the difference between signal and middleware in Django?
I dont understand what is the difference between this two function in Django. Both is doing something before or after request/response. Just like context switch or decorator. Can anyone tell me how to use this two Django function properly. -
How to assign a user to an employee in Django
I am a beginner in django and trying to create a web application for my task. I am trying to assign a user to every to employee. The idea is that user(in my class Employee) brings a list of user options that have not yet been assigned to the new employee to be registered My model class Employee(): name = models.CharField(max_length=100) job = models.CharField(max_length=30) user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return'{}'.format(self.name,self.job,self.user) My form class EmployeeForm(forms.ModelForm): user= forms.ModelChoiceField(queryset=User.objects.filter(id=Employee.user)) class Meta: model = Employee fields = [ 'name', 'job', 'user' ] My view def register_employee(request): if request.method == 'POST': form = EmployeeForm(request.POST) if form.is_valid(): form.save() return redirect('/') return redirect('list_employee') else: form = EmployeeForm() return render(request, 'employee/employee_form.html',{'form': form}) -
The correct way of modifying data before saving a model via the admin site
Django 4.1 models.py class Video(models.Model): phrase_id = models.IntegerField(default=-1, blank=False, null=False, validators=[MinValueValidator(0)]) # This field will be read only in the admin site. # Its only purpose is to ensure cascade deletion. _phrase = models.ForeignKey("vocabulary_phrases.Phrase", on_delete=models.CASCADE, default="", blank=True, null=True) admin.py class VideoAdmin(admin.ModelAdmin): list_display = ["phrase_id", "name", ] list_filter = ['phrase_id'] readonly_fields = ('_phrase',) form = VideoForm admin.site.register(Video, VideoAdmin) forms.py class VideoForm(ModelForm): def clean(self): if ("phrase_id" in self.changed_data) and self.cleaned_data.get("phrase_id"): phrase_id = self.cleaned_data["phrase_id"] _phrase = _get_phrase(phrase_id) self.cleaned_data["_phrase"] = _phrase return self.cleaned_data class Meta: model = Video exclude = [] In the admin site a user inserts an integer for phrase_id. Then in the admin form I wanted to substitute self.cleaned_data with Phrase instance I extract from the database. Well, the problem is that after saving, _phrase field is empty. Thid is the documentation: https://docs.djangoproject.com/en/4.1/ref/forms/validation/ It reads as follows: The form subclass’s clean() method... This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data Well, I have modified the cleaned_data, but it seems to have no effect on what is saved. My idea was: data are validated before saving, substitute cleaned_data, then your own data will be saved. I seem to have been wrong. Could … -
Django button submit not work after using javascript code
This would be my Registration page. When the script html tag testscript.js code is remove or commented out, the register button works perfectly fine but when I input the testscript.js, the register button is kind of disabled. So, I think the problem is the javascript code because that's the only part of the code that blocks the function of the register button. Here's my source code: views.py: def registration(request): form = CustomUserCreationForm() print("Working Form") if request.method == 'POST': form = CustomUserCreationForm(request.POST) print("Form Submitted") if form.is_valid(): form.save() context = {'form' : form} return render(request, 'activities/index.html', context) index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="../static/CSS/styles.css"> <link rel="stylesheet" href="../static/CSS/font-awesome/css/all.min.css"> <link rel="stylesheet" href="../static/CSS/css/bootstrap.min.css"> <script src="../static/Javascript/js/jquery.min.js"></script> <title>Document</title> </head> <body> <!-- Header --> <div class="site-header" > <nav class="navbar fixed-top navbar-expand-lg navbar-dark index__navbar scrolled"> <div class="container-fluid"> <div> <img class="navbar-icon" style="margin-left:15px;" src="../static/Media/avatar.png" alt="dasma-logo"> <span id="hideHomeTitle" class="brand__name" style="color:#2c5f2dff;">Preschooler Profiling and Monitoring</span> </a> </div> </div> </nav> </div> <!-- Form --> <div class="container-fluid" id="homeBody"> <br> <div class="form"> <div class="form-toggle"></div> <div class="form-panel one"> <div class="form-header"> <h1>Login</h1> </div> <div class="form-content"> <form action=""> <div class="form-group"> <label for="">Username</label> <input type="text" id="username" name="username"> </div> <div class="form-group"> <label for="">Password</label> <input type="password" id="password" name="password"> </div> <div class="form-group"> <label … -
Paginating the response of a Django POST request
I'm using Django for my work project. What I need to get is all likes put by some user. Likes are put to transactions, so I am getting the list of all transactions in 'items' field, where the user put his like/dislike. There are some optional parameters that can be in the request: user_id (usually is taken from session), like_kind_id(1 for like/2 for dislike), include_code_and_name for like_kind (True/False), and page_size (integer number) for pagination. With the last parameter, I am facing the issues. The result should look like this: { "user_id":id, "likes":[ { "like_kind":{ "id":id, "code":like_code, "name":like_name, }, "items":[ { "transaction_id":transaction_id, "time_of":date_created, },... ] } ] } "Likes" is just array of 2 elements (like and dislike). So, my problem is that I cannot set pagination for "items" array as there can be a lot of transactions. I am getting the page_size from request.data.get("page_size") but cannot apply it so that the results will be paginated. I know that for GET-requests I need simply set pagination_class in views.py. Anyone knows how can I do the similar procedure for POST-request and set the page_size of pagination class to 'page_size' from data.request? =) This is my views.py: class LikesUserPaginationAPIView(PageNumberPagination): page_size … -
AttributeError 'function' object has no attribute 'predict'
I got error like this AttributeError 'function' object has no attribute 'predict' while I put the 'predict' in 19. I tried to change the attribute but it has the same problem. How to solve the error? AttributeError at /predict/result/ 'function' object has no attribute 'predict' I put this code in views.py def result(request): cls = joblib.load("pnn_parkinson.sav") gaussian_tf = lambda x: (1.0/tf.sqrt(2*np.pi))* tf.exp(-.5*x**2) lis = [] lis.append(request.GET['n1']) lis.append(request.GET['n2']) lis.append(request.GET['n3']) lis.append(request.GET['n4']) lis.append(request.GET['n5']) lis.append(request.GET['n6']) lis.append(request.GET['n7']) lis.append(request.GET['n8']) lis.append(request.GET['n9']) lis.append(request.GET['n10']) lis.append(request.GET['n11']) lis.append(request.GET['n12']) predict = cls.predict([[lis]]) result = "" if predict==[1]: result = "Positive Parkinson" else: "No Parkinson" return render(request, "result.html", {"result1":result, 'predict':predict, 'lis':lis}) I also put this code in predict.html <div class="form-inline container p-5 my-5 border text-dark" style="text-align:left"> <h2>Prediksi</h2> <form action = "result" method="GET"> {% csrf_token %} <div class="mb-3 row form-inline"> <label for="text" class="col-sm-2 col-form-label">MDVP:Fo(Hz)</label> <div class="col-md-4"> <input type="text" class="form-control" id="text" placeholder="Enter MDVP:Fo(Hz)" name="n1" required> </div> In the urls.py I put this code path('predict/result/', views.result, name='result'), -
How to connect a payment system in django?
I'm new to the Django framework and I don't quite understand how to connect the payment system to the site, at the same time, so that part of the payment for the product goes to the balance of the user who exposed it, and 10%-20% of the amount goes to the balance of the service. And what is the best way to connect a payment system for individuals.faces? -
Shopify Django App not working in Safari Browser
We have a shopify django app that is embedded into shopify. It works fine for mozilla and chrome, but not working in safari. We are getting internal server error when trying to load the page. This is the error we are getting: Failed to load resource: The server responded with a status of 500. -
Python Plotly Dash Django testing daylight savings time
I have a time series data base where datetime is stored in UTC. A Python Dash date picker and Text box allows selection of date and time. The pandas DataFrame is made timezone aware and used as the x axis as follows: x=df['cdatetime'].dt.tz_localize('utc').dt.tz_convert('Europe/London'), The chart and map plot the data correctly, showing times in the correct locale which is currently BST. However I want to test if it still works when daylight savings time ends and locale timezone is GMT. What is the recommended way to do this please ? -
What is *args in Django view? And how to pass parameters to *args
I am a novice in Django and I want to clear for myself in Views - what is *args parameters? I know what is *args in Python, but I mean what it contains in Django view, how to pass *args to view? I do understand **kwargs in view - it's a URL-variables captured, request it's an HTTP-request params captured. But what is *args and where it's useful? -
How can I use request.method in a django python file?
I'm trying to get the data from a POST but I can't use the 'request' it says "NameError: name 'request' is not defined". I tried using 'import request' it says that 'No module named 'request''. This code is from my views.py that working well. Is it possible to use this also in a python file? or there is another way? in my graph.py def update_extend_traces_traceselect(): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) -
My flask app shows, Method Not Allowed The method is not allowed for the requested URL
I was trying to deploy a machine learning model using Flask, but I can't identify why it won't let me perform a POST request to get my predicted value. Can someone let me know where did I go wrong with my code? I already tried putting request.method == "POST" earlier but my Flask app still throws the error. app.py from flask import Flask, render_template, request import joblib import numpy as np model = joblib.load('ml_model_diabetes') app = Flask(__name__) # A must at all times app.config['TEMPLATES_AUTO_RELOAD'] = True app.debug = True @app.route("/") def home(): return render_template('index.html') @app.route("/diabetesdetection", methods=['POST']) def diabetesDetection(): numOfPreg = request.form['numOfPreg'] glucose = request.form['glucose'] bloodPressure = request.form['bloodPressure'] skinThickness = request.form['skinThickness'] bmi = request.form['bmi'] diabPedigFunc = request.form['diabPedigFunc'] age = request.form['age'] arr = np.array([[numOfPreg, glucose, bloodPressure, skinThickness, bmi, diabPedigFunc, age]], dtype=float) pred = model.predict(arr) return render_template('diabetes.html', data=pred) @app.route("/heartdisease-detection") def heartDiseaseDetection(): return render_template('heart.html') if __name__ == "__main__": app.run(debug = True) diabetes.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.101.0"> <title></title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <style> body { padding-top: 5rem; } .starter-template { padding: 3rem 1.5rem; text-align: center; } …