Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get the average score calculation to be less than 0.01 seconds?
I created a function to average the comments in TVAndMovie. However, when I created 100000 comments, it took an average of 4 seconds to get the average of the scores! I have been trying to find a way to get the average of the scores. How can I reduce the time to less than 0.01 seconds? class TVAndMovie(models.Model): tmdb_id = models.IntegerField( verbose_name="", blank=False, null=False, ) judge_tv_or_movie = models.CharField( blank=False, null=False, default="movie", max_length=20 ) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) def get_comments(self) -> object: return Comment.objects.filter( tv_or_movie_id=self.id ) def average_stars(self) -> float: comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = round( sum([comment.stars for comment in comments]) / n_comments, 3 ) else: self.stars = 0 self.save() return self.stars class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) tv_or_movie = models.ForeignKey(TVAndMovie, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ("user", "tv_or_movie") indexes = [models.Index(fields=["user", "tv_or_movie"])] -
How expensive is raise in Python?
During development using drf, an efficient method for error handling was needed. I found two methods, one using ErrorResponse created by inheriting Response, and one using APIException provided by drf. The first method is done through return, and the second method uses the raise command. I wonder which one is more efficient and why! I apologize in advance for the question may be too vague. -
Results are not being shown on my terminal
After writingenter image description here this code in my views.py, in order to be certain the code was working perfectly I added a print() into the if statement, but it doesn't seem to show the desired result This is the views.py 1: https://i.stack.imgur.com/aANSO.jpg Then the html is this enter image description here -
How can I fetch data from another model to create object in CreateAPIView in DRF
I have two models and their corresponding serializers: Review model: class Review(models.Model): store = models.ForeignKey(Store, to_field='id', null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(CustomerProfile, to_field='id', null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, on_delete=models.CASCADE) feedback_image = models.ImageField(upload_to='images', blank=True) comment = models.TextField(blank=True) store_rating = models.PositiveIntegerField(default=0) product_rating = models.PositiveIntegerField(default=0) Review serializer class ReviewSerializer(serializers.ModelSerializer): feedback_image = serializers.ImageField(required=False) class Meta: model = Review fields = '__all__' Order model: class Order(models.Model): store = models.ForeignKey(Store, to_field='id', null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(CustomerProfile, to_field='id', null=True, on_delete=models.SET_NULL) order_ref = models.CharField(max_length=20, unique=True, null=True) ... Order serializer class OrderSerializer(serializers.ModelSerializer): customer = serializers.ReadOnlyField(source='customer.email') class Meta: model = Order fields = ['order_ref', 'store', 'customer',...] I want to create a review instance but only have the following fields in the client payload: { "order_ref": "10001111401218982", "comment": "black black", "store_rating": 5, "product_rating": 4, "product": 1 } As you can see above, the payload is missing store and customer fields. These fields are in the Order model and can be gotten with the order_ref. I am trying to override the generics.CreateAPIView for the Review model so I can use the order_ref to first get the missing fields, and then create the Review object. Review view: class ReviewCreate(generics.CreateAPIView): permission_classes = [AllowAny] queryset = Review.objects.all() serializer_class = ReviewSerializer def create(self, request, *args, **kwargs): data … -
Django: view_name() missing 3 required positional arguments: 'email', 'amount', and 'product'
I am writing a simple logic for payment of product, i am passing in the some parameters in the function like name, 'amount', 'email' etc, but i started getting this error that says missing 3 required positional arguments: 'email', 'amount', and 'product' i cannot really tell where the problem is coming from? Views.py @login_required def productCheckout(request, pk): ... if request.method == "POST": order_item = OrderItem.objects.create(user=user, product=product) order_item_id = order_item.id product = Product.objects.get(id=pk) name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment_product(name,email,amount, product, order_item_id))) context = {"product":product,} return render(request, "marketplace/product-checkout.html", context) def process_payment_product(name, email, amount, product, order_item_id): auth_token= settings.FLUTTER_SECRET_KEY hed = {'Authorization': 'Bearer ' + auth_token} ... ... -
Websocket notifications in django
I am implementing web socket notifications into my Django project and am having trouble with passing the user the the amount of unread notifications that they currently have. My solution to this problem was to simply send all objects in the notification model class to the user once they connected to the web socket as messages in the web socket itself, which initially worked, but breaks if there are more then one tab open as each new tab connects to the web socket again which in turn will send the web socket messages again to any other open tab logged in to that user. ending up with duplicates of the same notification. What i need is a way display all notifications on each page when it is loaded. Preferably without sending it through the context of a view My consumers.py @database_sync_to_async def create_notification(notification): """ function to create a notification. :param notification: notification in json format to create notification object """ user = User.objects.get(username=notification["target"]) NotificationsModel.objects.create( target=user, sender=notification["sender"], alertType=notification["alertType"], title=notification["title"], message=notification["message"], ) class NotificationConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event: dict) -> None: if self.scope["user"].is_anonymous: await self.close() else: self.group_code = self.scope["url_route"]["kwargs"]["group_code"] await self.channel_layer.group_add(self.group_code, self.channel_name) await self.accept() # Since removed the send notifications from here … -
How to rename the ManytoMany Model in Django Admin
I have two models: class ModelA(models.Model): id = models.AutoField() name = models.ManyToManyField(ModelB) class ModelB(models.Model): id = models.AutoField() In the Django Admin page, I noticed that I now see a table called "modelA-modelB relationships". Is this the expected outcome? If so, how can I rename this to be something more user-friendly? I've tried several parameters verbose_name, related_name, and db_table for the ManytoManyField and none seem to overwrite the default name. -
python django - exclude class from makemigrations
Let`s say I have a class: class A(models.Model, GrandparentClassSharedByAllClasses): value = models.CharField(max_length=2000, blank=False, null=False) def __str__(self): return self.value class Meta: verbose_name = _('test') verbose_name_plural = _('tests') can I somehow exclude it from makemigration/migrations? Why would I want that? -> Class A is one of manny classes of which all others save the objects in the db. Class A should bring the same functionality like the other classes, so it can be used in the same pipeline, but not be stored in the db. -
how to sum(details_item_quantity) as an admin action in django
Hi! I need to know the quantity of sales made in a range of time and the subtotal per Item as an admin action in django admin. for example: between 6:30 and 7:00 pm of jan.01, 2022. customer-1: bought "1" item(666000354) for $1000 and "1" item(666000251) for $35 customer-2: bought "1" item(666000251) for $35 Show somethin like this: Total: $1070 Item(666000354) - qtty:1 - total_item: $ 1.000 Item(666000251) - qtty:2 - total_item: $ 70 The view of "TICKETS" in the django admin already show Tickets and Details_Ticket in a single view, so I want to make something similar, I know how to filter the new consulted-ticket and all that, but not how to correctly add every quantity and price per item because the details to SUM, are in another table. And another thing,how to search a date?, bc the list_filter in admin.py search for a string... models.py: class Ticket(models.Model): ticket_id =models.AutoField(primary_key=True) customer_id=models.ForeignKey(Customers, models.DO_NOTHING, blank=true, null=true) date= models.DateTimeField(blank=True, null=True) total= models.IntegerField(blank=True, null=True) class Meta: db_table='tickets' class Details_ticket(models.Model): detailsticket_id = models.AutoField(primary_key=True) ticket_id = models.ForeignKey(Ticket, models.DO_NOTHING, blank=true, null=true) item_id = models.ForeignKey(CartItems, models.DO_NOTHING, blank=true, null=true) qtty = models.IntegerField(blank=True, null=True) total_item= models.IntegerField(blank=True, null=True) -
Django link to JavaScript works from desktop platfroms but not mobile platforms
I recently finished upgrading a Django 1.9.6 project to 4.0.5. Everything is finally working well with one minor glitch. I have a function (JavaScript) that is called from within a form. The code uses an tag. I've used both href= and onclick=. Everything works when called from a desktop platform; Windows, Mack, or Linux. With a mobile platform like iOS or Android the link doesn't respond at all. Other controls on the page work fine. I compared the page with the original code and both versions are identical. I am not the original author of the code. I have to assume that this did work at one point as the owner has pointed it out to me. I've never run across something like this before and I'm at a bit of a loss as to where to look. Any suggestions would be greatly appreciated. Thanks in advance! -
Get the max value in Django queryset for a foreign key
Hell all, I have two models as following class Publisher(models.Model): location = models.CharField() some_other_field = models.CharField() class Author(models.Model): publisher = models.ForeignKey(Publisher, related_name='authors', on_delete=models.CASCADE) name = models.CharField() lastname = models.CharField() location = models.CharField() class Books(models.Model): author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) date_published = models.DateField() I want get the Max number of books for a given group of actors that belong to a certain set of publishers. Something along these lines: publisher_ids = [1, 2, 3] max_books = Author.objects.filter(publisher_in__in=publisher_ids).aggregate(max_value=Max('books')) Any help is really appreciated!!! -
Changing posts and information on form/page and getting an users information without directing to another page
I am creating a Django based website and it includes users information page. At the left side (can be seen in picture) I printed the usernames dynamically. I want to refresh the information of user when I clicked to a username without changing page or something. (It only shows the information of logged in user now.) Only want to change information written on the form. -
Set default media files in Docker using Django
I am deploying my Django web application using Docker and Docker Compose, Nginx and Postgresql. I have already done the deployment and it works well. But I have a problem with the default media files. When I was deploying in local and in my server, I add those default media files manually to the media folder, but now with Docker I can't do that. One of my models would be that one, which has a default image "dictionary/default.png" and obviously when I run my docker image doesn't load because it doesn't exist anywhere. class Dictionary(models.Model): dictionary_name = models.CharField(max_length=200) dictionary_picture = models.ImageField(upload_to='dictionary', default='dictionary/default.png') I was thinking to have these default media files locally and copy them to the Docker media folder in the Dockerfile, but I do not know if this is possible. -
How to keep a user logged in (even when phone turns off ) on a React Native app with Django backend?
I am beginning to code with react native and I am trying my first app. I am in the process of making the login/signup of the app. I managed to log the user in but I cannot seem to figure out how to keep the user logged in when I close the app. How can I keep a user logged in to the app even when the app is closed? This is what I have- login.js import { StatusBar } from 'expo-status-bar' import { StyleSheet, Text, View, FlatList, Image, Button, Pressable, ScrollView } from 'react-native'; import React, {useState, useEffect} from 'react' import { TextInput } from 'react-native-gesture-handler'; export default function Login(props) { const message = props.navigation.getParam('message', null) const [ username, setUsername ] = useState("") const [ password, setPassword ] = useState("") const log = () => { fetch(`http://192.168.5.223:8000/home/login/`, { method: 'POST', headers: { "Content-Type": 'application/json' }, body: JSON.stringify({ username: username, password: password}), }) .then( res => res.json()) .then( res => { console.log(res) if (res.valid === true){ if (res.set === true){ props.navigation.navigate("Home", {"user": username}) } else { props.navigation.navigate("Profile", {"user": username}) } } else { props.navigation.navigate("Login", {'message': "username/password are incorrect"}) } }) .catch( error => console.log(error)) } const sign = () => … -
K8's pod status: OutOfmemory
I have a Django application deployed on an Azure Kubernetes Service (AKS). It's using Redis as a server and Celery instances for the workers. I'm running into a new issue where one of the pods has a status of OutOfmemory and soon as it's redeployed. For example, I'll run kubectl delete -f deployment/dendro-pod-prod-2.yaml to remove the pod and kubectl apply -f deloyment/dendro-pod-prod2.yaml to redeploy it. When I run kubectl get pods immediately after, I see a status: NAME READY STATUS RESTARTS AGE dendro-backend 1/1 Running 1 84d dendro-celery 1/1 Running 0 23h dendro-celery-3 0/1 OutOfmemory 0 4s I would think that redeploying should reset the memory. I've tried increasing the memory for the requests and limits in the YAML file. I'm new to kubernetes, and the only related solutions I'm finding online have to do with the OOMKilled status. -
ModelChoiceField in ModelFormSet not selecting initial value when using custom ModelForm
So I am using a ModelFormSet to show a list of forms based on a predefined ModelForm. I need to customize the two fields in the forms, and therefore I have created this ModelForm: # forms.py class StudentRelationshipForm(forms.ModelForm): # the row below causes the issue: classroom = forms.ModelChoiceField(queryset=Classroom.objects.all(), widget=forms.Select(attrs={'class':'form-control border-0 bg-white text-black h5'}), to_field_name='clarsroom_name', disabled=True, required=True) student_type = forms.ChoiceField(choices=StudentRelatuionship.STUDENT_TYPES, widget=forms.Select(attrs={'class': 'form-control'}), required=True) class Meta: model = StudentRelatuionship fields = [ 'classroom', 'student_type', ] I am creating the ModelFormSet in the following view: # views.py .... class MyView(DetailView): def get_context_data(self, **kwargs): classroom_list = [ a list of classrooms goes here ] initial_formset_data = [] for classroom in related_companies: initial_formset_data.append({'classroom': classroom.pk}) StudentRelationshipFormSet = modelformset_factory(StudenrRelatuionship, form=StudentRelatuionshipForm, fields=['classroom', 'student_type'], extra=formset_extras) context['investor_relationships_formset'] = StudentRelationshipFormSet(queryset=StudentRelatuionship.objects.filter(student=self.request.user.user_profile, classroom__in=classroom_list), initial=initial_formset_data) .... Basically the problem that I have is that when I specify the classroom field in StudentRelationshipForm in forms.py, the HTML Select widget's default value becomes ---------. However, if I remove the row from forms.py, the HTML select widget correclty selects the classroom name from the database when editing an existing instance. How could I overcome this? The reason why I need the row is to specify that the field should be disabled. If there is another way to … -
Django + Apache + Ubuntu | ModuleNotFoundError: No module named 'myproject.settings'
I am running a django app on apache using wsgi on an ubuntu 18.04 aws ec2 instance. I have tested the django app on the development server and it works fine. When I run it on apache, it says that there was an error running wsgi.py, no module named myproject.settings. I am guessing this is an issue with how the directory is setup/apache can't get access to the settings.py file, but I am new to apache so I do not know. error.log: [Tue Aug 16 19:45:59.789014 2022] [mpm_event:notice] [pid 9672:tid 140130027445184] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Tue Aug 16 19:45:59.789098 2022] [core:notice] [pid 9672:tid 140130027445184] AH00094: Command line: '/usr/sbin/apache2' [Tue Aug 16 19:46:07.705559 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] mod_wsgi (pid=9675): Target WSGI script '/home/ubuntu/django/myproject/myproject/wsgi.py' cannot be loaded as Python module. [Tue Aug 16 19:46:07.705632 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] mod_wsgi (pid=9675): Exception occurred processing WSGI script '/home/ubuntu/django/myproject/myproject/wsgi.py'. [Tue Aug 16 19:46:07.706225 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] Traceback (most recent call last): [Tue Aug 16 19:46:07.706273 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] File "/home/ubuntu/django/myproject/myproject/wsgi.py", line 16, in <module> [Tue Aug 16 19:46:07.706279 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] … -
Django runserver+Celery worker+Celery beat not running at the same time (with broker and backend redis)
{proj name}/settings/celery.py My project name is 'cole_rochman' and versions of packages are django==2.2.8, celery==4.3.0, redis==3.3.11, django-celery-results==1.1.2. I'm using broker url with aws redis. BROKER_URL = '{primary endpoint}', CELERY_RESULT_BACKEND = 'django-db'. I'm also using aws ec2 server. I opened three linux servers and wrote command 'python manage.py runserver 0.0.0.0:8000', 'celery -A {proj name} worker -l INFO', 'celery -A {proj name} beat -l INFO' each. Django and celery separately runs with no problem but when running them together, server stops. Please help me about the reason why this happens. -
3 django model filterset with django-filter
I have 3 different django models and I want to filter using django-filter. The ORM query I wrote below works without any problems. but how can i do this with django-filter (filters.FilterSet) ? Employee.objects.filter(companyrecord__company__cname__icontains="ompanyname") THIS IS WORKS it is work for me in ORM. But how can i do this in filter set. I wrote above what I want to do My Models: class Employee(models.Model): employee_name = models.CharField(...) class CompanyRecord(models.Model): employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) class Company(models.Model): cname = models.CharField(...) My FilterSet: class EmployeeFilter(filters.FilterSet): full_name = filters.CharFilter(field_name="full_name", lookup_expr='icontains') class Meta: model = Employee fields = ['full_name'] -
Prevent capitalization in model field's verbose_name
I use the following template tag: @register.simple_tag def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ return instance._meta.get_field(field_name).verbose_name.title() Assume I have defined a model field lorem_ipsum with the field's verbose_name="FOO bar". Then, when I run {% get_verbose_field_name object "lorem_ipsum" %} in the template in a table's <th> element, I receive "Foo Bar". However, I want to keep the verbose name exactly how I defined it—in this example as "FOO bar". How can one disable auto-capitalization of verbose names? -
any change in CSS are not reflecting in django project
I have installed whitenoise on my project and settings for my projects for static file is, settings.py, STATIC_URL = '/static/' STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Media files MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR.joinpath('media')) in urls.py, ( + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) this is also added, problem is that the project is ok with older css but if I make any changes it have no effect,how to solve it -
Can I expand an HTML table to display more data from another django model?
I have the below HTML code, which creates a table by looping through the data from a Django SQL based model. I'd like to add a plus button to each row, allowing each to expand to show a few rows of data from a DIFFERENT model based on matching household id's. I've tried many different jquery functions along with adding the another body to the table with a new loop for the new model data, but I can't seem to get my desired result. Any help would be appreciated! Example desired result: expanding row image Code: <div class="container" style="height:600px;width:1200px;overflow:scroll;max-height:500px"> <table position="relative" class="table table-bordered"> <thead> <tr> <th>Household</th> <th>Name</th> <th>Account Number</th> <th>Basic Materials %</th> <th>Communication Services %</th> <th>Consumer Cyclical %</th> <th>Consumer Defensive %</th> <th>Energy %</th> <th>Financial Services %</th> <th>Healthcare %</th> <th>Industrials %</th> <th>Real Estate %</th> <th>Technology %</th> <th>Utilities %</th> </tr> </thead> <tbody> {% for i in sectors %} <tr> <td>{{ i.household }}</td> <td>{{ i.owner }}</td> <td>{{ i.account_num }}</td> <td>{{ i.basic_materials }}</td> <td>{{ i.communication_services }}</td> <td>{{ i.consumer_cyclical }}</td> <td>{{ i.consumer_defensive }}</td> <td>{{ i.energy }}</td> <td>{{ i.financial_services }}</td> <td>{{ i.healthcare }}</td> <td>{{ i.industrials }}</td> <td>{{ i.real_estate }}</td> <td>{{ i.technology }}</td> </tr> {% endfor %} </tbody> </table> </div> These are a few links i have … -
Django publish to KAFKA instead of save to database
We are trying to develop a microservice architecture in Django rest framework where all writes to a SQL database are done by publishing messages to topics on a Apache Kafka messaging system, and all reads are done directly from an SQL database. This is being done for several reasons, but most importantly it's to have an event log history through Kafka, and to avoid delays due to slower write cycles (reads to databases are usually much faster than writes). Using signals, it's quite easy to call a Kafka producer method in Django which will publish an event on Kafka showing the model data to be written to db. However, we don't know how to avoid having the save() method write anything to the database. We don't want to completely override the save() method as it may cause issues when dealing with ManytoMany relationships. Does someone have a simple suggestion to avoid database writes but still do database reads in Django? Please keep in mind that we still want to use the conventional method to read from the SQL database using Django models. Any suggestions would be valuable! Thanks in advance. -
Cannot access foreign key elements in html templates DJANGO
Views: def search_devis(request): devis = Devis.objects.all() commercial = User.objects.all() client = Client.objects.all() context={ 'devis': devis, 'commercial': commercial, 'client_': client, } return render(request, "manage_devis/search_devis.html",context ) Models: class Devis(models.Model): titre = models.CharField(max_length=30, ) date_ecriture = models.DateField(auto_now_add=True) date_expiration = models.DateField() client = models.ForeignKey(Client, name="CLIENT_FK", default=1 ,on_delete=models.SET_DEFAULT) total = models.DecimalField(max_digits=10, decimal_places=2) commercial = models.ForeignKey(User, name="COMMERCIALFK", default=1 ,on_delete=models.SET_DEFAULT) def __str__(self): return "DV"+str(self.pk) Templates: {% for devis_ in devis %} <tr> <th scope="row"><a href="{% url 'view_devis' devis_.pk %}">DV{{devis_.id }}</a></th> <td>{{ devis_.date_ecriture }}</td> <td>{{ devis_.date_expiration }}</td> <td>{{devis_.client.nom}}</td> <td>{{ devis_.total}} DH</td> <td>{{ devis_.commercial.last_name}}</td> </tr> {% endfor %} I can't display the attributes of the foreign key object, no value in it. nothing appear in the column. I'm using postgresql database. -
HTML For Loop to add Image from Django Database
I am working on passing through a logo into my html code, however whenever I pass it through into html, a little blue question mark appears instead. I was wondering how to pass through the logo into the src. Thanks for the help. class LoansOutstanding(models.Model): company_name = models.CharField("Company Name", max_length=50, default="") company_logo_url = models.ImageField("Company Logo", upload_to="main/None", height_field=None, width_field=None, max_length=100, blank=True, null=True) Views.py def number(request, number): loans_in_security = LoansOutstanding.objects.filter(number=number) return render(request, template_name='main/number.html', context={"loans_in_securities": loans_in_security}) HTML <div class="profile-details"> <div class="profile-image-pane"> <ul> {% for loans in loans_in_securities %} {% if forloop.first %} <li><img class="profile-image" src="{{loans.company_logo_url}}"/></li> {% endif %} {% endfor %} </ul> </div> </div>