Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If I need to sort objects by a sum of 2 fields, what is the most efficient way to do this [Django]
I have a class called LogSheet that looks like this: class LogSheet(models.Model): calls_logged = models.IntegerField(default=0) texts_logged = models.IntegerField(default=0) What would be the best way to get a queryset that is sorted by the calls_logged + texts_logged. Is there a way to index this query? -
Django write Q filter based on the Form elements
I would like to write django filter for the following scenario. CASE : I have 4 checkboxes box1, box2, box3, box4 and a submit button on my HTML page. I have written model post with 6 fieldd where 4 fields corresponds to box1,2,3,4. Based on the user input (4 checkboxes) it should filter the post. However does this mean i have to write 16 scenarios 4x4. or is it possible to formulate it in a better way. post.objects.filter(Q(id=1),Q(sid=1),Q(pid=1),Q(kid=1)) # case 1 post.objects.filter(Q(id=1),Q(sid=1)) post.objects.filter(Q(id=1),Q(kid=1)) post.objects.filter(Q(id=1),Q(pid=1)) post.objects.filter(Q(kid=1),Q(sid=1)) . . . post.objects.filter(Q(kid=1)) Is there a better way to do it? -
Rename Filter Label Model Admin Django
Is it possible to change this label in the list filter from model admin without creating a custom filter? I'm using the same table for 2 different fields and user needs to filter the table using both fields (separately or combining them). Without the rename in the Admin view will have 2 filters with same name applying to different fields. Not the best ux. -
how to filter users in admin panel?
I have a task form in my app. Django is informing owners that someone has sent a task and they need to assign a particular person to this task (by choosing user in column owner) from the admin panel. There can be only 1 person assigned to each task. My problem is that people who are assigning tasks can see the list of all users and I want to filter users in this dropdown list only to users that are in a group named "owners". Question Is there any way to filter users that are displayed in the dropdown list? models.py class TaskRquest(models.Model): title = models.CharField(max_length=1000, blank=True, null=True, default='') body = models.TextField('Description') priority = models.BooleanField(default=False, blank=True, null=True) publish_date = models.DateTimeField('publish', default=timezone.now) owner = models.OneToOneField(User, blank=True, null=True, on_delete=models.DO_NOTHING) admin.py class TaskRquestAdmin(ImportExportModelAdmin): list_display = ('title', 'publish_date', 'priority', 'owner') admin.site.register(TaskRquest, TaskRquestAdmin) -
I want more optimizing Django ORM
I have this model: class Actor(models.Model): act_id = models.AutoField(primary_key=True) act_name = models.CharField(max_length=125) act_gender = models.CharField(max_length=1) class Casting(models.Model): actor = models.ForeignKey('Actor', on_delete=models.CASCADE) movie = models.ForeignKey('product.Movie', on_delete=models.CASCADE) part = models.CharField(max_length=25, null=True) class Movie(TimeStampModel): mov_id = models.AutoField(primary_key=True) mov_title = models.CharField(max_length=200) director = models.ForeignKey('participant.Director', on_delete=models.CASCADE) I want this result: <QuerySet [{'actor_id__act_name': 'Dwayne Johnson', 'actor_id__act_id': 24}, {'actor_id__act_name': 'met smith', 'actor_id__act_id': 25}, {'actor_id__act_name': 'Will Smith', 'actor_id__act_id'__act_name': 'Vin Diesel', 'actor_id__act_id': 27}, {'actor_id__act_name': 'Chris Pratt', 'actor_id__act_id': 28}, {'actor_id__act_name': 'Ryan Reynolds', 'actor_id__act_id': 29}]> I wrote this code: Casting.objects.filter(movie_id=1).select_related('actor').values('actor_id__act_name', 'actor_id__act_id') I want to write an optimized ORM. Please suggest a better code. -
Test celery task with django
I´m trying test a celery task in my django project using the same database as django test. In my setup I have databases = '__all__' @classmethod def setUpClass(cls): super().setUpClass() # Start up celery worker cls.celery_worker = start_worker(app, perform_ping_check=False) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() # Close worker cls.celery_worker.__exit__(None, None, None) But i got psycopg2.InterfaceError: connection already closed when run cls.celery_worker.enter(). Somebody can help me? -
Using Class-Based Views with Function-Based Views together in Django
Is it possible to use Class-Based Views with Function-Based Views together in django project? If yes, Is that best practice ? Can I use them together in the same views.py -
Parent form not getting values from child form during child object initialization in Django
I created a basic form in django. class basicform(forms.Form): br = ((None,' '),('CSE','CSE'),('ECE','ECE'),('IT','IT')) se = ((None,' '),('M','Male'),('F','Female'),('O','Others')) secx = ((None,' '),('A','A'),('B','B'),('C','C'),('D','D')) roll_no = forms.CharField(required=False,label='Roll No:') name = forms.CharField(required=False,label='Name:') sex = forms.ChoiceField(required=False,choices=se,label='Gender:') branch = forms.ChoiceField(required=False,choices=br,label='Branch:') sec = forms.ChoiceField(required=False,choices=secx,label='Section:') i made another form class marks(basicform): s11 = forms.DecimalField(max_value=100,min_value=0) s12 = forms.DecimalField(max_value=100,min_value=0) s13 = forms.DecimalField(max_value=100,min_value=0) ...... def __init__(self,*args,**kwargs): super(marks,self).__init__(*args,**kwargs) self.fields['name'].disabled = True self.fields['roll_no'].disabled = True self.fields['sex'].disabled = True self.fields['branch'].disabled = True self.fields['sec'].disabled = True the issue is, i am taking post data from the base form, and i want that data to be assigned into the child (i.e. marks object) mark = marks(data = request.POST) this is what i'm trying to do. keep in mind the post data is from the base class(i.e. basicform), i'm under the assumption that the 'data' parameter would be passed onto the super class and therefore values would be assigned, but that is not the case. what am i doing wrong? def create(request): global form if request.method == 'POST': form = basicform(data = request.POST) if form.is_valid(): mark = marks(data = request.POST) mark.full_clean() print(form.cleaned_data) print(mark.cleaned_data) this is an excerpt from my view, here the print statements are for debugging and as i mentioned before, 'form' variable has the values … -
Django - Admin Area - I can't delete a user from users (User matching query does not exist.)
I created a Users app. In models i create a Profile and signals. In admin area i can create a new user end is created a Profile as well. When i delete the new user form Profile is also deleted from Users and is ok. But if i try to delete the new user from Users area i got error message: "DoesNotExist at /admin/auth/user/3/delete/ - User matching query does not exist". I dont know why ? Any suggestion ? I run and apply all the migrations and also i delete and create another database but is not solve this issue. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) username = models.CharField(max_length=200, blank=True, null=True) nume = models.CharField(max_length=200, blank=True, null=True) avatar = models.ImageField ( upload_to ='utilizatori/', default='utilizatori/avatar_profilearning.jpg', verbose_name='Avatar (320px * 320px)') departament = models.CharField(max_length=200, blank=True, null=True) functie = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) descriere = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/src/plugins/ckeditor_plugins/emojione/' , 'plugin.js', )], config_name='default') creat = models.DateTimeField(auto_now_add=True) #pentru a redimensiona rezolutia avatarului incarcat def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = Image.open(self.avatar.path) if img.height > 320 or img.width > … -
Azure IoT device loosing connection to transparent edge gateway device
I have an issue with a IoT device looses the connection to a transparent Azure IoT Edge gateway. I don't know where to start searching, therefore I'm a bit lost here. IoT Device I used the sample telemetry application (Python) and customized it to our needs. It connects to the Edge Device with MQTT over WS. Initially, it works great until the disconnect happens. SDK version is 2.11.0 IoT Edge I have setup an Azure IoT Edge device as transparent gateway. It is running the latest versions (1.2), installed on a Azure Linux VM. Problem When the script has been running for some time (e.g. 30 minutes) a connectivity issue appears. Exception caught in background thread. Unable to handle. ReconnectStage: DisconnectEvent received while in unexpected state - CONNECTING, Connected: False ['azure.iot.device.common.pipeline.pipeline_exceptions.OperationTimeout: Transport timeout on connection operation\n'] Traceback (most recent call last): File "C:\Users\foo\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\iot\device\iothub\aio\async_clients.py", line 33, in handle_result return await callback.completion() File "C:\Users\foo\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\iot\device\common\async_adapter.py", line 91, in completion return await self.future azure.iot.device.common.transport_exceptions.ConnectionDroppedError: transport disconnected The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\Development\machine-poc\python\telemetrysender.py", line 165, in <module> main() File "c:\Development\machine-poc\python\telemetrysender.py", line 76, in main send_telemetry_from_device(device_client, payload, i) File "c:\Development\machine-poc\python\telemetrysender.py", line 86, in send_telemetry_from_device … -
django:Model get all User except one user with his user id
Is there any method of django model.object to get all the users from User model except one user with his id? -
Django - Can I use one UpdateView to update fields on separate pages?
Let's say I have a Student model, with name and age fields, and I have a page with a DetailView class showing these fields. Let's say that rather than having one "update" button that will take me to a form to update all fields of my model at once, I want a separate button for each field that takes me to a separate page with a form to update it. I know how I could do this with a separate HTML file and separate UpdateView class for each field, but it seems like there should be a cleaner way. In the first HTML file I have two buttons: <a href="{% url 'update_name' pk=student.pk%}">Update name</a> <a href="{% url 'update_age' pk=student.pk%}">Update age</a> In the second I have the form: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> Urls: urlpatterns = [ path('<int:pk', views.StudentDetailView.as_view(), name="detail"), path('update_name/<int:pk>', views.StudentUpdateView.as_view(), name="update_name"), path('update_age/<int:pk>', views.StudentUpdateView.as_view(), name="update_age"), ] Views: class StudentUpdateView(UpdateView): model = models.Student template_name = 'update_student.html' I suppose I'm looking for some sort of if statement that I can put in my view, like: if condition: fields = ("name",) elif condition2: fields = ("age",) Hopefully this makes sense! Thank you for any help :) -
'no app installed with this label' error when creating an empty migration
WOrking on a django project, I had to split an app in two apps and move models from one app to the other. Now i want to move the data from the old table to the new one using the migrations. However, when i want to create an empty migration with "manage.py makemigrations --empty myapp" i have the error ==> 'no app installed with this label'. My new app is in the installed apps in settings. This is where the error occurs, when reading the settings. Has anyone a clue to help me solve my problem? -
Django: View and View-Test working against each other
right now I'm trying to test one of my really simple views - which is working totally fine - and receiving an error: Traceback (most recent call last): File "C:\Users\someone\Documents\django_tests\app\tests\test_views.py", line 42, in test_person_post ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000262BBE2CF10>>": "Person.created_from" must be a "CustomUser" instance. I've changed the default auth.user.model with AbstractUser and changed it into mail/password-, instead of username/password-combination. models.py: class Person(models.Model): GENDERS = ( ('-', '-'), ('Diverse', 'Diverse'), ('Female', 'Female'), ('Male', 'Male'), ) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) gender = models.CharField(max_length=10, null=False, blank=False, choices=GENDERS, default=GENDERS[0][1]) born = models.DateField(null=False, blank=False) adult = models.BooleanField(default=False) created_from = models.ForeignKey(USER, null=False, blank=False, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['last_name', 'first_name'] constraints = [ models.UniqueConstraint(fields=['last_name', 'first_name'], name="unique person constraint"), ] verbose_name = "Person" verbose_name_plural = "Persons" def get_absolute_url(self): return f"api/persons/{self.id}/" def __str__(self) -> str: return f"{self.first_name} {self.last_name}" forms.py: class PersonForm(ModelForm): class Meta: model = Person exclude = [ 'id', 'adult', 'created_from', 'created_date', 'updated_date', ] views.py: def index(request): form = PersonForm() if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): person = form.save(commit=False) person.created_from = request.user person.save() return redirect('index') context = {'form': form} return render(request, 'app/index.html', context) test_views.py: USER = get_user_model() class … -
Convert string to int before quering django ORM
I have a model class Entry(models.Model): maca = models.CharField(max_length=100, blank=True, null=True) This field will accept only numbers (cannot set char field to integer field for business reasons) Now I have to get all Entries that have maca greater than 90 What I'm trying to do is this: Entry.objects.filter(maca__gte=90) But gte isn't working because the maca is string How can I convert maca to int before filtering? or something like this? Thanks -
Add multiple real-time plots on the same page with Chart.js (Django)
i'm trying to add multiple real-time plots on the same page (Django framework) with Chart.js using websockets. When i try to add separate socket on the 2nd plot, the 1st freezes. Here is my code, thanks a lot. I'm sure there is a better way to write code, but I'm relatively new to js. <script> let socket =new WebSocket('ws://localhost:8000/ws/polData/'); socket.onopen =function(e){ alert('Connection established'); }; socket.onmessage = function(e){ console.log(e.data); var recData=JSON.parse(e.data); dataObjNew=dataObj['data']['datasets'][0]['data']; dataObjNew.shift(); dataObjNew.push(recData.value); dataObj['data']['datasets'][0]['data']=dataObjNew; window.myLine.update(); }; socket.onclose = function(e){ alert('Connection CLosed'); }; </script> <script> var dataObj={ type: 'line', data: { labels: [1,2,3,4,5,6], datasets: [{ label: 'Real time data', borderColor: "#1d7af3", pointBorderColor: "#FFF", pointBackgroundColor: "#1d7af3", pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 1, pointRadius: 4, backgroundColor: 'transparent', fill: true, borderWidth: 2, data: [12, 19, 3, 5, 2, 3], }] }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', labels : { padding: 10, fontColor: '#1d7af3', } }, tooltips: { bodySpacing: 4, mode:"nearest", intersect: 0, position:"nearest", xPadding:10, yPadding:10, caretPadding:10 }, layout:{ padding:{left:15,right:15,top:15,bottom:15} }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } } var ctx = document.getElementById('lineChart').getContext('2d'); window.myLine = new Chart(ctx,dataObj ); </script> <script> let socket =new WebSocket('ws://localhost:8000/ws/polData2/'); socket.onopen =function(e){ alert('Connection established'); }; socket.onmessage = function(e){ console.log(e.data); var recData=JSON.parse(e.data); … -
How to duplicate input field?
I want to create a button to add more file input. I mean, there is a file input on the page, when the user clicks the add more button, then it should create a new and different file input field. How can I do that? -
Difference Django DB models using the ForeignKey to object with or without "to" statement?
I am new to Django and trying to understand someone else code. Where I am struggling with is the models.py and when to use a direct assignment of another object or when to use the "to" statement. What is the difference between those statement? model = models.ForeignKey('Car', on_delete=models.CASCADE, blank=True, null=True) model = models.ForeignKey(to='Car', on_delete=models.CASCADE, blank=True, null=True) -
Get comma separated id with Group by and annotate with sub-query in django
from django.db.models import Subquery, OuterRef My queryset looks like this: AssessmentQueueTable.objects.filter(patient=1,is_deleted=False).annotate(followup_id= Subquery(FollowUp.objects.filter(reference_id=OuterRef('id')).values('id')[:1])) from above query i get only one value in followup_id field like followup_id = 1, but i need all comma separated id like followup_id = 1,2,3,4. if i remove [:1] from sub-query it throws error -
REGEXP for matching or finding only Streetname and housenumber without additionals
This is a regexp specific something that I need to do in the backend to strip the address. I need the streetname + number to be cleaned to a Streetname + housenumber without any additional letters or any other characters with other numbers. For example: Teststreet 123 (correct) Teststreet 123F needs to be stripped to Teststreet 123 Teststreet 12 and 3 needs to be stripped to Teststreet 12 Teststreet 123,5 needs to be stripped to Teststreet 123 Street name long 122 (correct) Street name long 122 - A needs to be stripped to Street name long 122 And so on... I have a function that gets the address from the model and sometimes the addresses could be with some additional characters etc which a API that I have to read does not work with it, so I have split/trim it in python to only a streetname and a housenumber. Does anyone have an idea how I can do this? And anyone an idea what the correct REGEXP for this can be? -
Django I have added an href parameter to my url but it does not work
I have a field in my datatable which represent product url and I have display it in my django template as href in order to enable the user to get the product page by clicking on this link. this is my code in django template : <td><a href="/Productlinks/">{{product.Productlinks }}</a></td> But when I click the url it gives me an error page . -
Why is my sign up button in Django not working?
I have been following a Django blog tutorial where a user can register an account, however my 'sign up' button should be redirecting to the homepage and creating the user, however it does neither. I have extensively searched online for an answer, yet can't seem to resolve the issue. Any help would be much appreciated. Here is my register.html file: {%block content%} <div class="content-section" <form method ="POST" > {%csrf_token%} <!django required security> <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{form.as_p}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit" value="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign in</a> </small> </div> </div> {%endblock content%} and here is my views.py file: from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register (request): if request.method == 'POST': form = UserCreationForm(request.POST) #creates instance of form with POST data if there's a POST request if form.is_valid(): #validation of form form.save() username=form.cleaned_data.get('username') messages.success(request, f'Account created for {username}.') return redirect ('requests-home') #redirecting to home page after account creation else: form = UserCreationForm() #creating instance of user creation form (empty) return render(request, 'users/register.html', {'form': form}) I also get this error when running the views.py file in VsCode: ** "ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, … -
I Want to get card rate in response to card category
What I am trying to do is that once I select a card category, the corresponding card rate should appear, I have three models: Giftcard, Category, and CardRate, which I link together using ForeignKey. Here are my models class Giftcard(models.Model): name = models.CharField(max_length=100, unique=True) card_image = models.ImageField(upload_to='Giftcard/', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) class Category(models.Model): category = models.CharField(max_length=250) card = models.ForeignKey(Giftcard, on_delete=models.CASCADE) class CardRate(models.Model): rate = models.IntegerField() card_category = models.ForeignKey(Category, on_delete=models.CASCADE) Here is my view: def giftcard(request): giftcards = Giftcard.objects.filter(publish=True) categories = Category.objects.all() context = { 'giftcards': giftcards, 'categories': categories, } return render(request, 'dashboard/giftcard.html', context) Here is my template, i thinking here were my mistake is coming from: {% for giftcard in giftcards %} <!-- Card --> <div class="col-lg-4 gift__card col-6 p-0"> <a type="button" class="btn"> <img class="img-fluid gift__card-img" src="{{ giftcard.card_image.url }}"> </a> <div class="container d-flex align-items-center justify-content-center"> <div class="gift__card-modal-container py-5"> <div class="card__container"> <div class="gift__card-overlay"></div> <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid gift__card-img" style="width: 40rem;" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <select id="category" class="form-select py-2" aria-label="Default select example"> {% … -
OrderForm not saving data to django database
i'm creating a webapp that allows a user to enter information in a form which then saves the data into django. Everything works well, I can add information to the form in the template and press submit however the data is not saved into the database (I cannot see it in my admin panel inside 'Order' table. I have the if form.is_valid() form.save() in my views.py file which should POST the data to my database but its not. Anyone know what i'm doing wrong? Order model from models.py class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) # on_delete = If customer is delete, we dont delete child (orders), customer just becomes null without deleting order customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) forms.py OrderForm class is inherited by CreateOrder views.py from django.forms import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' createOrder function from views.py: def createOrder(request): form = OrderForm() if request.method == 'POST': #print('Printing POST:',request.POST) form = OrderForm(request.POST) #form handles the process of saving to database/ if form.is_valid(): form.save return … -
writing to mariadb causes non-UTF-8-endocing
I am using mariadb with Server charset: UTF-8 Unicode (utf8mb4) and python 3.7.3 and for some reason beyond me, a CSV file read in and written to the database is saved in some weird encoding: models.py: class Product(models.Model) data = models.JSONField() store = models.ForeignKey(Store, on_delete = models.CASCADE) number = models.PositiveIntegerField() and when reading in a csv file: with open(filename, encoding = "utf-8") as f: reader = csv.reader(f) for row in reader: d = {header[i]: row[i] for i in range(1, len(row))} logging.error(f"{row[0]} - {d}") # prints "123 - süden" product = Product.objects.get(store = store, number = row[0]) product.data = d product.save() but in my database the line reads as "number": 123, "data": "s\u00fcden". So my struggles here: csv file is encoded in UTF-8 csv file is opened with UTF-8 encoding console prints the charset correctly phpmyadmin shows, "ü" saved as "\u00fc" printing the line in django shell prints "ü" correctly I already tried setting the an encoder for the JSONField: from django.core.serializers.json import DjangoJSONEncoder ... data = models.JSONField(encoder = DjangoJSONEncoder) and then ran migrations again. A simple test can be done in the admin, when searching for products süden returns zero hits. But when manually altering the value to süden in …