Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering using username instead of id in django rest api
I am trying to build a simple chat app using django channels & django restframework.I am completely new to django, Here is the model: user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') recipient = models.ForeignKey(User, on_delete=models.CASCADE,related_name='recipientu') timestamp = models.DateTimeField( auto_now_add=True) content = models.TextField() Serializers.py class MessageModelSerializer(serializers.ModelSerializer): user= serializers.CharField(source='user.username', read_only=True) recipient=serializers.CharField(source='recipient.username', read_only=True) class Meta: model = MessageModel fields = ('id', 'user', 'recipient', 'timestamp', 'content') class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) views.py class MessageModelViewset(ModelViewSet): queryset = MessageModel.objects.all() serializer_class = MessageModelSerializer def list(self, request, *args, **kwargs): recipient_name = self.request.query_params.get('recipient_name', None) if recipient_name is not None: self.queryset = self.queryset.filter( Q(recipient=request.user, user__username=recipient_name) | Q(recipient__username=recipient_name, user=request.user)) return super(MessageModelViewset, self).list(request, *args, **kwargs) class UserModelViewset(ModelViewSet): queryset = User.objects.all() serializer_class = UserModelSerializer I am trying to filter the messages between user and recipient from database. But while filtering from messagemodel it is taking userid as parameter instead of username. How to pass username as parameter and get the data? -
Getting the child info via parent ID
I was trying to fetch the beneficiary of an insuree via its ID but no data was display but when I make a query using the same code with the policy id it returns data Parent is Insuree and child is Beneficiary, Model of the Beneficiary is: class Beneficiaries(TimeStampedModel): user_policy = models.ForeignKey( InsureePolicy, related_name='user_policy', on_delete=models.CASCADE) # models.PositiveSmallIntegerField(blank=False, null=False) first_name = models.CharField(max_length=32, blank=False, null=False) middle_name = models.CharField(max_length=32, blank=True, null=True) last_name = models.CharField(max_length=32, blank=False, null=False) relationship = models.CharField(max_length=16, blank=False, null=True) birthday = models.DateField(blank=True, null=True) While the model of Insuree is: class InsureePaymentDetails(TimeStampedModel): insuree_id = models.ForeignKey( 'Insuree', related_name='insuree_payment_details', null=True, on_delete=models.CASCADE) app_label = 'digiinsurance' accountNumber = models.CharField(max_length=64, blank=True, null=True) While the serializer is: class GetBeneficiaryInfoSerilizer(serializers.ModelSerializer): class Meta: model=Beneficiaries fields=('__all__') and the URL is: path('insuree/beneficiary-info/<int:insuree_id>', views.GetBeneficiaryInfo.as_view(), name="get_beneficiary_info"), -
LEFT JOIN LATERAL Joining subquery in ORM Django
SELECT * FROM "table1" as "dd" LEFT JOIN LATERAL ( SELECT SUM(U02."quantity") AS "total", U02.drug_id FROM "order_items" U02 WHERE ( U02."branch_id" = 2 AND U02."type" = 'created' AND "dd".id = U02.drug_id AND U02."created_at" >= '2021-01-27T16:13:19.381564+00:00' :: timestamptz ) GROUP BY U02."drug_id" LIMIT 1 ) AS "last_month_ordered_quantity" on ( "dd"."id" = "last_month_ordered_quantity"."drug_id" ) LEFT OUTER JOIN "units" ON ("dd"."unit_id" = "units"."id") WHERE "dd".id = 64 -
Django template add 2 strings variables using 'with'
How can I add 2 strings in Django template. I want to define the image url string so I try to join 2 strings. Product is my model and 'image' is its attribute. {% with image='product/img/'+product.image %} <img src="{% static image %}" style="width:600px; height:230px; margin:50 0 50 0"> {% endwith %} -
Raw query added with Django Models
This is query: sub_query = PaymentDetails.objects.filter(order=OuterRef('pk')).order_by('-updated_at')[:1] payment_summary = """select jsonb_build_object( 'total_paid_amount', coalesce(sum(amount), 0), 'total_due_amount', CASE WHEN (order_order.total_gross - coalesce(sum(amount), 0)) > 0.02 then (order_order.total_gross - coalesce(sum(amount), 0)) else 0 end, 'is_full_paid', coalesce(sum(amount), 0) > 0 and (order_order.total_gross - coalesce(sum(amount), 0)) <= 0.02 and order_order.is_payment_completed, 'total_customer_payable_amount', CASE WHEN (coalesce(sum(amount), 0) - order_order.total_gross) > 0.02 then coalesce(sum(amount), 0) - order_order.total_gross else 0 end ) from payment_paymentdetails where payment_paymentdetails.order_id = order_order.id and payment_paymentdetails.status = %s""" orders = Order.objects.prefetch_related( 'lines', 'lines__qc', 'lines__variant__product__vendor_user', 'lines__variant__product', 'lines__variant', 'lines__variant__product__vendor_user__vendor_details', 'lines__tickets', 'lines__lines', 'lines__lines__pickup_req' ).select_related('shipping_address').annotate( payment_updated_at=Subquery(sub_query.values('transaction_date_time'))) \ .annotate(payment_summary=RawSQL(payment_summary, (PaymentStatus.CONFIRMED,))) \ .annotate(payment_method=Subquery(sub_query.values('method'))).order_by('-payment_updated_at').distinct() if 'status' in request.GET or 'id' in request.GET: status_list = request.GET.getlist('status') order_list = request.GET.getlist('id') if len(status_list) > 0 or len(order_list) > 0: orders = orders.filter( Q(status__in=status_list) | Q(id__in=order_list), Q(payment_details__status__in=[PaymentStatus.PAY_LATER, PaymentStatus.CONFIRMED]) ) else: orders = orders.filter( Q(status=OrderStatus.UNFULFILLED), Q(payment_details__status__in=[PaymentStatus.PAY_LATER, PaymentStatus.CONFIRMED]) ) Now I wanna add raw query with Order model like this AND (lower("account_user"."email") similar to '%(sara|aa)%' OR lower("account_vendordetails"."company_name") similar to '%(sara|aa)%' OR lower(order_orderline.data->>'host') similar to '%(sara|aa)%' )) when I filter with vendor name, then added this query like this if vendor_name: vendor_name = "".join(vendor_name).replace(', ', ',').replace(',', '|') print("vendor name============>", vendor_name) vendor_sub_query = f""" and (lower("account_user"."email") similar to '%({vendor_name})%' OR lower("account_vendordetails"."company_name") similar to '%({vendor_name})%' OR lower(order_orderline.data->>'host') similar to '%({vendor_name})%' )""" orders … -
linking to home page Django
Im having problems with making a link to homepage. What i have right now is href = "http://127.0.0.1:8000" but obvioulsy its not effective. Im not using {% url 'index' %} because i cant type anything after it, e.g: "{% url 'index' %}/articles" Is there any way to do that, using url 'index' or any other way? I dont want to use django admin and database for that tho, as the database will not be saved, as im giving the code to someone else (but that doesnt really matter, just know that the database will not be saved and i cant do anything about it). -
"non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] in django rest framework while calling api in postman
It was working fine when I created order object from orderitem objects using validated.pop() function. Now, I have another model for BillingDetails that needs to be created as well which has a foreign key to Order model. Now front end is sending chunks of data which contains orderitems data and also billingdetails at the same time. And I have to create Order object creating Orderitem objects and BillingDetails object at the same time. I have tried writing this but got error on api call on Postman. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.email class OrderItem(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class BillingDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, on_delete=models.CASCADE, blank=True, null=True, related_name='billing_details') first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=50,blank=True,null=True) country = models.CharField(max_length=50,blank=True,null=True) city = models.CharField(max_length=50,blank=True,null=True) address = models.CharField(max_length=100,blank=True,null=True) postal = models.CharField(max_length=50,blank=True,null=True) def __str__(self): return self.address My view: class AddtoOrderItemView(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = OrderItem.objects.all() serializer_class = OrderSerializer My serializer (Initially): class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, … -
Django correct url path but got page not found url didn't match
I'm having a hard time with this error and I'm not sure how to fix it I have this in my urls.py path('service/author/<uuid:author_id>/followers/', views.get_followers), path('service/author/<uuid:author_id>/followers/<uuid:foreign_author_id>/', views.edit_followers), the first path work when I go to it, but the second path will always give me 404 page not Django tried these URL patterns, in this order: ... service/author/uuid:author_id/followers/ service/author/uuid:author_id/followers/uuid:foreign_author_id/ ... The current path, service/author/075194d3-6885-417e-a8a8-6c931e272f00/followers/089200d3-6885-417e-v0v0-6c555f272f00, didn't match any of these. but it will work when I go to the same path but without the second uuid: service/author/075194d3-6885-417e-a8a8-6c931e272f00/followers/ I would really appreciate any help or insight into this issue, thank you! -
Select random field from database in Python
So I am developing a Django app and what I want at the moment in to develop a script that selects a random field from a row with 3 words in a MySQL database that I have. I have searched for info but haven't managed how to do it. My database: What I want is the script to read the database and select a random word each time. I haven't worked so much with DBs in Python so I have no clue about how to do it. Help is much appreciated. -
How to calaculate average in Custom Model Manager in Django
I have Following model class Review(models.Model): content = models.TextField() score = models.DecimalField( max_digits=3, validators=[validate_score], decimal_places=1 ) reviewed_by = models.ForeignKey(User, on_delete=models.CASCADE) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) show_review = models.BooleanField(default=False) objects = ScoreAverageManager() I am trying to calculate average using model manager when I try that model manager in shell I got error Stating Manager Object has no attribute 'average' here is my Manager code class ScoreAverageQuerySet(models.QuerySet): def average(self): return self.aggregate(Avg('score')) class ScoreAverageManager(models.Manager): def get_queryset(self): return ScoreAverageQuerySet(self.model, using=self._db) def average(self): return self.get_queryset().average() Could not figure out what went wrong and is my average() method to find average correct? -
drop/reset one/multiple (specified) models from database with django
I've added a field to my django model. Now, since I've had some instances of this model already, they not include this field resulting in django error page. I'm not able to manually delete those instances from admin panel. I've searched that python manage.py flush is a way to go for reseting whole db, but I would like to delete only this particular model. Is there a way to do this from the CLI ? -
Why date_joined empty?
"Date_joined This field is required" error message when i try to update user profile.Why is the value not being recorded automatically? Where are my mistakes? models.py class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) surname = models.CharField(max_length=210, blank=True) phone_number = models.CharField(null=False, max_length=20, validators=[validate_phone_number], default="+38(098)000-0000") image = models.ImageField(default='default.png', upload_to='accounts') def save(self, *args, **kwargs): super().save(*args, **kwargs) image = Image.open(self.image) image.thumbnail((300, 300), Image.ANTIALIAS) image.save(self.image.path) view.py class AccountRegistrationView(CreateView): model = User template_name = 'registration.html' success_url = reverse_lazy('accounts:login') form_class = AccountRegistrationForm def form_valid(self, form): result = super().form_valid(form) messages.success(self.request, 'User registered successfully') return result forms.py class AccountRegistrationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ['username', 'first_name', 'last_name', 'email'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'register__input' }) -
App not compatible with buildpack: error during deploying django app to heroku
I am trying to deploy django app to heroku. During attempt of deployment i'm getting error: App not compatible with buildpack i'm doing this first time and i have no idea what i'm doing wrong. May be my master branch is on the venw directory and directory of app is on main branch. I have tried use call: git push heroku main on main branch but it doesn't work. My main branch contains files requirements.txt, procfile and runtime.txt. It is necessary to push app to heroku from master branch or main branch is also possible? Any idea how to solve my problem? My git bash logs below: ggb@DESKTOP-PNHHOHJ MINGW64 /c/projekty/tabele/tabenv (master) $ ls Include/ Lib/ pyvenv.cfg requiremenrs.txt runtime.txt Scripts/ tabele/ (tabenv) gg@DESKTOP-PNHHOHJ MINGW64 /c/projekty/tabele/tabenv (master) $ git push heroku master Enumerating objects: 9191, done. Counting objects: 100% (9191/9191), done. Delta compression using up to 4 threads Compressing objects: 100% (5820/5820), done. Writing objects: 100% (9191/9191), 17.71 MiB | 4.76 MiB/s, done. Total 9191 (delta 2299), reused 9184 (delta 2296), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: … -
Django: Best practice temporary file storage and initializing objects once for all views
I do have two questions regarding best practice in Django. I have a working solution for both questions but feel like they are very "hacky" and that there must be a better way to solve this. Question 1: In my application I generated a lot of temporary files where in the end I only keep a few of them. The files have to be shown to the user. My question is where is the correct place to store them? Currently I just store them in the static folder of the app that generates the front-end for the user but I would like to have a more general place as the files are generated inside another app. Question 2: To generate the temporary files I used an additional python module that holds all the logic regarding the generation. To create these temporary files I have an object of the generator class. To avoid the creation of this object for each view I created it once inside a custom middleware and added it to the request. This has the problem that I now add it to every request while it's only needed for some. What would be the right way to persist … -
Django channels Sync consumer blocking main thread
Recently I ran into the Django Sockpuppet project on Github. This is the first time I checked out Django channels, so I'm a bit new to all this. There is a particular piece of code in sockpuppet that doesn't seem to be thread safe, but I'm not quite sure if this is a problem, because it's an ASGI app. I tried a very basic test, by just adding a time.sleep and checking if blocking one request would block the entire app, and it does. So that seems to imply that no threads are used. Then I tried to print out the current thread id in every request, it prints the same id every time. Again, implying a single thread is used. However, digging into the code a little bit, I notived that sockpuppet uses a Channels JsonWebsocketCusomer. This consumer inherits from SyncConsumer, the docstring on sync consumer explicitly mentions that it's requests are executed by a thread pool in sync mode. I've checked to see that the sockpuppet consumer is actually declared as _sync, which it is. Also, the dispatch method on SyncConsumer is decorated with a slightly altered version of asgiref's SyncToAsync decorator, which does in fact run it's … -
django save() doesn't effect in sqlite
I have a scrapy project and want to save retrieved data in sqlite. I write scrapy spider in views file. You can see a portion of it below. This is views.py file: class DivarSpider(scrapy.Spider): name = "divar" def parse_each_ads(self, response): . . . src = Source() src.name = self.name ctlg = Catalogue() ctlg.city = city ctlg.type = slug ctlg.area = area ctlg.room = room ctlg.price = price ctlg.district = district ctlg.datetime = date ctlg.source = self.name ctlg.source_token = token src.save() ctlg.save() This is models.py file: class Source(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Catalogue(models.Model): source = models.ForeignKey(Source, null=False, on_delete=models.CASCADE) city = models.CharField(max_length=100) district = models.CharField(max_length=100) type = models.CharField(max_length=100) room = models.CharField(max_length=100) area = models.CharField(max_length=100) price = models.CharField(max_length=100) datetime = models.CharField(max_length=100) source_token = models.CharField(max_length=100) Why src.save() and ctlg.save() doesn't work? -
How to implement paho python client in Django 3.1
from this SO question, I implemented a subscriber client in my Django project as following: in mqtt.py, I create a client and connect to a local broker and subscribe to a topic. #myapp/mqtt.py: import paho.mqtt.client as paho import json import django django.setup() from .models import Temperature, Turbidity, Refined_fuels, Crude_oil from datetime import datetime # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("CONNACK received with code %d." % (rc)) client.subscribe("sensor/temp", qos=0) def on_subscribe(client, userdata, mid, granted_qos): print("Subscribed: "+str(mid)+" "+str(granted_qos)) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+", "+'QOS: ' +str(msg.qos)+",\n"+str(msg.payload, 'utf-8')) message_dict = json.loads(msg.payload) now = datetime.now() captured_timestamp = datetime.utcfromtimestamp(int(message_dict['Timestamp'])).strftime('%Y-%m-%d %H:%M:%S') print('timestamp: ', captured_timestamp ) if message_dict['Temperature'] and message_dict['D850'] and message_dict['D280']: temp = Temperature(captured_timestamp=captured_timestamp, data=message_dict['Temperature'], received_timestamp=now) temp.save() refined_fuels = Refined_fuels(captured_timestamp=captured_timestamp, data=float(message_dict['D850']), received_timestamp=now) refined_fuels.save() crude_oil = Crude_oil(captured_timestamp=captured_timestamp, data=float(message_dict['D280']), received_timestamp=now) crude_oil.save() # defining client client = paho.Client(client_id="testSubscriber", clean_session=True, userdata=None, protocol=paho.MQTTv311) # adding callbacks to client client.on_connect = on_connect client.on_subscribe = on_subscribe client.on_message = on_message client.connect(host="localhost", port=1883, keepalive=60, bind_address="" ) in __init__.py I call the loop_start() of client: # myapp/__init__.py from . import mqtt mqtt.client.loop_start() For publisher client I used paho C client. … -
django ifchanged value before change
I used ifcahnged as {% for day in doctor.scheduled_by.all %} {% ifchanged day.start_day_time %} <span> {{ day }} </span> <span>{{ day.start_day_time }} AM - {{ day.end_day_time }} PM</span> {% endifchanged %} {% endfor %} and the result is as Saturday 5:00:00 AM - 14:30:00 PM Friday 0:09:00 AM - 0:02:00 PM I want something like Saturday - Thursday 5:00:00 AM - 14:30:00 PM Friday 0:09:00 AM - 0:02:00 PM :) (new to community). -
Connect local website with server cpanel database
I am working an a DJANGO web application that is going to be running locally only. But I would like to make it connect to my CPANEL database so that I can monitor every transaction without accessing that PC. I tried connecting as shown below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'user_name', 'PASSWORD': 'user_password', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'STRICT_ALL_TABLES', } } } I have created the database and the user in MySql Database in my CPANEL and I granted the user all previliges. But still when I try to run the software (web application) I get this error: django.db.utils.OperationalError: (1045, "Access denied for user 'user_name'@'localhost' (using password: YES)") now some will say change the HOST from localhost to the server's name or IP address, I tried the public IP @ but didn't work and regarding the server's name it is Server: Localhost via UNIX socket Any Idea? -
I am creating django app .I am Face the difficulty on ULRS.PY page. I want solution with PATH not URL
path('apiemp/(?P\d+)/$', views.EmployeeDetailsAll.as_view()), this is not working its [this is SC][1] [1]: https://i.stack.imgur.com/SICFT.png Buturl(r'^apiemp/(?P<id>\d+)/$ This is work -
How to create an executable file with multiple commands?
I want to create an executable file with various commands that run a project in django along with a virtual environment. The commands I want to run are: d: cd Python/projects myvenv\Scripts\activate cd web python manage.py runserver -
How to list kirana store/cafe for particular pincode on django website?
based on pincode or location given by user how do i retrieve the list of near by kirana stores/cafe? Kindly help me with this. -
Store credentials used by django when deployed
I have a Django deployed to Google App Engine (GAE). Curently the credentials for the database containing user information and the Django secret key is stored in a Bucket, which can be accessed only by using the given credentials.json. Furthermore I have whitelisted only the IP for the GAE. The problem is that the App Engine need access to the credential-file, i.e I need to deploy that. I have thought of many solutions, but I cannot come up with one where we dont have anything stored in some kind of plain text on the App Engine, since it need to have something of which it can read and use for authorization at some point. What is the most common way to store such credentials? I have seen people using the .env file but I cannot see the advantage of having the credentials in plain-text in the .env file compared to just in the settings.py file. Note, if there is some "GCP interaction" that can handle this issue (e.g letting an GAE connect to a GCP Sql-server without credentials but through some kind of whitelisting of the App Engine); please let me know. -
How can i authenticate any user for login with an extra field (other then username/ email and password) in django
I am creating a user profile using django’s authentication system (from django.contrib.auth.models import User). Before this I am trying to extend the field of user using an extra field (i.e- userprofile= ceo/developer/marketinghead) in models.py. Here is my models.py file from django.db import models from django.contrib.auth.models import User Create your models here. class extendeduser(models.Model): userprofile_choice=( ('ceo', 'ceo'), ('developer', 'developer'), ('marketinghead', 'marketinghead'), ) userprofile=models.CharField(choices= userprofile_choice, max_length=255, blank=False) user=models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self) -> str: return self.userprofile now I am sucessfully registering the new user. Now I have created differrent html pages based on their profile. So at the time of login I take an extra input from user which is userprofile. And based on this I have created views.py for redirecting the user at correct place. Here is my views.py file :- def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] uf = request.POST['userprofile'] user = auth.authenticate(username=username, password=password) user_profile = extendeduser.objects.filter(user = user) # print(user_profile[0]) # print(uf) # print(user.get_username) # print(user.__dict__) #print(user.get_userprofile) if user is not None: if uf==user_profile[0]: if uf=='ceo': auth.login(request, user) messages.success(request, "You are logged-In") return redirect('wtoday') elif uf=='developer': auth.login(request, user) messages.success(request, "You are logged-In") return redirect('swhome') elif uf=='marketinghead': auth.login(request, user) messages.success(request, "You are logged-In") return redirect('sswhome') else: … -
heroku-django , sqlite3
last day I hosted my Django blog website on the Heroku server I'm using the sqlite3 database. whenever I'm adding a new post from Django admin panel it shows post on website for an hour but after some time my posts automatically disappears please help me I'll provide whatever files you want