Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using KMeans adding it to my django app python
I have a general and basic understanding of how the K-Means algorithm works. My problem revolves around connecting people with similar interests which is represented in features that will be used during clustering. Having done that before on files like a csv and txt, how would I go about adding it to my Django app to have it run every time an event occurs, like someone outside the cluster likes another's post. -
Format Django rendered date string dates into YYYY-MM-DD format
When we pass date object in django view and render in html, it outputs in below format. 'Oct. 7, 2022', 'Sept. 9, 2022', 'Aug. 12, 2022', 'July 15, 2022', 'June 17, 2022', 'May 20, 2022', 'April 22, 2022', 'March 25, 2022', 'Feb. 25, 2022', 'Jan. 28, 2022', 'Dec. 31, 2021', 'Feb. 11, 2022', 'Nov. 5, 2021' This is example of how each month looks like. I want to convert it into YYYY-MM-DD format. I am using below approach which is working version but I am looking for optimized code for the same. import re import datetime date_value = 'Sept. 9, 2022' date_value = re.split("[., ]", date_value) date_value[0] = date_value[0][:3] date_value = ' '.join(date_value) date_value = datetime.datetime.strptime(date_value, '%b %d %Y').strftime('%Y-%m-%d') print(date_value) >> 2022-09-09 Is there any other way to directly convert it into this format? This question is not about formatting django date like date_value |date:"Y-M-d" on UI. Rather I am looking to do in python backend. Thanks in advance! -
How to sign-in with LDAP using django-allauth login page
We use django-allauth for authentication. And we want to use django-auth-ldap. Currently, we can login with LDAP from the default django sign-in page (/admin). We learned that this should be done with the DefaultAccountAdapter in the django-allauth package. How can we login with LDAP information using django-allauth sign-in page? # project/settings.py: ACCOUNT_ADAPTER = 'project.users.adapter.CustomAccountAdapter' # project/users/adapter.py: from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter class CustomAccountAdapter(DefaultAccountAdapter): ... -
Django: How to create a model that contains a foreign key with CreateView?
If possible, I want to make a model that includes the foreign key with class-based CreateView. I know it can be done using a function. models.py class Pizza(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return "/pizzas" class Topping(models.Model): pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse("pizza", kwargs={"pizza_id": self.pizza.pk}) views.py class NewTopping(CreateView): model = Topping template_name = "pizzas/new_topping.html" form_class = ToppingForm urls.py path("topping/<pk>/create",views.NewTopping.as_view(),name="new_topping") I've tried to do it like this, but I get an integrity error when I try to save the new instance: NOT NULL constraint failed: pizzas_topping.pizza_id -
How to raise error from custom save method in django?
I have defined a custom save method. In this method i want to raise some error if one of the field is empty. def save(self, *args, **kwargs): # do some operation and end up getting self.iot_boxes # this model field (iot_boxes) can be a list full of values or an empty list logger.info(f"Selected IOT boxes to be updated {self.iot_boxes}") super().save(*args, **kwargs) Initially iot_boxes may or may not be empty or after some operation it can end up empty during operation in the save() method. How can i display some kind of error on the admin page when the self.iot_boxes comes out as empty. -
Best ways deal with large data on backend django?
I know this is a broad question that is kinda difficult to understand. But I couldn't get answers by googling. I have a large amount of data from more than 100 000 users. The data is about purchases, shipping, user invites, and so on. Overall, it is quite big and almost all models in my Django backend have foreign keys to each other. When sorting users I have to access the database for each user, which takes around 30 seconds to sort. So, instead, I am caching all user-related data in Redis(refreshing it once a day) and sorting them on request (without accessing the database, jut using what is in the cache), which reduced the time to ~1.5sec. If someone knows a better way to deal with it, can you please share it? -
Warning when installing Tailwind in Django
To have tailwind in my django project I'm trying to crete an output.css file using: npx tailwindcss -i ./static/src/input.css -o ./static/dist/output.css --watch and I'm getting these warnings: warn - The `content` option in your Tailwind CSS configuration is missing or empty. warn - Configure your content sources or your generated CSS will be missing styles. warn - https://tailwindcss.com/docs/content-configuration If I get it correct the problem seems to be my tailwind.config.js and maybe I did not set the path correctly. This is my tailwind.config.js file: module.exports = { content: [ './templates/**/*.html' ], theme: { extend: {}, }, plugins: [], } This is my django's project structure: - website -- main -- app1 -- static --- src --- dist --- node_modules --- tailwind.config.js -- templates --- assets ---- base.html --- main ---- index.html --- app1 -- website --- setting.py this is my input.css file: /* static/src/input.css */ @tailwind base; @tailwind components; @tailwind utilities; What am I doing wrong? -
django.core.exceptions.ValidationError: ['“<django.db.models.fields.DecimalField>” value must be a decimal number.']
I have a decimal field in django models, it never shown any error till today when I added new field with decimalfield, why is that issue? -
Django task to created objects in database systematically failed on the first record
I use Django (2.2.5), Docker, celery and Postgresql database. I have write a celery task that query database first, create a dataframe with results of the query and update_or_create objects in databases based on this dataframe. code simplified # load queries definition queries = dcf_queries_definitions() # this line query the database # print(queries) if not queries.empty: for index, row in queries.iterrows(): # multiple call to api of another app to look for missing data # return **df** dataframe that will be used to create objects in database records = df.to_dict(orient='records') for record in records: try: DataCorrectionForm.objects.create( dcf_ide=record['dcf_ide'], category=record['category'], crf=record['crf'], crf_ide=record['crf_ide'], patient=record['patient'], record_date=record['record_date'], field_name=record['field_name'], field_label=record['field_label'], message=record['message'], field_value=record['field_value'], dcf_status=record['dcf_status'], query_id=record['query_id'], deactivated=record['deactivated'], comments=record['comments'] ) except Exception as e: print(record) print('Exception raised when trying to update object',e) continue But I have a OperationalError that systematically raised on the first objects to be created or updated. The message in not very explicit for me. OperationalError('server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n') I controlled data I try to insert in the model and there is no problem. If I upload the same datas from a csv file to insert in my database, there is no problem. I … -
Form Wizard || adding multiple persons in one of the steps
I am using Form Wizard in Django. My form is okay the problem is adding multiple person details in the form. There is a button on the HTML to add person. If it is click there is a drop down. For now the code works for adding one person only. Is there a way that you can repeat the step in FormWizard if the user wants to add many people? Do I need to save it in session? Thank you HTML {% extends "incident_report_home.html" %} {% block form_if %}{% block form_else %} {% csrf_token %} <fieldset> {% comment %} <legend>Title</legend> {% endcomment %} <div> {% comment %} <label>{{ form.field.label }}:<p class="note">{{ form.field.help_text }}</p></label> <hr> {% endcomment %} <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapsePeople" aria-expanded="false" aria-controls="collapsePeople"> <i class='bx bx-plus'></i> Add Person </button> <div class="collapse pt-4" id="collapsePeople"> <form> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputFirstName">First Name</label> {{form.incident_first_name}} </div> <div class="form-group col-md-4"> <label for="inputMiddleName">Middle Name</label> {{form.incident_middle_name}} </div> <div class="form-group col-md-4"> <label for="inputLastName">Last Name</label> {{form.incident_last_name}} </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputAge">Age</label> {{form.incident_age}} </div> <div class="form-group col-md-4"> <label for="inputGender">Gender</label> {{form.incident_gender}} </div> </div> <div class="form-group"> <label for="inputAddress">Address</label> {{form.incident_address}} </div> <!-- ================================= --> <hr> <div class="form-row"> <div class="form-group col-md-4"> <label for="inputInvolvement">Involvement</label> {{form.incident_involvement}} </div> <div … -
How to get the url name from a django url path?
In my view i export the main_url_patterns from my app and i want to process this list to get two parts in a different lists: URL path URL name So in my view i do something like that: def siteurls_view(request): path_list=urls.main_urlpatterns url_list=[] for p in path_list: print(p, type(p),p[0]) Where urls.main_urlpatterns is: path('consumptions_points/send/', views.send_consumptions_points_view, name='send_consumptions_points'), path('consumptions/', views.consumptions_view, name='consumptions'), path('consumptions/new/', views.consumptions_new_view, name='consumptions_new'), path('consumptions/get_tx/', views.get_tx_consumption_view, name='get_tx_consumption'), path('consumptions/send/', views.send_consumptions_view, name='send_consumptions') So i would like to get for example all names from the path and insert them into a new list. Many thanks -
Django form is not submitted to the database
I am writing a Django website for dentists, the dentist can register patients with form easily not an issue, however when registering visits for a patient it is not saved, in the admin panel both models works just fine, on the website the visits form dose not save to database. models.py from django.db import models class Paitent(models.Model): pname = models.CharField(max_length=50) age = models.IntegerField() gender = models.CharField(max_length=50) address = models.CharField(max_length=50) telephone = models.IntegerField() mHistory = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.pname class Visit(models.Model): paitent = models.ForeignKey(Paitent,null=True ,on_delete=models.CASCADE, blank=True) toothNumber = models.CharField('involved tooth', max_length=120) cComplaint = models.CharField('chief complaint',max_length=120) sASymptoms = models.CharField('signs and symptoms',max_length=120) diagnosis = models.CharField(max_length=120) procedure = models.CharField(max_length=120) notes = models.TextField(blank=True) currentVisit = models.DateTimeField( 'time and date of current visit', null=True) nextAppointment = models.DateTimeField() def __str__(self): return self.toothNumber forms.py from django import forms from .models import Paitent from .models import Visit class PaitentForm(forms.ModelForm): class Meta: model = Paitent fields = ['pname', 'age', 'gender', 'address', 'telephone'] class VisitForm(forms.ModelForm): class Meta: model = Visit fields = ['paitent', 'toothNumber', 'cComplaint', 'sASymptoms', 'diagnosis', 'procedure', 'notes', 'currentVisit', 'nextAppointment'] views.py from django.shortcuts import render from .models import Paitent from .models import Visit from .forms import PaitentForm from .forms import VisitForm import calendar from calendar import HTMLCalendar … -
Hi, I am having an working NLP (spacy) model in jupyter. i need to add this model to django backend
Hi, My spacy model format is looks like this how can i add this model to django backend and this is my spacy model, how can i add this to django backend? -
How to create an object in Django Rest Framework that is related to other models
I have 3 models: user, barber and booking. In my createBooking view, I am having trouble to figure out how to pass the IDs of the user and the barber. Here's my code: The view: def createBooking(request): data = request.data booking = Booking.objects.create( barber_id = data['barberb_id'], customer_id = data[ 'customer_id'], timeslot = data['timeslot'], ) serializer = BookingSerializer(booking, many=False) return Response(serializer.data) The booking model: customer_id = models.ForeignKey(User, on_delete = models.CASCADE,) barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE) timeslot = models.DateTimeField('appointment') def __str__(self): return f"{self.customer_id} {self.barber_id} {self.timeslot}" With the current code, I'm getting the error Cannot assign "['customer_id']": "Booking.customer_id" must be a "User" instance. -
Django Migration issue when we are adding new column to the auth.Group table
We had a CustomUser model in our application and I am trying to add two new columns to the existing auth.Group table as below. Group.add_to_class('source', models.CharField(max_length=255, default='XXXXXXX')) Group.add_to_class('tags', TaggableManager(blank=True)) When we try to execute python manage.py makemigrations. Its throwing an error saying inconsistent of migration history. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration customuser.0001_initial is applied before its dependency auth.0013_group_source_group_tags on database 'default'. Need suggestion on the same. How do we handle migrations in such situation. We don't want to create new data base and migrate all the data everytime. -
How to fetch id with get method in django?
I have a model named WorkOut that stores all the data regarding workout sessions. LIke type of workout, reps, weights etc. There are 2 columns that I do not fill initially. I am trying to fill them with button clicks. Start time and end time. The idea is at the beginning of the set user will click a button and it will fill up the "start time" column with current time. At the end of the set they will click the other button to fill up the "end time" column. To achieve this I need to fetch the id for that specific object(row). If I have 10 sets of workout, I need to get the id for each specific row so when button is clicked only the column associated to that row is updated. It should be simple but I am struggling. This is how my attempt looks like- WorkOut.objects.get('id') I am running a for loop to display the entire model on the template. I checked by displaying all the id on my template, they are there. But the above code doesn't fetch individual id. When I know the id, I can go like this- WorkOut.objects.get(id=18) And sure enough it … -
Conversion of “where exists” SQL clause to Django ORM
I want to convert below PostgreSQL query into Django ORM. It would be great if someone can help me out here. Query: select U0.* from audit_audithistory U0 where exists ( select U2.historyId from (select Max(U1.id) as historyId from audit_audithistory U1 group by U1.group_uid, U1.record_identifier ) U2 where U0.id = U2.historyId ) Model: class AuditHistory(models.Model): model_name = models.ForeignKey(AuditHistoryConfigMaster, on_delete=models.CASCADE) record_identifier = models.JSONField(blank=False, default=dict) tenant_id = models.CharField(null=True, blank=True, max_length=500, verbose_name='Application Tenant ID') updated_fields = models.JSONField(blank=True, default=dict, verbose_name='Complete Current Record') modified_by = models.CharField(max_length=200, blank=False, null=False) group_uid = models.CharField(max_length=50, blank=False, null=False) created_dtm = models.DateTimeField(auto_now_add=True, blank=False, null=False) update_dtm = models.DateTimeField(auto_now=True, blank=False, null=False) -
I have a scenario in which I need to delete all the records in a table A (many2many) in which a particular site id has more than one record
Table A has following fields id role pizza_id topping_id. I want to delete all the records in of pizza_id which has more than one topping_id related to it, if the pizza_id has only one record with the topping id, the delete and replace with another value. Is this possible to execute with only one query using Case, When conditional operators in django ? -
How can I create an Azure Iot Device using Django Python?
I'm new using Azure Iot Hub and I want to create a device using python software. Is that possible? I have read some documentation, but I didn't get it exactly. Do you have any example code or more detailed documents? Like if I click a button the device will be created. -
Django generate custom cheque number
I'm new in django, I want to create custom Cart number that starts with #. When a new record comes into database. #1-1000, #1-1001, #1-9999, .... #2-1000, ...#2-9999 etc. This is my model class Cart(models.Model): # id = models.CharField(primary_key=True, editable=False, max_length=10) user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="cart") create_date = models.DateField(auto_now_add=True) cart_number = models.CharField(max_length=500, default=increment_cart_number, null=True, blank=True) total_summa = models.FloatField() time = models.TimeField(auto_now_add=True) The cart_number will be always in range 1000- 9999 so how can I do that with increment_cart_number function? -
Best way to read csv and xls files data and store into the database in Djnago
I just wanted to know which is the best module for reading the data from CSV and XLS file and store it into the database in Django, I know we can use Pandas and default csv module but is that any other common module which we can use? Thanks -
Problems when trying to save an image from react-native to a django model
I am writing my first react-native app with a django backend. for my app to work properly I need to send an image from the device's image library to the django server and then save it in the model. here's my code - react-native- const sendI = async (image) => { const formData = new FormData() let image_data = { uri : image.uri, name : image.fileName, type : image.type, } if (image != null){ await formData.append( 'image', image_data) await formData.append('name', usern) //await formData.append('name', 'a' ) console.log(formData) setSentI(formData) console.log('recieved') } console.log(image) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); // Explore the result console.log(result); if (!result.cancelled) { await setProfileImage(result); console.log(result.uri); sendI(result); } } const openCamera = async () => { // Ask the user for the permission to access the camera const permissionResult = await ImagePicker.requestCameraPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your camera!"); return; … -
Alternatives to insert a variable inside another variable in a Django Template
I have a dictionary in a django template that is showing as following: {1: 10.0, 2: 12.0} with the variable name of {{ dicts }} I can access the value of each key by the following: {{ dicts.1 }} or {{ dicts.2 }} In my django template I also have another variable showing as {{ b.order}}. My question: Since {{ b.order}} is a number how can I add this number to act as key value inside to be something like this {{ dicts.{{ b.order}} }} Obviosly this is not showing any results so I was wondering what is the alternative and I am avoiding forloops. -
Assign employee to user
I am a beginner in Django and trying to create a web application. In this case I want to assign an employee to a user. In the user form, the call is made to the employees who are active and who do not yet have assigned users. The problem is that when making the call and listing the employees on the screen, it does not bring me the name of the employee, it only brings me: Employee Object(8) My model(User) class User(AbstractUser): active = models.BooleanField(default=True) employee = models.OneToOneField(Employee,on_delete=models.CASCADE,null=True) def __str__ (self): return '{}'.format(self.username,self.groups,self.active,self.employee) My Form(User) class UserForm(UserCreationForm): username = forms.CharField(label="User", widget=forms.TextInput(attrs{"class":"formcontrol"})) groups = forms.ModelMultipleChoiceField(label="Rol",queryset=Group.objects.all(), widget=forms.CheckboxSelectMultiple,required=True) password1 = forms.PasswordInput(attrs={'class':'form-control'}) password2 = forms.PasswordInput(attrs={'class':'form-control'}) employee = forms.ModelChoiceField(queryset=Employee.objects.filter(user=None,active=True), widget=forms.Select(attrs={'class':'form-control'})) class Meta: model = User fields = [ "username", "password1", "password2", "groups", "employee", #"active", ] -
ValueError at /cart/add_cart/1/ The view carts.views.add_cart didn't return an HttpResponse object. It returned None instead. http://.cart/add_cart/1/
If I add a product to the cart once is fine and the carts are created. But if I add it again then the above error occurs. In addition, when trying to edit or delete the created cart, an error also occurs: "TypeError at /admin/carts/cartitem/3/change/ str returned non-string (type Product)" I have Django project with follow modules: Model Product from django.db import models from category.models import Category from django.shortcuts import reverse class Product(models.Model): product_name = models.CharField(max_length=256, unique=True) slug = models.SlugField(max_length=256, unique=True) description = models.TextField(max_length=512, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() #TODO: Автоматизация is_available = models.BooleanField(default=True) #TODO: Автоматизация category = models.ForeignKey(Category, on_delete=models.CASCADE) create_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def get_url(self): return reverse('store:product-detail', args=[self.category.slug, self.slug]) def __str__(self): return self.product_name Model Cart from django.db import models from store.models import Product class Cart(models.Model): cart_id = models.CharField(max_length=256, blank=True) date_added = models.DateField(auto_now_add=True) def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() is_active = models.BooleanField(default=True) def __str__(self): return self.product Carts views from django.shortcuts import render, redirect from store.models import Product from .models import Cart, CartItem def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) # …