Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) # … -
BUG: When passing django.messages variable through HTML tag
messages.info(request, 'Attendance Ready To Be Taken!') Over here i use django messages to send a string to the user {% for message in messages %} {% if message == 'Attendance Ready To Be Taken!' %} <div class="alert success"> <span class="closebtn">&times;</span> <strong>SUCCESS!</strong> {{message}} </div> {% else %} <div class="alert"> <span class="closebtn">&times;</span> <strong>WARNING!</strong> {{message}} </div> {% endif %} {% endfor %} However, although the string is clearly the same..it doesn’t output SUCCESS message. It can display the message indeed..but I want to filter if it’s a success message to be green..and error message to be red..just for user interface to warn users .alert { padding: 20px; background-color: #f44336; color: white; opacity: 1; transition: opacity 0.6s; margin-bottom: 15px; } .alert.success {background-color: #04AA6D;} Above is the CSS code for the two messages' styles for your reference. The message “Attendance ready to be taken” should be showing green..but it’s red color in the webpage. So I guess it didn’t fulfill the conditional 'if' statement. That’s why it goes to 'else', and becomes red color. But im not sure why it doesn’t. Because the message displayed is the same thing as the string i compared it with.. Does anyone know what's causing this weird bug? Any … -
Add SSL to AWS elastic beanstalk public DNS
I'm deploying django4 on AWS elastic beanstalk(EB), and currently trying to add SSL to the public domain provided by AWS. Is it actually possible to add SSL to EB's public domain? I know that certbot requires domain name, but does EB's public domain considered good enough? I tried to use certbot but it failed. Has anybody tried this? -
Set value of annotate field from another related child value
I want to add extra field which with value from 2nd level of related model. the probelem is because the first level is one to many. example Models: class ModelA(BaseModel): name=models.CharField() class ModelB(BaseModel): type=models.CharField(max_length=100, unique=True) #the value will be one of [x, y, z] parent = models.ForeignKey('ModelA', related_name='related_models') class ModelC(BaseModel): ext = models.CharField(max_length=100, unique=True) model_b = models.ForeignKey('ModelB', related_name='modelc') example values of models modelA = [ {'id': 1,'name': 'data1'}, {'id': 2,'name': 'data2'}, {'id': 3,'name': 'data3'}, {'id': 4,'name': 'data4'} ] modelB = [ {'id': 1,'type': 'y', 'parent_id': 1}, {'id': 2,'type': 'z', 'parent_id': 1}, {'id': 3,'type': 'x', 'parent_id': 3}, {'id': 4,'type': 'z', 'parent_id': 3}, {'id': 5,'type': 'z', 'parent_id': 2}, ] modelC = [ {'id': 1, 'ext': 'juststr#1', 'model_b_id': 2}, {'id': 2, 'ext': 'juststr#2', 'model_b_id': 4}, ] expected output: [ {'id': 1,'name': 'data1', 'mc_status': True}, {'id': 2,'name': 'data2', 'mc_status': False}, {'id': 3,'name': 'data3', 'mc_status': True}, {'id': 4,'name': 'data4', 'mc_status': False} ] I've tried: model_a = model_a.annotate( mc_status=Case( When( Q('related_models__type'='z', 'related_models__modelc__isnull'=False), then=True ), default=Value(False), output_field=BooleanField() ) ) #wrrong result :( -
How to inner join multi tables or merge multi serializers in Django?
i have this code here for the models: class Users(models.Model): first_name = models.CharField(max_length=32, blank=True, null=True) last_name = models.CharField(max_length=32, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) class Images(models.Model): user= models.ForeignKey(Users, on_delete=models.RESTRICT) encoded_pic = models.JSONField( encoder=None, default=dict, blank=True, null=True) pic_thumbnail_path = models.CharField(max_length=222, blank=True, null=True) class WorkingDays(models.Model): user= models.ForeignKey(Users, on_delete=models.RESTRICT) day = models.DateField(blank=True, null=True) enter_time = models.DateTimeField(blank=True, null=True) exit_time = models.CharField(max_length=32, blank=True, null=True) class Departments(models.Model): user= models.ForeignKey(Users, on_delete=models.RESTRICT) department_name = models.CharField(max_length=32, blank=True, null=True) These are the serializers: class UserssSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' class ImagesSerializer(serializers.ModelSerializer): class Meta: model = Images fields = '__all__' class WorkingDaysSerializer(serializers.ModelSerializer): class Meta: model = WorkingDays fields = '__all__' class DepartmentsSerializer(serializers.ModelSerializer): class Meta: model = WorkingDays fields = '__all__' I tried this code but it only returns the images fields not the others data=Images.objects.filter(user_id__workingdays=pk).values() What i want to do is to inner join images, workingdays and departments table using user_id field also is there away to merge serializers of all these 3 tables to make the serializer returns all the fields from all the 3 tables? -
Nginx server does not recognize static Django files
I'm setting up an AWS server and I finished the tutorial provided by DigitalOcean, however my server doesn't recognize my static files and displays a page with styles only via CDN (Tailwind) Nginx Configuration: server { listen 80; server_name xxxxxxxxxxxxx; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubuntu/Filmes/static; } location /media { root /home/ubuntu/Filmes; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } My project settings.py: import os STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR / "static") Structure when running python manage.py collectstatic: - static |------ admin |------ css |------ images |------ js |------ staticfiles.json Tutorial:https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 -
generic createview and django form only rendering a button in a template
I have encountered a funny challenge, as am building some apps where they want track some expenses and revenues profits ... I used generic views to create and get details and delete, all work fine with expenses, but I copied the same code and I used it for revenues from expenses you can't imagine this view is rendering a button only yet it has a form, NOTE SAME CODE WORK WELL ON EXPENSES. I even exchanged templates but it kept rendering the former content even after changing the template. it doesn't matter what's in the template the view just renders the same thing even when I remove the form, even when I put pass. class AccountsRevenueCreate(CreateView): template_name='dashboard/expense_create.html' model= AccountsExpense success_url = reverse_lazy('dashboard:expenses') form_class=AccountsExpenseForm and the form class AccountsRevenueForm(forms.ModelForm): class Meta: model = AccountsRevenue fields = '__all__' and in the template <div class="row"> <div class="col-12"> <h5 class="form-title"><span>revenue Update </span></h5> </div> <form method="post", action="{% url 'dashboard:revenue_add' %}"> {% csrf_token %} {% comment %} {{ form|crispy }} {% endcomment %} {{ form.as_p }} <button type="submit" class="btn btn-primary col-12 col-sm-12">Save </button> </form> </div> and the URLs path ('accounts/revenues/create/', AccountsRevenueCreate.as_view(), name='revenue_create'), I have chosen to show you only where the problem is not paste unnecessary … -
Django Template Variables to Javascript File
Currently I have my Django project set up so that the JS variables that depend on template variables are first defined under a script tag in the HTML template. Then, when the template runs, the JS variable gets created and added to the Javascript context, causing other external JS scripts to be able to use said variable without declaring it anywhere. Html template: <body> content </body> <script> const var = "{{ my_template_var }}"; </script> <script type="module" src="{% url 'app_name/index.js' %}"></script> JS Script (app_name/index.js) console.log(var) // Prints value of "my_template_var" in the form of a string However, I dont like the fact that the var variable in the JS script just "magically" has the value defined in the template when it runs (there's no actual statement saying const var = something). Is there any way that I can include a declaration in my JS file (not a comment) so that its a bit clearer to the rest of the developers from where the variable is coming from? (NOTE: I'm mainly doing this as well because when using Typescript, those variables appear as undefined, even though they are receiving a value from somewhere) -
Suitescript url.resolveTaskLink and line breaks
I am using url.resolveTaskLink to convert a custom record to a sales order. On the custom record there is a text area field where there a line breaks but when I convert it over to a sales order - instead of performing the line breaks I am getting a tag. I tried using replace like this but it did not work: var fixpuaddress = puaddress.replace(/&lt;br&gt;/g," "); How can I have it do the actual carriage return? -
I want to access the files inside the zip file and send it back to Django backend
I want to access the file extracted from a zip file and post it to the database, this code is for extracting the files, I don't know how to access the files: var reader = new FileReader(); reader.onload = function (ev) { JSZip.loadAsync(ev.target.result).then(function (zip) { var zipfile_names = new Array(); var shpfile_names = new Array(); var BreakException = {}; var allFiles = new Array(); try { zip.forEach(function (relativePath, zipEntry) { $("#div1").hide(); document.getElementById("div2").hidden = false; $("#div2").show(); //CONTROL THAT FILE EXTENSIONS ARE ALL SHAPEFILE VALID var allowed_shp_extensions = ['shp', 'shx', 'dbf', 'sbn', 'sbx', 'fbn', 'fbx', 'ain', 'aih', 'atx', 'ixs', 'mxs', 'prj', 'xml', 'cpg'] var shpext = ['shp'] // check the zipEntry is a file if ((zipEntry.name.includes('.') == true) && (zipEntry.dir == false)) { var split_filename = zipEntry.name.split('.') if (allowed_shp_extensions.includes(split_filename[split_filename.length - 1]) == true) { var name_extract = zipEntry.name.replace(/^.*[\\\/]/, '') zipfile_names.push(name_extract) } allFiles.push(zipEntry.name); };});``` -
Profile table not being created for extended User model in django
I am facing this problem in django where even though there is a Profile model in my models.py file which extends the django User model still on running the 'makemigration' and 'migrate' commands the Profile table is not being generated in database. This is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) clg_name = models.CharField(max_length=200) class Student(models.Model): name = models.CharField(max_length=100, blank=False) enrollment_number = models.IntegerField(unique=True, null=True, blank=False) clg_name = models.CharField(max_length=200, blank=False) program_name = models.CharField(max_length=30, blank=False) class Result(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) sem = models.IntegerField() exam_name = models.CharField(max_length=30) percnt = models.FloatField(null=True) cgpa = models.FloatField(null=True) class Marks(models.Model): result = models.ForeignKey(Result, on_delete=models.CASCADE) course_name = models.CharField(max_length=100, null=True) course_code = models.IntegerField(null=True) course_credit = models.IntegerField(null=True) grade = models.FloatField(null=True) Here is the output of py manage.py makemigration account: Migrations for 'account': account\migrations\0001_initial.py - Create model Result - Create model Profile - Create model Marks And this is the output of py manage.py migrate: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions Running migrations: No migrations to apply.