Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
auto download the pdf file right after payment is done
what could be the function to automatically download pdf file automatically right after payment is done and page loads. Actually algorithm guides are there in the media folder but i dont know how to make it download right after payment is made. i am totally clue less help me out please.. views.py def payForAlgorithmGuide(request): print('---------payForAlgorithmGuide--------------') if request.method == 'POST': algoName = request.POST.get('algoName') print('algoName:', algoName) return render(request, 'pay-for-algo-guide.html') models.py class AlgorithmGuide(models.Model): id = models.AutoField(primary_key=True) # buyer_id = models.IntegerField(blank=True, null=True) algorithm_name = models.CharField(max_length=200, blank=True, null=True) guide_data = models.FileField(upload_to=user_directory_path2, null=True, verbose_name="", validators=[FileExtensionValidator(allowed_extensions=['doc', 'docx','pdf'])]) class Meta: db_table = 'AlgorithmGuide' -
how to use two tables inside a query? django
I am trying to use two tables inside one django query. But my query is resulting as "invalid JSON" format. I want to filter data in Request table by (status="Aprv"). The Request table contains attributes 'from_id' and 'to_id'. The uid is the id of the user who is currently logged in. If the current user(uid) is having the 'from_id' of Requests table, the query should return data of 'to_id' from the 'RegUsers' table. If the current user(uid) is having the 'to_id' of Requests table, the query should return data of 'from_id' from the 'RegUsers' table. class frnds(APIView): def post(self, request): uid = request.data['uid'] ob = Requests.objects.filter(status="Aprv") fid = ob.value('from_id') tid = ob.value('to_id') if fid == uid: obj = RegUsers.objects.filter(u_id=tid) else: obj = RegUsers.objects.filter(u_id=fid) ser = android_serialiser(obj, many=True) return Response(ser.data) I dont want to use foreign keys. Please Do Help me Currect the syntax. -
How to get instance of Parent Object and Create Related Child at the same time
Let's say we have: class Parent(Model): pass class Child(Model): parent = ForeignKey(Parent, related_name='children') Now on Child Creation: parent = Parent.objects.get(id=id) Child.objects.create(parent=parent) Here I can see 2 things happening, getting an instance of a parent object and then creating the child object. How I can process it at a time? on child creating. Is it fine to follow the above approach? or we can make it better. -
djagno management command as a package?
I'm trying to have a directory structure for my Django custom commands. According to the Django tutorial commands are created as modules under management/commands directory. e.g. management/commands/closepoll.py I have many commands so I'm trying to split them into packages. I want to have a package structure, like: management/commands/closepoll/closepoll.py <-- contains the Command class. management/commands/closepoll/closepoll_utils.py management/commands/closepoll/__init__.py Tried that, but Django does not recognize the command. -
Send Request From Nextjs to Django Served From Unix Socket
I have a nextjs app and django app running on a linux server. For the purposes of SSR, I am trying to get data from the django app to the nextjs app using getServerSideProps. The easiest I would do this is to send a request from the nextjs app to the django app. This was relatively easy for me to do in development. Requests would be sent to http://localhost:8000, since the django app was using port 8000, from port 3000 which is the port the nextjs app is using. However, in our production server, the django app run on a unix socket, served via gunicorn. upstream app_server { server unix:/path/to/gunicorn.sock fail_timeout=0; } How can I request for data from the django app to the nextjs app when the django app is accessible via unix socket? -
Running kafka consumer with Django
I've setup a kafka server on AWS and I already have a Django project acting as the producer, using kafka-python. I've also setup a second Django project to act as the consumer (kafka-python), but I'm trying to figure out a way to run the consumer automatically after the server has started without having to trigger the consumer through an API call. Everything I've tried so far either runs the consumer and blocks the server from starting or runs the server and blocks the consumer. -
How to modify DateRangeFilter in django admin section?
There is one prebuilt filter DateRangeFilter in django. How to modify the result of filtering data. -
How to restrict a list of fields for a django model generated using _meta.fields by use of a filter
In my project I am trying to retrieve field names of a model which has been selected using a dropdown list. The idea is to list all underlying fields of the selected model, select one of the fields and save the combination in a model for use in a scenario later. To generate the list of fields I am using: model_fields = [fld.name for fld in modelSelected._meta.fields] where modelSelected is the previously selected model (as sent from template using an Ajax function). The set up is working as intended with one caveat. When I start to type in the input field for model field name (using jQuery autocomplete), all the fields of the model are shown in the (selection) list. Is there a way to restrict the field names in what I am attempting to do here? For example, to accomplish an autocomplete on a model HoldingCoy I would be doing: parent_coy = HoldingCoy.objects.filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('holding_coy', 'value', 'label') How can I apply filter to restrict number of fields displayed in the drop down list and achieve a similar effect as used for querying a model instance (as in the above example)? -
Django path didn’t match any of these when adding query param to the endpoint
I am using django 4.1 I have a product model class Product(models.Model): product_id = models.CharField( blank=False, null=False, max_length=50, verbose_name="stock ID", ) name = models.CharField(max_length=30, blank=False) price = models.IntegerField(blank=False) availability = models.IntegerField(verbose_name="product availability") timestamp = models.DateTimeField(auto_now=True) product/urls.py router = routers.DefaultRouter() router.register("product/<slug:product_id>", productViewset, basename="productPrice") urlpatterns = [ path("", include(router.urls)), ] and in project urls.py api_patterns = [ path("", include("product.urls")), ] urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(api_patterns)), ] when I try to call this endpoint"http://127.0.0.1:8000/api/product/2048cf23-6bb2-4532-a140-b13dd1361c4/" it doesn't match any of the paths in my project! NB:product_id is not the primary key as there are more than one row for the same product but at different time and price. I tried to use < str:product_id > < string:product_id > < uuid:product_id > but nothing works,I am not sure why it's happening but when I change the url in product urls.py to router.register("product", productViewset, basename="productPrice") it works but I need to path that id to filter the queryset. the error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/api/product/2048cf23-6bb2-4532-a140-b13dd1361c4/ Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: admin/ api/ ^product/<slug:product_id>//$ [name='productPrice-list'] api/ ^product/<slug:product_id>\.(?P<format>[a-z0-9]+)/?$ [name='productPrice-list'] api/ ^product/<slug:product_id>//(?P<pk>[^/.]+)/$ [name='productPrice-detail'] api/ ^product/<slug:product_id>//(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='productPrice-detail'] api/ ^$ [name='api-root'] api/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] … -
Trouble combining CustomUser and Profile into single endpoint in django
I have a CustomUser model and two separate Models for profile two types of User. I'm trying to combine the attribute of CustomUser and one of the Profile into single endpoint from which the user can see/update/delete the user/profile. For instance there are 2 types of users, doctor & patient. so if the user is doc then the endpoint will return the attributes of CustomUser+DoctorProfile and same for the Patient CustomUser+PatientProfile. Below is the code. I will explain the issue in the code base with comments. I will enormously appreciate any suggestion. One thing to mention is that I split the models.py file into 3 different folder and imported all of them into __init__.py of models folder. CustomUser Model: class CustomUser(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): DOCTOR = "DOCTOR", "Doctor" PATIENT = "PATIENT", "Patient" # what type of user type = models.CharField(_("Type"), max_length=50, choices=Types.choices, null=True, blank=False) avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomBaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'type'] #email is required by default def get_full_name(self): return self.name def __str__(self): return self.email DoctorProfile Model: class DoctorProfile(models.Model): class DoctorType(models.TextChoices): """Doctor will choose profession category from enum""" PSYCHIATRIST = … -
How to correctly write view for saving file?
My model looks like this: class Document(models.Model): id: int = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # type: ignore order_id: str = models.CharField(max_length=255) # type: ignore publicated_at: datetime = models.DateTimeField(null=True) # type: ignore expired_at: datetime = models.DateTimeField(null=True) # type: ignore created_at: datetime = models.DateTimeField(auto_now_add=True) # type: ignore updated_at: datetime = models.DateTimeField(auto_now=True) # type: ignore department: Department = models.ForeignKey(Department, on_delete=models.DO_NOTHING, null=True, blank=True) # type: ignore file_name: str = models.CharField(max_length=255) # type: ignore owner: CustomUser = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, null=True, related_name='owned_documents') # type: ignore loaded_by: CustomUser = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='loaded_documents') # type: ignore file_id: str = models.CharField(max_length=255, null=True, blank=False) # type: ignore metrics: Metric = models.ManyToManyField(Metric, through="DocumentsMetrics", related_name="documents") # type: ignore document_status: DocumentStatus = models.ForeignKey(DocumentStatus, on_delete=models.SET_NULL, null=True) # type: ignore issue: str = models.TextField(null=True, blank=True) # type: ignore suggestion: str = models.TextField(null=True, blank=True) # type: ignore class Meta: app_label = 'library' mongo_file_key = 'file_id' def upsert_document(self, buffer: IStream) -> None: file_ms.update_from_bytes(self, self.mongo_file_key, buffer) def get_document_bytes(self) -> IStream | None: return file_ms.get_bytes(self, self.mongo_file_key) def save_document(self, path: str) -> None: with open(path, 'wb') as f: I am storing a "Document" object in PostgreSQL. In the file_id field, I insert the id from mongoDB. My model has method upsert_document to save file to mongo which returns mongo_id. … -
Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['delete/(?P<slug>[^/]+)/\\Z']
Been stuck at this trying to delete data from the database, i'm clearly lost with the logic somewhere i'd grately appreciate any assistance. resume-detail.html <div class="row"> {% if educations %} {% for education in educations %} <div class="col-lg-12 mt-4 pt-2"> <div class="component-wrapper rounded shadow"> <div class="p-4 border-bottom bg-light"> <h4 class="title mb-0">{{education.institution}}</h4> </div> <div class="p-4"> <div class="row"> <div class="col"> <p><strong>Qualification: </strong> {{education.qualification}}</p> </div> <div class="col"> <p><strong>Level of Qualification: </strong> {{education.level}}</p> </div> </div> <div class="row"> <div class="col"> <a href="{% url 'delete' educations.slug %}" class="btn btn-danger">Delete Qualification </a> <!-- <button class="btn btn-danger">Delete Qualification</button> --> </div> </div> </div> </div> </div> {% endfor %} {% endif %} </div> <div class="row"> <div class="col-lg-12 mt-4 pt-2"> <h4 class="text-dark"><button type="button" class="btn btn-secondary-outline btn-outline-success" data-toggle="modal" data-target="#addEducation"><span class="mr-2">+</span> Add Education</button></h4> </div> </div> i'm using a modal to capture this data <div class="modal fade" id="addEducation" tabindex="-1" aria-labelledby="addEducationLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <form action="{% url 'delete' educations.slug %}" method="POST"> {% csrf_token %}.... urls.py path('userapp/view/<slug:slug>/', user_views.resume_detail, name='resume-detail'), path('delete/<str:slug>/', user_views.delete_view, name='delete' ) views.py def delete_view(request, slug): obj = Resume.objects.get(id = slug) if request.method =="POST": obj.delete() messages.success(request,"Information Deleted Successfully") return redirect('resume-detail', id = slug) educations = Education.objects.get(resume = obj) experiences = Experience.objects.get(resume = obj) context = {} context['object'] = obj context['educations'] = educations context['experiences'] … -
Not getting results from searched in Django app
I am traying to create a simple search option in Django. But I am not getting any results after the search from the model. files: model.py class ChoresPost(models.Model): # Job post ChoresPost_TYPE_CHOICE = ( # job category ('1', 'Vodoinstalater\ka'), ('2', 'Eelektricar\ka'), ('3', 'Moler\ka'), ('4', 'Stolar\ka'), ('5', 'IT'), ('6', 'Zidar\ka'), ('7', 'Cistac\ica') ) user_of_post = models.ForeignKey(ClientsUsers, null=True, on_delete=models.CASCADE) post_id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50, null=False, blank=False, db_index=True) bio = models.TextField(null=False, blank=False) date_of_post = models.DateTimeField(auto_now=True) category = models.CharField(max_length=100, choices=ChoresPost_TYPE_CHOICE) budget = models.IntegerField(default=0) date = models.DateField(null=True) view.py def search_venues(request): if request.method == "POST": searched = request.POST['searched'] venues = ChoresPost.objects.filter(name__icontains=searched) return render(request, 'search_venues.html', {'searched': searched, 'venues': venues}) else: return render(request, 'search_venues.html', {}) urls.py urlpatterns = [ path('AddNewOffer/', AddOfferPage, name='AddNewOffer'), path('Offers/', OfferView, name='OfferView'), path('Offer/<int:pk>', ShowOffer.as_view(), name='ShowOffer'), path('search_venues/', search_venues, name='searchvenues'), ] In project.html, I set my search fields: <form class="d-flax" method="POST" action="{% url 'searchvenues' %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" name="searched"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> A page for displaying the result search_venues.html {% block content %} {% if user.is_authenticated %} {% if searched %} <h1>You searched for {{ searched }}</h1> {% for venue in venues %} <p>{{venue}}</p> #here I am not getting any results {% endfor%} {% else %} <h1>No result</h1> … -
Getting 'draw' datatables value on Django
I'm using datatables Server-side processing official documentation with Django and I'm not very clear with the documentation, below I describe the problem I'm having, I hope someone can help me. Thanks in advance. In my view.py I am getting the draw value sent by DataTables as follows: draw = request.GET.get("draw") and then I am sending it along with other necessary parameters to my JSON as follows: records = MyObject.objects.all().count() response = { 'draw': draw, 'recordsTotal': records, 'recordsFiltered': records, 'data': data } return JsonResponse(response) The problem I am having is that I receive the value of draw as a string and I have to send it as an int, maybe I'm understanding something wrong, the point is that I do not clarify, Paging and search are also not working. Could someone explain how it works? I have been reading for hours and I still have a lot of doubts. -
TypeError: User() got unexpected keyword arguments: 'reg_data_l' & You may need to make the field read-only, or override the UserSerializer.create()
Models.py class User(AbstractUser, PermissionsMixin): is_admin = models.BooleanField(default=False) is_librarian = models.BooleanField(default=False) is_member = models.BooleanField(default=False) class Librarian(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) librarian_firstname = models.CharField(max_length=20) librarian_middlename = models.CharField(max_length=20) librarian_lastname = models.CharField(max_length=20) CATEGORY_GENDER = (('Male','Male'),('Female','Female')) librarian_gender = models.CharField(max_length=6, choices=CATEGORY_GENDER) librarian_contact = models.CharField(max_length=10, unique=True, blank=True) librarian_photo = models.ImageField(upload_to = 'media/librarian_photo', default='media/default.webp', blank=True) librarian_address = models.CharField(max_length=100) def __str__(self): return str(self.librarian_firstname)+ ' - '+(self.librarian_lastname) def save(self, *args, **kwargs): for field_name in ['librarian_firstname', 'librarian_middlename', 'librarian_lastname']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Librarian, self).save(*args, **kwargs) class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) member_firstname = models.CharField(max_length=20) member_middlename = models.CharField(max_length=20) member_lastname = models.CharField(max_length=20) CATEGORY_GENDER = (('Male','Male'),('Female','Female')) member_gender = models.CharField(max_length=6, choices=CATEGORY_GENDER) member_contact = models.CharField(max_length=10, unique=True, blank=True) member_photo = models.ImageField(upload_to = 'media/member_photo', default='media/default.webp', blank=True) member_address = models.CharField(max_length=100) def __str__(self): return str(self.member_firstname)+ ' - '+(self.member_lastname) def save(self, *args, **kwargs): for field_name in ['member_firstname', 'member_middlename', 'member_lastname']: val = getattr(self, field_name, False) if val: setattr(self, field_name, val.capitalize()) super(Member, self).save(*args, **kwargs) class Books(models.Model): book_name = models.CharField(max_length=50) book_author = models.CharField(max_length=30) book_isbn = models.PositiveIntegerField() def __str__(self): return str(self.book_name) serializer.py class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('member_firstname','member_middlename','member_lastname','member_gender', 'member_contact','member_photo','member_address') class UserSerializer(serializers.ModelSerializer): reg_data = MemberSerializer() class Meta: model = User fields = ('username','password','reg_data',) def create(self, validated_data): reg_info = validated_data.pop('reg_data') user_reg = User.objects.create(**validated_data) user_reg.set_password(validated_data['password']) user_reg.save() Member.objects.create(user=user_reg, **reg_info) … -
how to use model in django view
I want to use my model parameter for the API query parameter in Django View. How can I use this? Anyone can give me suggestions. Here curd is my model name. and consumer_type is the required query parameter from .models import curd for consumer_type in curd: response = requests.get("http://localhost:8280?ConsumerID="+consumer_type) -
How to avoid path duplication of images downloaded to database with django form
I have a problem with django ImageField. To be precise, with its download path and saving to database. I`ve set upload_to to the directory needed, and it saves files right where it should be. photo = models.ImageField( default="Person-595b40b65ba036ed117d315a.svg", upload_to="static/img", ) There should also be no problems with retrieving those photos as I added my directory to STATICFILES_DIRS: STATIC_URL = "static/" STATICFILES_DIRS = ( BASE_DIR / "static", "static/img", ) But when it comes to the database, my photos are saved like this and when it comes to retrieving, django firstly goes to my static files directory, which is static/img and the searches for static/img/static/img/images.png which is not found for sure. static/img/images.png So my question is how to avoid path duplicating in database? How to make my images download to specified directory but appearing in the database without path so I could retrieve it without any changes in db? Thanks in advance!!! -
How to implement Like feature similar to Instagram with Django using ajax?
hi I have been making a social media site with a like feature similar to Instagram where user does not need to view the individual post to like it but can like that post directly from the main page , how can i do that ? my main template: {% load static %} {% if user.is_authenticated %} {% if obj %} <h1 style="background:skyblue;text-align:center;">Posts</h1> {% for obj in obj %} <div style="background:lightgrey;border-radius:5px;margin-bottom:20px;padding:1rem;"> <form method="get"> <input hidden value="{{obj.id}}" name="liked_post_id"> </form> <p>{{obj.user}}</p> <p>{{obj.name}}</p> <img height="250px" width="100%" src="{{ obj.image.url }}" alt="Image "> <p>{{obj.desription}}</p> <!-- {% include "like_page.html" %}--> <button id="btn_1" name="btn_1" type="submit" value="{{ obj.id }}">like </button> <span id="like_count">{{obj.like_count}}</span> <h4>add a comment</h4> {% include "comments.html" %} </div> {% endfor %} {% else %} <h1 style="background:skyblue;text-align:center;">No Posts available</h1> {% endif %} {% endif %} my urls : from django.urls import path from .views import index, show, LikeView, addComment\ # , likeviewNumber urlpatterns = [ path("", index, name="home"), path("show", show, name="show"), path("like/", LikeView, name="post_like"), path("comment/",addComment, name="comment" ), # path('like_num',likeviewNumber ) ] the ajax I used: <script src="{% static 'jquery-3.6.0.js' %}" type="text/javascript"></script> <script> $(document).on('click','#btn_1',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "post_like" %}', data:{ postid:$('post_id').val(), // idher mene abhi name=Post_id use kia ha <like_page.html> k ander /warna yahan par buton … -
how to sum model in Django rest Api
I am new to Django rest Api devlopment I want to sum rent_amount, bijli_bill, other_amount and get value as Total amount, i dont know to add them pls help I want value like this { "id": 1, "rent_date": "23-08-2022", "rentmonth": "June", "rent_amount": 500.0, "bijli_bill": 200.0, "other_amount": 100.0, "other_commnet": "test", "total_amount": 800.0, } This the model file from sqlite3 import Date from django.db import models from django import forms from django.contrib.auth.models import User class rent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # id=models.IntegerField(primary_key=True) rent_date = models.DateField(auto_now_add=True) rentmonth = models.CharField(max_length=30) rent_amount = models.FloatField() bijli_bill = models.FloatField() other_amount = models.FloatField(blank=True) other_commnet = models.CharField(blank=True, max_length=200) This is my serializer from rest_framework import serializers from .models import rent from django.contrib.auth.models import User from django.db.models import Sum class rentSerializer(serializers.ModelSerializer): rent_date = serializers.DateField(format="%d-%m-%Y", read_only=True) rentmonth = serializers.CharField() rent_amount = serializers.FloatField() bijli_bill = serializers.FloatField() other_amount = serializers.FloatField() other_commnet = serializers.CharField(max_length=200) class Meta: model = rent fields = ('__all__') This is view file class rentViews(APIView): def get(self, request, id=None): if id: item = rent.objects.get(id=id) serializer = rentSerializer(item) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) items = rent.objects.all() serializer = rentSerializer(items, many=True) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) -
Django can't add new item to another database on admin site
I'm using two databases to create an app and everything looks fine, I can change, delete the existing item but can't add new item to other database table on the admin site. The data should be stored in dbcost.tbItemDetail instead of userauth.tbItemDetail. Does anyone know how to correct this? Thanks Here is the code: code on admin.py: from unicodedata import name from django.contrib import admin from .models import * #Create MultiDBModelAdmin to expose multiple databases for admin site class MultiDBModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): # Tell Django to save objects to the other database. obj.save(using=self.using) def delete_model(self, request, obj): # Tell Django to delete objects from the other database obj.delete(using=self.using) def get_queryset(self, request): # Tell Django to look for objects on the other database. return super().get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): # Tell Django to populate ForeignKey widgets using a query # on the other database. return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): # Tell Django to populate ManyToMany widgets using a query # on the other database. return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs) # Register your other database here: class tb_companyinfo(MultiDBModelAdmin): using = 'dbcost' #select database name list_display = ('name','emailaddress',) #add different fields into admin … -
SQLAlchemy ORM group_by and join
I have a query query = session.query(portfolioAnalysis_portfoliomain,portfolioAnalysis_stocklist, stock_companymaster, stock_industrymaster,func.count(stock_industrymaster.c.INDUSTRY).label('count_ind'))\ .filter(portfolioAnalysis_portfoliomain.c.user_id==user_dt.id)\ .join(portfolioAnalysis_stocklist, portfolioAnalysis_stocklist.c.portfolio_id==portfolioAnalysis_portfoliomain.c.id)\ .join(stock_companymaster, stock_companymaster.c.FINCODE==portfolioAnalysis_stocklist.c.stock_id)\ .join(stock_industrymaster, stock_industrymaster.c.IND_CODE==stock_companymaster.c.IND_CODE)\ .group_by(portfolioAnalysis_stocklist.c.id)\ .all() I wnat the data as ('Refinary', 2) ('Banking', 3) but I am getting the data as ('Refinary', 1) ('Refinary', 1) ('Banking', 1) ('Banking', 1) ('Banking', 1) I tried the below query but it throws error. query = session.query(portfolioAnalysis_portfoliomain,portfolioAnalysis_stocklist, stock_companymaster, stock_industrymaster,func.count(portfolioAnalysis_stocklist.c.id).label('count_ind'))\ .filter(portfolioAnalysis_portfoliomain.c.user_id==user_dt.id)\ .join(portfolioAnalysis_stocklist, portfolioAnalysis_stocklist.c.portfolio_id==portfolioAnalysis_portfoliomain.c.id)\ .join(stock_companymaster, stock_companymaster.c.FINCODE==portfolioAnalysis_stocklist.c.stock_id)\ .join(stock_industrymaster, stock_industrymaster.c.IND_CODE==stock_companymaster.c.IND_CODE)\ .group_by(stock_industrymaster.c.INDUSTRY)\ .all() -
Retrieving ID atribute from URL
In my django project i have a url: https://example.com/nice_page#123 This url will lead user to particular post on my page, this is an example how it works on stackoverflow: What is the "N+1 selects problem" in ORM (Object-Relational Mapping)? (it is a link to particular answer, and your browser will move you right to this answer.) My goal is to get this #123 id from url. I can't do it with django's META data by request.META it doesn't show this #123 id, it only returns me https://example.com/nice_page How can i get this #123 id? I would prefer making it with django, but javascript is also acceptable. -
Loading css from static files in django not working
this is what the file explorer looks like this is the html file userController/templates/users/dashboard.html {% extends 'base.html' %} {% load static %} <html> <head> /* loadint the css */ <link rel="stylesheet" href="{% static 'css/dashboard.css' %}"> demowebsite/settings.py # STATIC_DIR=os.path.join(BASE_DIR,'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'userController/static/') ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') the css file is not getting loaded, i cant tell where my problem is -
Django - how to add items to ManyToMany field from Queryset
What I am trying to achieve is to get the title that the user inserted in the form and save it in all components that are currently in the cart. This piece of code contains the items that are currently in the cart: get_components = user.cart_component.all() It gives me a queryset like this: <QuerySet [<ProductComponents: component 1>, <ProductComponents: component 2>, <ProductComponents: component 3>]> I am also able to get the title from the form by using get('title'). What I am struggling with is how can I add all components from get_component to the newly created template. I am getting the following error: Field 'id' expected a number but got 'test template'. my post method in TemplateView: def post(self, *args, **kwargs): ce_template_form = SaveAsTemplateForm(data=self.request.POST) if ce_template_form.is_valid(): template_title = ce_template_form.cleaned_data.get('title') user = self.request.user get_components = user.cart_component.all() for component in get_components: component.template.add(template_title) # how can I pass id here? ce_template_form.save() return redirect('cart') models.py class UserTemplate(models.Model): title = models.CharField(max_length=200) class CostCalculator(models.Model): [...] template = models.ManyToManyField(UserTemplate, related_name='user_template', blank=True, default='-') -
crontab django Erorr
hello everyone im trying to start simple crontab-django job scheduled as i will show you in the code below My os is Ubuntu 20.04 this is the myapp/cron.py file as mentioned in the documentation cron.py from .models import Cats def my_scheduled_job(): Cats.objects.create(text='Testt') and this is the settings i used frm the documentation CRONJOBS = [ ('*/1 * * * *', 'coins.cron.my_scheduled_job') ] INSTALLED_APPS = ( 'django_crontab', ... ) i keep getting this error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django_crontab/crontab.py", line 126, in run_job job = self.__get_job_by_hash(job_hash) File "/home/madahsm/python projects/corntab/lib/python3.8/site-packages/django_crontab/crontab.py", line 171, in __get_job_by_hash raise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! even i tried to add python manage.py crontab add again and show and it appears python manage.py …