Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extract only the data from a Django Query Set
I am working to learn Django, and have built a test database to work with. I have a table that provides basic vendor invoice information, so, and I want to simply present a user with the total value of invoices that have been loaded to into the database. I found that the following queryset does sum the column as I'd hoped: total_outstanding: object = Invoice.objects.aggregate(Sum('invoice_amount')) but the result is presented on the page in the following unhelpful way: Total $ Outstanding: {'invoice_amount__sum': Decimal('1965')} The 1965 is the correct total for the invoices that I populated the database with, so the queryset is pulling what I want it to, but I just want to present that portion of the result to the user, without the other stuff. Someone else asked a similar question (basically the same) here: how-to-extract-data-from-django-queryset, but the answer makes no sense to me, it is just: k = k[0] = {'name': 'John'} Queryset is list . Can anyone help me with a plain-English explanation of how I can extract just the numerical result of that query for presentation to a user? -
How to bulk get_or_create in Django?
This answer is 10 years old. Is there a more efficient way for doing the following in 2020 with PostgreSQL? for item in item_list: e, new = Entry.objects.get_or_create( field1 = item.field1, field2 = item.field2, ) The above approach hits the DB continuously. Django 2.2 released bulk_update and bulk_create but a bulk_get_or_create doesn't seem to exist? -
How to get class path in Python
In Python, we can define a class and print it as such: class a: num = 1 b = a() print(b) And we would get the output: <class '__main__.a'> I'm trying to identify unique classes, and I have some classes with longer paths. I would like to extract the "class path", or __main__.a in the case above. For example, if I print some longer class I would get: <class 'django_seed.tests.Game'> <class 'django_seed.tests.Player'> <class 'django_seed.tests.Action'> And I would like to extract: 'django_seed.tests.Game' 'django_seed.tests.Player' 'django_seed.tests.Action' Since I can cast <class 'django_seed.tests.Game'> to a string, I can substring it quite easily with '<class 'django_seed.tests.Game'>'[8:-2], but I'm sure there must be a cleaner way. Thanks! -
Django: I dont know want is the wrong with my code
So I was trying to add an imagefield in my model using the UserModel, so I made this models from django.contrib.auth.models import User from django.db import models class ProfileImage(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, editable=False) avatar = models.ImageField() def user_avatar(self): return self.profileimage.avatar User.add_to_class('user_avatar', user_avatar) And I made an admin to see the imagefield in the users, admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin # Register your models here. UserAdmin.fieldsets += ('Custom fields set', {'fields': ('user_avatar',)}), I dont kno what is wrong with my code, when I open a user to see the image field and , does anyone know what is the problem? -
how to display user profile data by id in django
was trying to link the user of a profile to a post they made in django here's what ive tried: views.py def user(request, id): if request.method == 'POST': r_form = upload_resume(request.POST, request.FILES, instance=request.user.profile) if r_form.is_valid(): r_form.save() messages.success(request, f'your resume has been uploaded') return redirect('user') else: r_form = upload_resume(instance=request.user) context = { 'r_form': r_form } return render(request, 'users/profile.html', context) models.py class profile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE, related_name='profile') bio = models.TextField(blank=True) urls.py path('user/<int:id>/', views.user, name='user') and finally html of the profile page <div class="profile-card__name" style="color: #212f3c;">@{{user.get_username}}</div> <div class="profile-card__txt"style="text-align: center;">last seen on {{user.last_login}}</div><br> {%if user.first_name and user.last_name%} <div class="text" style="font-size: 15px;display: flex;-webkit-box-align: center;-ms-flex-align: center;align-items: center;position: relative; align-items: flex-start;padding-left: 20px;"><img class="user_icons" src="{{object.profile.profile_pic.url}}" style="border-radius: 100%;height: 20px;width: 25px;"><b style="padding-left: 10px;">{{user.first_name}} {{user.last_name}}</b></div> {%endif%} {%if object.profile.bio%} <div class="profile-card__txt" style="position: relative;align-items: flex-start;padding-left: 20px;"><b>About me:</b> {{object.profile.bio}}</div> {%endif%} {%if object.profile.current_location%} <div class="text" style="font-size: 15px;display: flex;-webkit-box-align: center;-ms-flex-align: center;align-items: center;position: relative; align-items: flex-start;padding-left: 20px;"><img class="user_icons" src="{% static 'blog/location.svg'%}" style=" height: 25px;width: 25px;padding-right: 5px;"><b>{{object.profile.current_location}}</b></div> {%endif%} when ever i go to user/25/ it renders the information of the current logged in user even with the id of another user..how do i fix this..Thanks in advance :) -
What is the Terminal Command to update code on web server
My configuration is Python 3.81 and window 10 I got a Django Project connected to online server . I connect the webserver first with python manage.py runserver 0.0.0.0:XXXX, Then I amend the codes on my local IDE. After I change the codes .What is the Terminal Command to update codes on web server ? I only got the result of root@localhost:/home/project # sudo supervisorctl restart Project && sudo service nginx restart in Linux Environment How to transform the above codes to WINDOW OS environment applicable? -
Django Rest Framework generics CreateAPIView - how to just include foreign key, without creating one
I am trying to make a generics.CreateAPIView, per the DRF documentation. I have this (I can include my PageSerializer if it would be helpful: class PageCreateView(generics.CreateAPIView): queryset = Page.objects.all() serializer_class = PageSerializer Here is my model: class Page(models.Model): date = models.DateField("Post date") intro = models.CharField(max_length=600) title = models.CharField(max_length=255) chinese = models.TextField(blank=True) english = models.TextField(blank=True) json = JSONField(default=dict, null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE) calculated_hsk = models.DecimalField( default=1, max_digits=3, decimal_places=2) translated = models.BooleanField(default=False) I am trying to use the POST endpoint, however when I have a POST request like this: { "translated": true, "category": 1, "title": "Test POST title", "english": "Test English Text", "chinese": "我是一个兵", "intro": "test intro", "date": "2020-08-02", "calculated_hsk": 3.5, "json": { } } I get the following error: { "category": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } When I try to put it inside a dict, I get requests for fields for the category, which is a totally separate table. I have zero desire to create a new category entry every time I create a new page - I just want to associate the page with the category. How do I do that? -
Running periodic django tasks inside docker
I have a django management-command to scrape a site and update the database accordingly. I plan to run this task every 10 mins continuously. Previously I had written cronjobs to update the database during development but now in production, I am using Docker where I can only run one CMD command which I am using for runserver. RUN python manage.py makemigrations RUN python manage.py migrate CMD [ "python", "manage.py", "runserver", "0.0.0.0:5000" ] RUN touch /var/log/cron.log RUN (crontab -e ; "python manage.py update_db >> /var/log/cron.log") | crontab CMD cron && tail -f /var/log/cron.log I tried something like this and then came to know we cant have 2 CMD in a Dockerfile. I looked at celery but in that case, as well I would have to run that command and would have 2 CMD in a Dockerfile. What would be the best approach in this situation as I am very new to Docker and writing cronjobs. Thanks. -
POST without body on DRF
I am writting an API on Django Rest Framework to follow users. I define a method POST method to follow, but a body is required. I want to do without body or a default body. If I replace POST with GET works, If is it possible and how can I do? class UserProfileViewSet(ModelViewSet): serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() filter_backends = (filters.SearchFilter,) search_fields = ('name', 'email') permission_classes = (UpdateOwnProfile,) @action(methods=['POST'], detail=True, url_path='follow') def follow(self, request, pk=None): user_to_follow = UserProfile.objects.get(pk=pk) request.user.add_relationship( user_to_follow, RELATIONSHIP_FOLLOWING) return Response([], status=status.HTTP_200_OK) -
Obtain the "one" side of the OneToMany relationship without repeated records in a custom Manager
I'm trying to retrieve the one side of the OnetoMany relationship, but this operation is conditioned by some criteria that must be met by the many side: Example # one side class Car(models.Model): # many side class Obligation(models.Model): car = models.ForeignKey(to=Car, on_delete=models.CASCADE) expiration_date = models.DateField(default=date.today) What I am looking for is to obtain all those Car with Obligation whose expiration_date are expired, for the following I have created a manager to perform this operation: class CarManager(models.Manager): """Define a manager for Car model.""" def with_obligations_expired(self) -> "QuerySet[Car]": """Get those cars whose obligations are expired.""" return self.get_queryset().filter( obligation__expiration_date__range=[TODAY] ) The problem If one Car has 2 or 3 Obligation when you run Car.objects.with_obligations_expired() you will obtain: <QuerySet [<Car: car1>, <Car: car1>, <Car: car1>]> The result is a Queryset list with repeated records of cars because many obligations belong to one car then each obligation returns the car that belongs. but I need a list without repeated records. I mean I need to get a list of those cars with expired obligations without repeated records. -
Fail to install pyrebase on windows
My Python version is 3.81 and PC is window 10 I tried to install pyrebase by pip install pyrebase But install fail . Got this error : How to solve ? -
Break up field into its own serializer in Django Rest Framework
Let's say I have simple Product Django model: class Product: name = models.CharField(max_length=255, unique=True) created_on = models.DateField() I'm using Django Rest Framework to serialize this model. I'd like to break up created_on into its own object (including the response from GET requests and the payload in POST requests): { "name": "MyProduct", "created_on": { "year": 2020, "month": 1, "day": 24 } } Here's what I have so far: class DateSerializer(serializers.Serializer): year = serializers.IntegerField() month = serializers.IntegerField() day = serializers.IntegerField() def validate(data): return datetime.date(data["year"], data["month"], data["day"]) class ProductSerializer(serialzers.ModelSerializer): created_on = DateSerializer() class Meta: model = Friend fields = ("name", "created_on") def create(self, validated_data): return Product.objects.create(**validated_data) class ProductViewset(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer This approach works for the GET requests (that is, I get the json above). However, it doesn't work for POST requests (payload being the json above). The response is 400 status code with the message {'created_on': [ErrorDetail(string='This field is required.', code='required')]}. If I pass required=False into DateSerializer, I see self.initial_data in the create method is <QueryDict: {'name': ['MyProduct'], 'created_on': ['year', 'month', 'day']}>. So the values disappear for some reason. Any idea what I'm doing wrong here and how I can get this to work? -
How to print out my inventory for my django web application
I am trying to figure out how to modify my django app to print my inventory to my website. I also need to modify my product page. When a customer clicks on a product on the home page. The customer needs to be redirected to the particular product page. The ID is the primary key. URLS.py: from django.urls import path from . import views from django.http import HttpResponse app_name='home' urlpatterns = [ path('',views.home,name='home'), path('AboutUs/',views.AboutUs,name='AboutUs'), path('LongArmServices/',views.LongArmServices,name='LongArmServices'), path('product/',views.product,name='product'), ] views.py: from django.shortcuts import render from home.models import Products #This is the home view def home(request): products = Product.object.get('Product') return render(request,'home.html', {'product_name':product_name,'product_description':product_description,'product_price':product_price,'product_photo':product_photo}) #This is the About Us page view def AboutUs(request): return render(request,'AboutUs.html') #This is the Long Arm Services View def LongArmServices(request): return render(request,'LongArmServices.html') #This is the product View def product(request): return render(request,'product.html') home.html for loop: <div class="row"> {% for Product in Products%} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="#" alt="Pillow"></a> <div class="card-body"> <h4 class="card-title"> <a href="#">Product Name</a> </h4> <h5 href="#">$20.99</h5> <p href="#"class="card-text">Product Description</p> </div> <div class="card-footer"> <!--<small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small>--> </div> </div> </div> {% enfor %} </div> <!-- /.row --> product.html {% extends 'index.html' %} {% block content %} <h1> This is where the items will … -
How can I link my image folders (having thousands of images) with database in django
I am making a website that will show thousand of images. I have all the images. Images are stored in categories wise folders. I have models like : class Bestplayer(models.Model): image = models.ImageField(upload_to='pics') -
Send data from model signal post_save to view
I am connected to an api then I save all data coming to my DB, I have already setup the signals for that model's post_save. How can I display all new data to my feed without the users needing to reload the page. -
Django: missing request when try to reach a media file
I'm using Django REST Framework as backend and React as front end, I've created a data base where I upload some articles. These articles contains a title, a body and an image. I'm fetching this data base by axios in React and I'm able to render the title and body, but not the image. I think I have to use the absolute path where the image is store but here is the problem, I can't reach that image. Models.py class Article(models.Model): index = models.AutoField(primary_key=True, editable=False) title = models.CharField(blank=False, max_length=150,editable=True) img = models.ImageField(upload_to='articles/', blank=True, null=True) Django Rest Framework dispatcher { "index": 2, "title": "First article", "img": "/media/articles/14-101.jpg", }, settings.py ... STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py ... url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The server does not receive the request when I try to reach 127.0.1.1:8000/media/articles/14-101.jpg. Thank you in advance! -
Change my image url field to absolute url while passing my serializer to another serializer
i've built a model named person and a portfolio which has foreign key of person in it . in my person serializer i have these : class PersonDetailSerializer(serializers.ModelSerializer): skills = serializers.SerializerMethodField() educations = serializers.SerializerMethodField() workplaces = serializers.SerializerMethodField() portfolios = serializers.SerializerMethodField() class Meta: model = Person fields = ('id' , 'full_name' , 'first_name' ,'last_name', 'age' , 'title' ,'nationality' , 'phone' , 'email','img' ,'resume' , 'linkedin' , 'github' ,'instagram','telegram' , 'languages' , 'description','experience' , 'completed_projects', 'skills' , 'educations' , 'workplaces' , 'portfolios' ) def get_skills(self , obj): return SkillSerializer(obj.skills_set.all(), many= True).data def get_educations(self , obj): return EduSerializer(obj.education_set.all() , many=True).data def get_workplaces(self , obj): return WorkSerializer(obj.workplaces_set.all() ,many=True).data def get_portfolios(self , obj): return PortfolioSerializer(obj.portfolio_set.all() , many = True).data and as u can see i'm using get_portfolio to add my portfolio serializer to person serializer which is this: class PortfolioSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ('id' , 'project_name' , 'project_url' , 'project_img' , 'techlonogies_used', 'description' ) and the result of these codes is this response: { "id": "1cc93963-0c50-4edd-9cfb-e5ee97fd5a44", "full_name": "Atabak Hs", "portfolios": [ { "id": 1, "project_name": "rodizio", "project_url": "http://app.test.com/", "project_img": "/media/Coins.jpg", "techlonogies_used": "React - django rest framework - redux -mysql", "description": "this is a hot chipsy grill" } ] } and as … -
Django: How to fix UUID ValueError('badly formed hexadecimal UUID string')? It is new problem
I've stuck at this problem for hours, please help! Here is the detail: Python 3.8 and Django 3.0 Models.py class CustomeUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... class ActivationCode(models.Model): Code = models.CharField(max_length=30, null=False, unique=True) ForUser = models.ForeignKey(CustomUser, null=True, blank=True, on_delete=models.CASCADE) ... Code: jj = {'app_id': '100', 'color': 'blue', 'os_type': 'MacOS', 'time': '1596397345', 'regKey': 'dJbeetbQ', 'os_version': '10.15.6', 'place_id': '20190228-3', 'version': '2.0.0.8', 'guid': '10614ba9b54f909a715ed518cc39741811369a11', 'randomString': '3808651424'} regKey = jj["regKey"] record = ActivationCode.objects.get(Code=regKey) will get exception: value = uuid.UUID(value) File "C:\Users\Ken\anaconda3\lib\uuid.py", line 160, in __init__ raise ValueError('badly formed hexadecimal UUID string') but if I do it this way, I will get the record with no error.: temp_str = 'dJbeetbQ' record = ActivationCode.objects.get(Code=temp_str) I tried: print(type(regKey)) <class 'str'> print(type(temp_str)) <class 'str'> What's the problem here? -
Is there a way to extract data from django templates except the POST method
In one of the pages of my website i m trying to create two buttons save and delete. Save as the name suggests saves the data filled into form in my database. Delete deletes this data. I want to access these two buttons separately in my views.py file but the only way i know to detect user input is checking if request.method == 'POST'. But in the case of both the save and delete button POST request is going to be made. How can i differentiate between the click of delete and save button so that i can write different code for each? -
Getting a boolean value from a Django template tag and using it in an if-filter
The title is fairly self-explanatory. I am trying to get a boolean value from a template tag and use that in an if-filter in my template. So far, I have this: from myproject.settings import DEBUG register = template.Library() @register.simple_tag def is_production(): return not DEBUG And in my template, I am doing this: {% if is_production %} <script src="..."></script> {% endif %} Unfortunately, this does not seem to work, and the script is never actually in the DOM, even if I hard-code the method to return True. What exactly am I doing wrong? Thanks for any help. -
Django Select across three models with filter criteria
I have three models: class Vehicle(models.Model): Vehicle_ID = models.AutoField('ID', primary_key= True) Vehicle_VIN = models.CharField('FIN', max_length=30) Vehicle_DELETED = models.BooleanField('Gelöscht',default=False) class Recall(models.Model): Recall_ID = models.AutoField('ID', primary_key= True) Recall_CODE = models.CharField('Rückruf-Code',max_length=500, unique= True) class Vehicle_Recall(models.Model): Vehicle_Recall_ID = models.AutoField('ID', primary_key=True) Vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) Recall = models.ForeignKey(Recall, on_delete=models.CASCADE) I want to make a Select Statement like this: SELECT * FROM Vehicle INNER JOIN(Recall INNER JOIN Vehicle_Recall ON Recall.ID = Vehicle_Recall.Recall) ON Vehicle.ID = Vehicle_Recall.Vehicle WHERE Recall.ID=1 AND Vehicle.DELETED)=FALSE; Is there a way to make such query in django? -
UnboundLocalError at /checkoutview/. local variable 'shipping_address' referenced before assignment
I got an error "UnboundLocalError at /checkoutview/. local variable 'shipping_address' referenced before assignment. kindly assist me figure it out. I got from the traceback that the problem is on the line in bold - ** billing_address = shipping_address ** views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get( user=self.request.user, ordered=False, ) form = CheckoutForm() context = { "order": order, "form": form } shipping_address_qs = Address.objects.filter( user=self.request.user, address_type="S", default=True ) if shipping_address_qs.exists(): context.update( {"default_shipping_address": shipping_address_qs[0]} ) billing_address_qs = Address.objects.filter( user=self.request.user, address_type="B", default=True ) if billing_address_qs.exists(): context.update( {"default_billing_address": billing_address_qs[0]} ) return render(self.request, "checkout-page.html", context) except ObjectDoesNotExist: messages.info( self.request, f"There exist no default shipping information") return redirect("checkout") def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order = Order.objects.get( user=self.request.user, ordered=False, ) if form.is_valid(): use_default_shipping = form.cleaned_data.get( "use_default_shipping") if use_default_shipping: address_qs = Address.objects.filter( user=self.request.user, address_type="S", default=True ) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info( self.request, f"There exist no default shipping information") return redirect('checkout') else: messages.info( self.request, f"In the absence of default shipping information, new data would be used") shipping_address1 = form.cleaned_data.get( "shipping_address") shipping_address2 = form.cleaned_data.get( "shipping_address2") shipping_country = form.cleaned_data.get( "shipping_country") shipping_zip = form.cleaned_data.get("shipping_zip") if is_valid_form([shipping_address1, shipping_country, shipping_zip]): shipping_address = Address( user=self.request.user, street_address=shipping_address1, apartment_address=shipping_address2, countries=shipping_country, zip=shipping_zip, address_type="S", … -
filter by weekday returns empty JSON, while it should return one object for Sunday, Django Rest Framework
This is very very weird and I cant find a proper solution. I have a Job model That I am trying to serialize. In my view set class I have a function that filters the query set based on the day of the week. According to the documentation, weekday 6 is Sunday so the query set should have one Job in it. However it returns an empty JSON. This is the object that should match that query: expected output and this is the view set function: enter image description here If i hard code int 1 for Sunday then it works, this is quite nerve wrecking, some insight on this will be highly appreciated! -
Django Error NoReverseMatch at / - Django Pattern No Match Error
I tried a lot of solution on internet and tried a lot of URL pattern but nothing working fine. here is my urls.py urlpatterns = [ re_path(r'^category/(?P<cat>\w+)/$',views.categoryPage,name="category"), re_path(r'^',views.home,name="index"), ] html link <a class="nav-link" href='{% url "category" cat=mobiles %}'>Mobiles & Tablets <i class="fa fa-angle-down iconClr" aria-hidden="true"></i></a> and views.py def categoryPage(request,cat): return render(request,'amazonApp/categoryItem.html',context={'category_name':cat}) Error In Browser NoReverseMatch at / Reverse for 'category' with keyword arguments '{'cat': ''}' not found. 1 pattern(s) tried: ['category/<cat>'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'category' with keyword arguments '{'cat': ''}' not found. 1 pattern(s) tried: ['category/<cat>'] Exception Location: C:\Users\DELL\Django\amazon_affiliate\env\lib\site- packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\DELL\Django\amazon_affiliate\env\Scripts\python.exe Python Version: 3.8.5 ] I tried one Django Documentation solution, but it didn't help. -
Advise on learning python :) [closed]
I am beginner to python, thought of picking up django framework directly than learning the syntax or understanding core mechanisms of python. Please advise whats the best way to begin with so that I get proficient at it.