Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call manager of select_related field
I have the following example: class Profile(models.Model): ... class Person(models.Model): profile = models.ForeignKey(Profile, ...) I have complex Model manager for Profile class and I built a view to list a big amount of Person. I try to compute everything in database so I would like to call the Profile Manager from Person QuerySet. To do that, I need to do something like: Person.objects.filter(...).select_related('profile', queryset=Profile.objects.with_computed_revenue().all()) And then I should be able to get person.profile.computed_revenue retrieved from SQL, with the function "with_computed_revenue" being a function of the ProfileManager that annotate computed_revenue. The final goal is to add in person queryset : .values('profile__computed_revenue') It seems possible with Prefetch for prefetch_related, but I cannot find an equivalent with select_related. -
Nested table rows
I'm working on a project that is still in its early stages using Django and Jquery. I would wish to create a nested table in that team leaders have people assigned to them. So far I have been able to display team leaders but not able to display employees associated with them. Views.py class SupervisorEmployee(View): def get(self,request,firstname,lastname,*args,**kwargs): supervisor_name=get_object_or_404(Supervisor,firstname=firstname, lastname=lastname) filtered_team_leaders=TeamLeaders.objects.filter(supervisor=supervisor_name.pk) context={ 'firstname':firstname, 'lastname':lastname, 'filtered_team_leaders':filtered_team_leaders, } return render(request,'supervisors/employees.html',context) class EmployeeResponseView(View): def post(self,request): first_value = request.POST.get('first_value') first_value=first_value.strip() second_value = request.POST.get('second_value') second_value=second_value.strip() team_leader_query=get_object_or_404(TeamLeaders,fname=first_value,lname=second_value) employee_query=Employees.objects.filter(team_leader=team_leader_query.pk) data=serializers.serialize('json',employee_query) return HttpResponse(data,content_type='application/json') template.html <thead class="bg-secondary text-white"> <th>ID</th> <th>firstname</th> <th>lastname</th> <th>Role</th> <th>Joining</th> <th>age</th> <th>remuneration</th> </thead> <tbody> {% for team_leaders in filtered_team_leaders %} <tr id="emb" class="bg-light"> <input id="first" type="hidden" value="{{ team_leaders.fname|safe }}"> <input id="second" type="hidden" value="{{team_leaders.lname|safe }} "> <td>{{ team_leaders.id }}</td> <td>{{ team_leaders.fname }}</td> <td>{{ team_leaders.lname }}</td> <td><span class="badge bg-danger">{{ team_leaders.role }}</span></td> <td>{{ team_leaders.joining }}</td> <td>{{ team_leaders.age }}</td> <td>{{ team_leaders.remuneration }} / day</td> </tr> employee data goes here {% endfor %} </tbody> </table> template associated with jquery to add employee data below supervisor var first_value=$.trim($('#first').val()); if(second_value != '' && first_value != '') { $.ajax({ url:'{% url "employee_response" %}', method:'POST', data:{'first_value':first_value,'second_value':second_value}, success:function(data) { Response data from database should be embedded below each team leader }, error:function() { alert('Error fetching employees'); } … -
Cannot create a server with run.py for e-commerce website
This is one of my first times using this website so please feel free to ask for clarification underneath if I haven't worded this well! So, im creating an e-commerce website for a project however I have an error where my form code is displaying on my website instead of actually working (if that makes sense!) I asked for help previously and was told I needed to run my server with run.py to get to the local host. However when I try running run.py I have this error: Traceback (most recent call last): File "run.py", line 1, in from shop import app File "/Users/darby/Desktop/CM1102-WA-master copy/Coursework_3/shop/init.py", line 4, in from shop import routes File "/Users/darby/Desktop/CM1102-WA-master copy/Coursework_3/shop/routes.py", line 3, in from others.py import app, db ModuleNotFoundError: No module named 'others' The files it references in question are as follows: run.py from shop import app if __name__ == "__main__": app.run(debug=True) init.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from shop import routes app = Flask(__name__, static_folder="static") db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) routes.py from flask import Flask, render_template, flash, redirect, url_for, session, request, logging, session from flask_login import login_user, current_user, logout_user, login_required from others import app, db … -
Django, Foreign key not getting filled with session data
im trying to fill my foreignkey with the user that is logged in, but i have seen alot of way but they havent worked for me, does anyone know what im doing wrong? and how i can fix it? View: class JobCreate(CreateView): model = Job form = JobCreateForm() form_class = JobCreateForm context = {} success_url = reverse_lazy('jobsview') def POST(self,request): if(request.method == 'POST'): form = JobCreateForm(request.POST) if(form.is_valid): job = form.save(commit=False) job.employer = request.user job.save() context = {} return render(request, 'jobs/jobs.html',context) else: context = {} return render(request, 'jobs/job_form.html',context) Model: class Job(models.Model): employer = models.ForeignKey(User, related_name='employer', on_delete=CASCADE,blank=True) employees = models.ManyToManyField(User, related_name='employees2user',null=True,blank=True) title = models.CharField(max_length=200,) description = models.CharField(max_length=200,null=True,blank=True) category_id = models.ManyToManyField(Category,blank=True) skill_id = models.ManyToManyField(Skill,blank=True) approved = models.BooleanField(default=False) # img = models.ImageField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): # Default value return self.title -
use model's value to create a Django form
I have a model which is as follows: class BloodTestType(models.Model): type = models.CharField(max_length=200) def __str__(self): return str(self.type) class BloodParameters(models.Model): type = models.ForeignKey(BloodTestType, on_delete=models.CASCADE) parameter = models.CharField(max_length=200) minimum_value = models.FloatField() maximum_value = models.FloatField() unit = models.CharField(max_length=200) required = models.BooleanField(default=True) GENDER_CHOICES = [ ('B', 'Both'), ('M', 'Male'), ('F', 'Female'), ] gender = models.CharField(max_length = 100,choices = GENDER_CHOICES,default = 'B') def __str__(self): return str(self.type) + ' ' + str(self.parameter) Consider BloodParameters model has 3 parameters with type = '1' I want to create a Django form containing these 3 parameters as input fields but the form loads up as blank. I'm trying something on these lines in my forms file : class BloodReportCBCIronForm(forms.Form): cbc_iron_parameters = BloodParameters.objects.filter(type = 1) print('asd') print(cbc_iron_parameters.__dict__) for each in cbc_iron_parameters: each.parameter = forms.CharField(label = each.parameter,max_length = 80,required = True,) -
Django- Ajax returning wrong data
I'm building a webcomic using Django framework. The problem that I have now is to display chapters from different issues with AJAX. Let's say we have issue#1 and issue#2, when user clicks on issue#1 cover, it displays chapters of issue#1. I have managed to make it partially work, but it always displays issue#2 chapters, even if I click issue#1. excpected behaviour: how it is now: issue list html {% csrf_token %} <script> const csrftoken = document.querySelector("[name=csrfmiddlewaretoken]").value; </script> <div class="container mt-3 mb-3"> {% if issue_pl %} <div class="center-issues"> {% for issue in issue_pl %} <img src="{{ issue.cover.url }}" class="issue-thumbnail" alt="{{ issue.title }}" title="{{ issue.title }}" onclick="aload();" /> <script> function aload() { var xhr = new XMLHttpRequest(); xhr.open("POST", "{% url 'chapter_pl' issue.slug %}"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.onload = function () { document.getElementById("container").innerHTML = this.response; }; xhr.send(); } </script> {% endfor %} </div> {% endif %} <div id="container"></div> </div> views.py def ChapterListPL(request, slug): chapter_pl = ChapterPL.objects.filter(issue__slug=slug, status=1).order_by('number').all() context = { 'chapter_pl': chapter_pl, } return render(request, 'comics/chapters_pl.html', context) urls.py path('comics/<slug>/chapters', views.ChapterListPL, name='chapter_pl'), -
Using multiple connection vs single connections in sql python
I am using pymysql to connect to sql like this: con=pymysql.connect(...) cur=con.cursor() Well I am using flask web framework for some use. I defined the connection object as a single time and pass it to other function for use like this: @app.route('/') def index(): cur.execute(...) con.commit() #other stuffs My questions is that whether it is a good way or this: @app.route('/') def index(): con=pymysql.connect(...) cur=con.cursor() cur.execute(...) con.commit() #other stuffs What should I choose using a single connection or multiple one for every function. I don't want to make it crash if two requests are made at the same it and make it synchronised too. What's actually a good way? Thanks! -
alueError: Cannot assign value-field-must-be-a-object-instance
I get the following error ValueError: Cannot assign "(<UserProfile: testUser>, True)": "Comments.profileInfo" must be a "UserProfile" instance. What I am doing is unit testing : def create_user_profile(user): profile = UserProfile.objects.update_or_create(gender = 'F', defaults={ 'user': user}) return profile def create_comment(profile, cat): comment, __ = Comments.objects.update_or_create( defaults= {'profileInfo' : profile, 'category' : cat} ) return comment class CommentsFeature(TestCase): def setUp(self): self.user = create_user("testUser", "testPassword") login = self.client.login(username='testUser', password='testPassword') self.profile = create_user_profile(self.user) self.comment = create_comment(self.profile, self.cat) Model Code: class Comments(models.Model): profileInfo = models.ForeignKey(UserProfile, on_delete=models.CASCADE) class UserProfile(models.Model): GENDER_CHOICES = ( ('F', 'Female'), ('M', 'Male'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) dob = models.DateField(blank=True, null=True) facebook = models.BooleanField(default = False) # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User, on_delete=models.CASCADE) website = models.URLField(default = "", blank = True) picture = models.ImageField(upload_to='profile_images', default="", blank = True) def __str__(self): return self.user.username The error is coming from the set up function only. My test cases are returning this error Traceback (most recent call last): File "C:\Users\nikhi\Workspace_backup\Rango_Project\rango\tests.py", line 187, in setUp self.comment = create_comment(self.profile, self.cat) File "C:\Users\nikhi\Workspace_backup\Rango_Project\rango\tests.py", line 53, in create_comment 'category' : cat} -
Django - Able to makemigrations and migrate locally but not on Heroku
There seems to be a problem with migrating my models on the Heroku server. I am able to run python manage.py makemigrations and python manage.py migrate just fine and I am able to view my site on my local machine (SQLite), but when I try to run migrations on Heroku (PostgreSQL) I get the following error: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute remote: return self.cursor.execute(sql, params) remote: psycopg2.errors.UndefinedTable: relation "portfolio_category" does not exist remote: LINE 1: ...ategory"."name", "portfolio_category"."name" FROM "portfolio... remote: ^ remote: remote: remote: The above exception was the direct cause of the following exception: remote: remote: Traceback (most recent call last): remote: File "/app/manage.py", line 22, in <module> remote: main() remote: File "/app/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped remote: res = handle_func(*args, **kwargs) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 75, in handle remote: self.check(databases=[database]) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check remote: all_issues = checks.run_checks( … -
Django test field that slug is created from
I'm trying to write a test for UpdateView of Model which has a title and slug. When I try to test my view I can't recive a response because save method throws an ERROR Reverse for 'books-delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<slug>[^/]+)$'] I understand that slug can not be empty and that's what I try to test. So step by step: MODEL from django.utils.text import slugify class Book(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=120, unique=True, blank=True) def __str__(self) -> str: return f'{self.title}' def save(self, *args, **kwargs): self.slug = slugify(self.title) return super().save(*args, **kwargs) TEST class BookUpdateTest(TestCase): def test_book_must_have_title(self): """Create book object and updates fields with wrong data""" book = Book.objects.create(title='Camera Work 2') response = self.client.post( reverse('books-update', kwargs={'slug': book.slug}), {'title': '',}) self.assertEqual(response.status_code, 200) How the test for title field should look like? -
Distribution of Django based application [closed]
I want to distribute a Django based application to run on customer's intranet. I want to give a simple way to install the application, one script or tgz to install everything needed, including a http server and a database. What is the right way to do that? -
dynamically update html content and get the file content as a string in Django rest framework
I am doing the back-end side of a web application using Django rest-framework and PostgreSQL as database. I have an html file. I need to change some field values of the html based on the data getting from front-end and need to pass the html contend to another API as a sting. Please help me to find a proper solution. -
How to use async Django views without sleep?
I'm working on a Django view where I have two time-consuming operations that could be run in parallel (reads from a remote DB). I have created an async view but, presumably because I have no sleep statements, my code is still executing sequentially. If I understand correctly, Python code will always be executed sequentially until it finds some statement that allows it to pause and go execute the other task. I understand that sleep is one of these statements, but what are the others? The documentation and every single tutorial I found uses sleep statements in literally ALL of their examples. It almost seems like the only way to make code run async is to use a sleep statement, but that seems weird because sleep makes my code pause and do nothing, which can't be suitable for production. Here's some code that runs asynchronously: import time import asyncio from django.http import HttpResponse async def func1(n): print("Running func1...") for i in range(n): await asyncio.sleep(1) print("Done with func1!") return n async def func2(n): print("Running func2...") for i in range(n): await asyncio.sleep(1) print("Done with func2!") return n async def myview(request): print("Running myview...") start = time.time() res1, res2 = await asyncio.gather(func1(3), func2(4)) duration = … -
Django group by foreign key and return its object
I need some help with django orm. I have an EvaluationScore model and a Category Model class EvaluationScore(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) score = models.FloatField(null=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, db_column='id_category') class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=100) What I want to do is to query EvaluationScore and return the average by category. So I did something like this EvaluationScore.objects.values('category').annotate(Avg('score')) The problem is that it returns a dict like this for every gategory {'category': UUID('67a56798-24da-4800-af15-79b9839a3f84'), 'score__avg': 28.166666666666668} What I need is the category object, not only the UUID. Is there a way to do so? -
Show only "Reorder" item
I am using Django and in the front end, I am trying to show only "Reorder" Parts on the table. To define the status of Available and Reorder, I am normally using the if-else method to track. I was thinking about filtering but I have no such Status field in my DB. Anyone can give me any idea how to do that? Here is what I've done for now HTML <tr> <th class="serial">#</th> <th>Part No</th> <th>Part Name</th> <th>Quantity</th> <th>Status</th> <th>Date</th> <th>Action</th> </tr> {% if parts %} {% for part in parts %} <tr> <td class="serial">{{ forloop.counter }}</td> <td>{{ part.partno }}</td> <td>{{ part.partname }}</td> <td>{{ part.quan }}</td> <td> {% if part.quan <= part.limit %} <p style="color: #FF0000"> Reorder </p> {% elif part.quan > part.limit %} <p style="color:#008000"> Available </p> {% endif %} </td> <td>{{ part.created_date }}</td> </tr> Part Table -
Django: Create objects from list of inequal dicts
Is there a way to call MODEL.objects.create() and map values from a list of dicts with inequal keys? Usually, I would write some IF statements but that might result in a lot of most the same code. Example code: accounts = [ {'name': 'A', 'age': 18, 'food': 'pizza'}, {'name': 'B', 'age': 20, 'shoe': 'adidas'}, ] for a in accounts: Account.objects.create( name=a['name'], age=a['age'], food=a['food'], # SET ONLY IF IN DICT OTHERWISE TAKE DEFAULT shoe=a['shoe'] # SET ONLY IF IN DICT OTHERWISE TAKE DEFAULT ) -
How to use Light Select2Widget instead of ModelSelect2Widget for foreign key with django-select2
In my django app I have a CenterModel with a CenterType field (foreigm key). I am using django-select2 ModelSelect2Widget to represent CenterType in the form. With ModelSelect2Widget the data is NOT pre-rendered onto the page, So i have to start typing in the search box before I would be able to see the CenterTypes names in the select2 widget. Since there are not too many Center types is there any way to pre-render all the options onto the page so I can see the widget like this image As you can see all the options are available from the begining. I dont need to type anything to see the options I want the widget for Center type to look that way class CenterModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, unique=True,blank=False, null=False) center_type_id = models.ForeignKey("CenterTypeModel", verbose_name=_("Tipo"), blank=True, null=True, on_delete=models.SET_NULL, related_name="centers") class CenterTypeModel(models.Model): name = models.CharField(verbose_name=_("Nombre"),unique=True, max_length=50, blank=False, null=False) description = models.TextField( verbose_name=_("Descripción"),max_length=500, blank=True, null=True) #TODO saber si esto debe ser unico def __str__(self): return self.name from django_select2.forms import ModelSelect2Widget class CenterForm(forms.ModelForm): class Meta: model = CenterModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'center_type_id' : ModelSelect2Widget(model=CenterTypeModel, queryset=CenterTypeModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;'}), -
Is there a way we can create Django JWT access token and refresh token by using our own auth models (no inbuilt user model), from inside the views?
I want to authenticate the user to a third party website and then only issue a token. So I need to create both the access token and the refresh tokens manually from the views, without using any inbuilt user models. How to do that? -
Write properly appointment system with availabilities
My aim is to create an appointment system in Django able to create appointment between teachers and student with the possibility for teachers to choose their availabilities and for student to choose time slots according to teacher's availabilities. There are 2 classes : One is the class with the teacher's availabilities: the foreign key is the teacher and there are also the date and the start time and end time One is the class appointment with 2 foreign keys for both student and teacher But now how to withdraw an time slot availability in the teacher's class availabilities to not allow student to ask an appointment at the same time ? -
How do i change size of runcatewords_html in django template?
I have used truncatewords_html|90 for the truncate paragraphs. I want to change the size of truncatewords_html to 50 in mobile mode. How do I do it? {{ student.description|safe|truncatewords_html:90 }} in desktop mode {{ student.description|safe|truncatewords_html:90 }} in mobile mode -
django-auditlog not working for User model
I am using django-auditlog for creating entries in LogEntry table. my actions for User Model are not getting logged in LogEntry table. my User model - class User(AbstractUser): ... ... ... username = None USERNAME_FIELD = 'id' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return f"{self.email}" ... ... auditlog.register(User) *I have to use django-auditlog only so pls suggest accordigly TIA -
React rendered components from Django doesn't show after reloading
I have a Django project that emits Javascript(ReactJS) to the browser as frontend. It's an SSR app -- Django renders a view with a template that loads a React script. Everything works just fine except when I go to a different page(React component routed with React-router) and reload the browser. The Django server routes the URL to a pattern that doesn't exist in URLconf, hence the interference with react components that result in a Django 404 error. Is there a workaround to solve this? PS: I chose this method rather than the decoupled method for compatibility and testing purposes. Below are the essential parts that relate the issue: Backend urls.py from django.urls import path from frontend import views urlpatterns = [ path("", views.react_template, name="react_template"), ] views.py from django.shortcuts import render def react_template(request): return render(request, "template.html", {"title": "Chatter"}) template from django.urls import path from frontend import views urlpatterns = [ path("", views.react_template, name="react_template"), ] Frontend App.js import React, { useEffect, Fragment } from "react"; import ReactDOM from "react-dom"; import webSocketInstance from "../utils/websocket"; import PrivateRoute from "../utils/privateRoute"; // ... import Chat from "./chat/chat"; import CreateRoom from "./chat/room"; import { BrowserRouter, Switch, Route, Link } from "react-router-dom"; export default function App() { return … -
how to save all item of cart in model order single field instead of creating creating ever item other field
i want to fetch all the item in a single model field instead of creating spreat field for every item my models.py class Order(models.Model): status_choices = ( (1, 'PENDING'), (2, 'CONFIRMED'), (3, 'PACKED'), (4, 'SHIPPED'), (5, 'IN WAY'), (6, 'ARRIVED DESTINATION'), (7, 'RECIEVED'), (8, 'COMPLETED') ) payment_status_choices = ( (1, 'SUCCESS'), (2, 'FAILURE' ), (3, 'PENDING'), ) user = models.ForeignKey(User, on_delete=models.CASCADE,) item = models.ForeignKey(Item, on_delete=models.CASCADE ) status = models.IntegerField(choices = status_choices, default=1) method = models.CharField(max_length=50, blank=False,) size = models.CharField(max_length=20, blank=False) price = models.FloatField(blank=False) created_at = models.DateField(auto_now=True, editable=False) payment_status = models.IntegerField(choices = payment_status_choices, default=3) order_id = models.CharField(unique=True, max_length=200, null=True, blank=True, default=None) datetime_of_payment = models.DateTimeField(default=timezone.now) def placeorder(self): self.save() def __str__(self): return self.user.username my views.py for saving the form not using modelform class Checkout(View): def post (self, request,): user = request.user address = Address.objects.filter(user=request.user, default=True) cart = request.session.get('cart') items = Item.get_items_by_id(list(cart.keys())) prefer = request.POST.get('payment') for item in items: order = Order(user=user, item=items, method=prefer, size=cart.get(str(item.id)), price=item.price) order.save() request.session['cart'] = {} return redirect('transactions:cart',) what i want to save all the product id which are in cart and in single field after clicking checkout and his total price in place of price and its all size in place of size but right now it does creating … -
How can I only change the fields attribute in inherited serializer class in DRF?
I have a serializer as:- class SuperUserListSerializer(serializers.Modelserializer): class Meta: model = User fields = ( 'id', 'username', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'birth_date', 'is_active', 'is_staff', 'is_superuser', 'groups', ) I want to remove some of the fields from this serializers, so what I did, rewrote the Meta class and gave the serializer appropriate required fields:- class UserListSerializer(SuperUserListSerializer): class Meta: model = User fields = ( 'id', 'username', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'birth_date', 'is_active', 'groups', ) I am not satisfied by this approach, Is there any way I can do, so that I am not required to re-introduce the Meta class, and pass/change the appropriate fields for the second serializer -
In javascript Event source response error occurs while publish data
I am trying to publish some data.Js throws this error. EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.