Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SQL query to ORM implementation involving Joins and Group By
This query should return the total sum of (quantity - qty_fulfilled) grouped by product_id. I'm stuck trying to convert this postgres sql query into an ORM query. This sql query works, but get_queryset() method in the Admin models does not support RawQueryset as indicated here, so this needs to be in a Queryset form. select t1.id, t3.req_from_orders from inventory_inventory t1 left join product_app_product t2 on t1.product_id = t2.id left join ( select product_id, sum(quantity) - sum(qty_fulfilled) as req_from_orders from order_app_cartitem oac group by oac.product_id ) t3 on t1.product_id = t3.product_id Models: * Inventory * product_id (OneToOneField) * id (UUID) * Product * id (UUID) * CartItem * id (UUID) * product_id (ForeignKey) * quantity (int) * qty_fulfilled (int) * Inventory <-> Product <-* CartItem Tried using annotate(RawSQL="<query>", params=(param,)) but params cannot take in dynamic ids. Any help would be greatly appreciated. -
DRF - APIView and Serializing a model with multiple foreign Keys(User)
How to save multiple foreign keys(User) data? models class HireProfessional(models.Model): hireBy = models.ForeignKey(User, related_name='owner', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") hire_start_date_time = models.DateTimeField(default=timezone.now) hire_end_date_time = models.DateTimeField(default=timezone.now) seriliazer class HireProfessionalSerializer(serializers.ModelSerializer): class Meta: model = HireProfessional fields = '__all__' views class HireProfessionalCreateApp(APIView): permission_classes = (IsAuthenticated, IsClientUser,) def get_user(self): user = self.request.user return user def post(self, request, pk, format=None): user = User.objects.filter(id=pk).first() serializer = HireProfessionalSerializer(data = request.data, instance=user) data = {} if serializer.is_valid(): hire = serializer.save(owner=self.get_user()) data['hireTo'] = hire.hireTo return JsonResponse ( { "message":"professional hired success.", "success" : True, "result" : data, "status" : status.HTTP_201_CREATED } ) else: data = serializer.errors return Response(data) It returns hireBy, user: "This field is required." how do I solve this problem? Does anybody have any idea? -
django filters icontains with __in lookup
Similar to this question: django icontains with __in lookup I am attempting to filter a single field with multiple values using the django-filters package. For example, I have a model Content with field paragraph. I want to return the object if Content.paragraph contains string "McDonald" or Content.paragraph contains string "MacDonald". Essentially be able to pass multiple icontains to a single field. Thanks! -
Nginx is rendering the wrong website. Does anyone know why?
My website 1 Nginx .conf file is rendering website 2 on my server. So both websites render website 2. I want website 1 to render a Django website. Website 2 is just a normal HTML website. The files for both the websites are located in /home/webserver not in /var/www. Website 1: # the upstream component nginx needs to connect to upstream django { server unix:///home/webserver/exo_dashboard/dashboard/exo.sock; } # configuration of the server server { listen 80; server_name beta.exobot.xyz www.beta.exobot.xyz; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media/ { alias /home/webserver/exo_dashboard/dashboard/media; } location /static/ { alias /home/webserver/exo_dashboard/dashboard/static/; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/webserver/exo_dashboard/dashboard/uwsgi_params; } } Website 2: server { root /home/webserver/website; index index.html index.htm index.nginx-debian.html; server_name exobot.xyz www.exobot.xyz; location / { try_files $uri $uri/ =404; } location = /arc-sw.js { proxy_pass https://arc.io; proxy_ssl_server_name on; } listen [::]:443 ssl; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/exobot.xyz/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/exobot.xyz/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = exobot.xyz) { return 301 … -
how to change color help text using crispy tags
I am trying to use cripsy forms for a django website, everything works fine but as you can see my background isn’t white,but blue so the help text doesn’t stand out How can I change the color of the helper text? -
Unable to make correct migrations in Django
I cannot make correct migrations with one specific fields image_two in my Django Project. I have also configured Django-Rest and all this is connected to AWS. Endpoint is looking alright and I am getting correct url from image_one and image_two. But I don't know how to create a column in database for storage this image URL. Yes, I have read documentation from ImageKIT and they said: ImageSpecFields, on the other hand, are virtual—they add no fields to your database and don’t require a database. This is handy for a lot of reasons, but it means that the path to the image file needs to be programmatically constructed based on the source image and the spec. In ImageKIT there is also ProcessedImageField, but this is not an option for me, because I have to also save in database source image and send it to AWS S3. from django.db import models from imagekit import ImageSpec, register from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill from imagekit.utils import get_field_info class ImageTest (models.Model): name = models.CharField(max_length=50, blank=False) added_at = models.DateTimeField(auto_now_add=True) image_one = models.ImageField(null=True, blank=False) new_width = models.PositiveIntegerField(blank=False) new_height = models.PositiveIntegerField(blank=False) image_two = ImageSpecField(source='image_source', id='myapp:imagetest:resizeme',) class ResizeMe(ImageSpec): format = 'JPEG' options = {'quality': 80} @property … -
Django filtering models in Foreign Key
Models.py class AdmissionStudent(models.Model): studentlabel = models.CharField(max_length = 100, null = False, blank = False) def __str__(self): return self.studentlabel class AdmissionRequirement(models.Model): requirementstudent = models.ForeignKey(AdmissionStudent, on_delete = models.CASCADE, null = False, blank = False) requirementparagraph = models.TextField(null = False, blank = False) def __str__(self): return '{} - {}'.format(self.requirementstudent, self.requirementparagraph) Views.py def admission(request): header = AdmissionHeader.objects.first() student = AdmissionStudent.objects.all() requirement = AdmissionRequirement.objects.all() context = { 'header': header, 'student': student, 'requirement': requirement, 'title':'Admissions' } return render(request, 'pages/admission.html', context) Admission.html (template) {% for student in student %} <b>{{ student.studentlabel }}</b><br> {% if {{ student.studentlabel}} == {{requirement.requirementstudent }} %} {% for requirement in requirement %} {{ requirement.requirementparagraph }}<br> {% endfor %} {% endfor %} I know what I did in my template is stupid, but i really don't know how to filter Admission Requirements for enrollment, Below is an example of how I want it to appear: Transferee -1st requirement -2nd requirement -3rd requirement Foreign Student -1st requirement -2nd requirement -etc -
Convert QuerySet into List in Django for ModelMultipleChoiceField
TIMESLOT_LIST = ( (5, '09:00 – 09:30'), (9, '09:30 – 10:00'), (2, '10:00 – 10:30'), ) class AvailabilitiesForm(forms.Form): time_slot = forms.ModelMultipleChoiceField(queryset = None, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): date = kwargs.pop('date') super(AvailabilitiesForm, self).__init__(*args, **kwargs) #choices = getChoices(letter) self.fields['time_slot'].queryset = Appointment.objects.filter(date = date).values_list('time_slot', flat = True) This displays : I want : How can I use the TIMESLOT_LIST to display the string "9h00 - 9h30" and not 5 ? While passing through, how can I can withdraw the bullet points ? -
How to update item quantity on django ecommerce project
I am trying to update the quantity of my cart when I use click the add to cart button. I have been trying to figure out the logic behind it but cannot seem to get it. I believe under my views.py I am adding an item to the cart but it is not working. Can anyone give me some direction on this? main.Html <button href="{% url 'add_cart'%}" class="btn btn-primary add-cart">Add to Cart</button> urls.py urlpatterns = [ path('add_cart', views.add_cart, name='add_cart') ] Views.py def add_cart(request, slug): product = get_object_or_404(Product, slug=slug) item = Item.objects.create(product=product) order = Order.objects.filter(user=request.user, ordered=False) if order.exists(): order = order[0] if order.items.filter(item_slug=item.slug).exists(): item.quantity += 1 item.save() else: order = Order.objects.create(user=request.user) order.items.add(item) return redirect('main') models.py class Product(models.Model): img = models.CharField(max_length=30) product_name = models.CharField(max_length=250, null=True) price = models.CharField(max_length=250, null=True) description = models.TextField() slug = models.SlugField() def __str__(self): return self.product_name class Shopper(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=250, null=True) email = models.CharField(max_length=250, null=True) def __str__(self): return self.name class Order(models.Model): shopper = models.ForeignKey( Shopper, on_delete=models.SET_NULL, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) trans_id = models.CharField(max_length=250, null=True) ordered = models.BooleanField(default=False) def __str__(self): return str(self.trans_id) @property def cart_total_items(self): total_items = self.item_set.all() cart_total_items = sum([item.quantity for item in total_items]) return cart_total_items def cart_total(self): total_items = … -
How to float text in the input box in javascript?
I want to text the code I wrote in JavaScript into the input box. However, there is a problem that the input box is not outputting text. The input box I want to print is in html. The content is as follows: <input name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "원 Is there a problem with my source code? I wonder why the text doesn't appear. Wise developers, please help me solve this problem I'm facing. script function pay_unit_func($par, unit_amount, quantity) { //1번 단 var unit_total_amount = $par.find('.price_amount').text((unit_amount * quantity).toLocaleString()); } function pay_total_func() { //2번 단 var amount_total = 0; var converse_unit = 0; $('.cart_list li').each(function () { converse_unit = $(this).find('.price_amount').text().replace(/[^0-9]/g, ""); amount_total = amount_total + (parseInt(converse_unit) || 0); }); var total_amount_money = $('.cart_total_price').children().find('.item_price').getElementsByClassName("item_price").text(amount_total.toLocaleString()); var total_total_price = $('.cart_total_price').children().find('.total_price').text(total_price.toLocaleString()); } html " <div class=\"total_p\" style='margin-top:30px; margin-left: -2px;'>\n" + " <p style=\"font-size: 18px;\">가격<input name=\"price2\" id=\"price2\" class=\"price_amount\" style=\"font-size: 18px; color: #849160; margin-left: 180px;\">" + 0 + "원\n" + " </div>\n" + **All Sourcecode ** <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = parseInt($(this).find(':selected').data('price')); var hapgae = price + test if (checkValue … -
Is there a way to prevent Django from trimming leading white space in a text field?
Is there a way to prevent Django from trimming leading white space in models.TextField? I've been scouring the docs and haven't found anything. The database I'm using is PSQL. Any guidance would be appreciated. -
Is there a better way to get the created object?
I have this code and I want to store this created user and question in a variable in one line instead of doing it this weird way, is this even possible?: if UserProfile.objects.filter(discord_id=request.data['author_id']).exists(): profile = UserProfile.objects.get(discord_id=request.data['author_id']) else: x = UserProfile.objects.create(discord_id=request.data['author_id'], name=request.data['name']) profile = UserProfile.objects.get(discord_id=request.data['author_id']) Question.objects.create(title=request.data['title'], author=profile, points=int(request.data['points'])) question = Question.objects.filter(author=profile, title=request.data['title'])[0] -
Django duplicated query causing slow loading
I'm having trouble finding a solution for duplicated queries, I tried doing this. Code: for c in coupons: fname = Users.objects.filter( id=c['WhoReviewed']).values('first_name') lname = Users.objects.filter( id=c['WhoReviewed']).values('last_name') for f in fname: first = f['first_name'] for l in lname: last = l['last_name'] full = first + ' ' + last c['WhoReviewed'] = full Result: -
How to fix NoReverseMatch error in Django for the getting and displaying user specific data in ListView
Hey I have a video sharing webapp project with basic CRUD operations in it. Any user after successful login can post any number of videos and after login the user is redirected to home page of another app inside the django project. Home page shows all the videos uploaded by different users. Now I want place all the videos uploaded by the user at an seprate endpoint. If user clicks on this endpoint link in the nav-bar then the user should be directed to this endpoint containing all the videos uploaded by him/her. I am using builtin class based view ListView for this purpose and I have just one model of Video. But I am getting Noreversematch error after performing get_queryset() function and here is my error : part of views.py class UserUploads(LoginRequiredMixin, ListView): model = Video template_name = 'courses/user_uploads.html' context_object_name = 'videos' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Video.objects.filter(uploader=user).order_by('-date_time') def get_success_url(self): return reverse('courses:video-detail', kwargs={'pk': self.object.pk}) part of urls.py from django.urls import path, include from django.contrib import admin from . import views from .views import CreateVideo, DetailVideo, UpdateVideo, DeleteVideo app_name = "courses" urlpatterns = [ path('', views.Index.as_view(), name = "home"), path('user-uploads/<str:username>', views.UserUploads.as_view(), name = "user-uploads"), path('create-video', CreateVideo.as_view(), name='video-create'), path('<int:pk>/', … -
how to display list of LANGUAGES in django template
i'm trying to show languages label list in my template , but it only shows the original name of the language my settings.py LANGUAGES = ( ('en', _('english uk')), ('ar', _('arabic uae')), ('fa', _('Persian')), ) my template <li class="nav-item dropdown"> <a class="nav-link" data-toggle="dropdown" href="#"> <i class="fas fa-globe"></i> </a> <div class="text-center dropdown-menu dropdown-menu-lg dropdown-menu-right"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <a class="dropdown-item" href="/{{lang.code}}/"> {{lang.name_local}}</a> {% endfor %} </div> </li> is it possible please ? thank you for helping .. -
dynamic form in django using choiceField
I'm building my first web app with django and am having a hard time figuring out how to use dynamic form in order to have diffent output for different selected choice. for example for my mesure choice qualitative, I want the form be the same(no extra fields) but if the quantitative value is selected, I want my template to show tow more fields(value_min and Value_max) the first option when qualitative value is selected the second option when quantitative value is selected thank you for your help... -
How to get users back after deploying Django App to Heroku
I've deployed a React/Django app on Heroku and when I tried to login, I found out none of the users I had locally were present on the deployed App. I thought it could be that it didn't migrate so I did heroku run python manage.py makemigrations heroku run python manage.py migrate Got no migrations to apply so I now have an app without an Admin account and I don't know how I could create one nor access the one I had locally Ps: I'm using Sqlite database on it -
Filter objects of a manytomanyfield inside another model
I am a beginner programming learning django. I'm trying to build a contacts app much like google contacts. users have to log in to create contact groups and contacts. problem: when a user creates a group, it shows up in the form field for a different user. How do I restrict groups created by a user to only that user. Models.py from django.db import models from django.contrib.auth.models import User from uuid import uuid4 class Group(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, unique=True, editable=False) owner = models.ForeignKey(to=User, on_delete=models.CASCADE, editable=False) group_name = models.CharField(max_length=255, verbose_name="Group Name") def __str__(self) -> str: return str(self.group_name) class Contact(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, unique=True, editable=False) owner = models.ForeignKey(to=User, on_delete=models.CASCADE, editable=False) first_name = models.CharField(max_length=256, verbose_name='First Name', blank=True, null=True) last_name = models.CharField(max_length=256, verbose_name='Last Name', blank=True, null=True) other_names = models.CharField(max_length=256, verbose_name='Other Names', blank=True, null=True) nick_name = models.CharField(max_length=256, verbose_name='Nickname', blank=True, null=True) phone = models.CharField(max_length=256) groups = models.ManyToManyField(to=Group, null=True, blank=True) views.py from rest_framework import viewsets from rest_framework import permissions from django.contrib.auth.models import User from contacts.models import Group from contacts.models import Contact from contacts.serializers import GroupSerializer from contacts.serializers import ContactSerializer from contacts.serializers import UserSerializer class GroupView(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] serializer_class = GroupSerializer def get_queryset(self): return Group.objects.all().filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) class ContactView(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] serializer_class … -
How to change permission in Django view sub-class?
I have the following setup right now: class MyView(MyPermission1, MyPermission2, FormView): ... class MyChildView(MyView): ... The child view is inheriting from the parent, but I want to remove MyPermission1 and MyPermission2 from it and apply another class called MyPermissionChild. Is there a way to do this using the generic views available in Django? -
How to get the value of the foreign key field and count or other aggregation operations?
I have two models. How can i count and show results like below: Male 235 Female 240 Other 10 My models.py class student(models.Model): name = models.CharField(max_length = 200) gender = models.ForeignKey(gender, on_delete = models.SET_NULL, null = True, blank=True) def __str__(self): return '%s' % (self.name) class gender(models.Model): title= models.CharField(max_length = 200) def __str__(self): return '%s' % (self.title) My views.py def viewlist(request): mylist = student.objects.values('gender').annotate(total=Count('gender')).order_by('-total') -
Django render field json in template
i'm doing a project using the Django 3.1.2, this project needs a register logs. I created a model for logs: class Log(models.Model): Usuario = models.CharField('Usuário que fez a ação', max_length=100) Perfil = models.SmallIntegerField( 'Quem está sofrendo a ação', choices=PERFIL_CHOICE) Acao = models.CharField('Tipo de Ação Realizada', max_length=2, choices=ACAO_CHOICE) Resultado = models.JSONField('Resultado', null=True, blank=True) Processando = models.BooleanField('Processando', default=True) TituloProcesso = models.CharField( "Titulo do Processo", max_length=100, null=True, blank=True) DataAcao = models.DateTimeField('Data da Ação', auto_now_add=True) The model log has field "Resultado" that is of type JSONField, this field is working correctly. The data that is save in the field, is dynamic, so the json keys and values will not always be the same, so i needed it easier to dysplay this field in template. I was looking the "django-jsonfiel", not work in Django 3.1 Does anyone know any way to display this field already formatted dynamically? -
Pass parameters in URL to Django Admin add_view
I need to pass a parameter in the URL to the Django Admin add view, so that when I type the URL: http://localhost:8000/admin/myapp/car/add?brand_id=1, the add_view reads the brand_id parameter. I want to use this so that I can set a default value for the brand attribute of Car. def get_form(self, request, obj=None, **kwargs): form = super(CarAdmin, self).get_form(request, obj, **kwargs) form.base_fields['brand'].initial = <<GET['brand_id']>> return form Use case: I want this because in my BrandsAdmin, I have added a "+" button for each brand, that should add a Car with that Brand as FK. I've tried getting it from request in get_form, but when that code is executed, Django has already changed my URL as I guess it doesn't understand it as a "legal" parameter. Thanks a lot! -
How to serialize tthe foreign key field in django rest framework
I working on project with drf where I'm getting serializer data as follows which is absolutely fine: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": 2, "item": 1, "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } } but I want to get as following: { "message": "Updated Successfully", "status": 200, "errors": {}, "data": { "id": 8, "user": "user name", "item": "product name", "price: "3.44", "quantity": 4, "created_at": "2021-08-11T13:49:27.391939Z", "updated_at": "2021-08-11T13:51:07.229794Z" } } I tried using drf RelatedField and PrimaryKryRelatedField but in all these cases I need to make corresponding fields as read_only=True which I want to skip. Please if anyone can help, it would be greatly appreciated. Thanks -
Django render many to many attributes after query, display None
I am using slug to query the model, and render result in HTML. The code is unable to render actual name of region, it just return None Model class Region(models.Model): name = models.CharField(blank=False, unique=True) def __str__(self): return self.name class Theme(models.Model): name = models.CharField(blank=False, unique=True) slug = models.SlugField(default="", null=False) def __str__(self): return self.name class ETF(models.Model): ticker = models.CharField(max_length=6, blank=False, db_index=True, unique=True) full_name = models.CharField(max_length=200, blank=False) # many to many region = models.ManyToManyField(Region) theme = models.ManyToManyField(Theme) views.py def theme_etf(request, slug): # render ETFs with theme filter filtered_results = ETF.objects.filter(theme__slug=slug) return render(request, "etf/list_etf.html", { "ETFs": filtered_results }) Part of list_etf.html {% for ETF in ETFs %} <tr> <td>{{ ETF.ticker }}</td> <td>{{ ETF.full_name }}</td> <td>{{ ETF.region.name }}</td> # What should I use in this line </tr> {% endfor %} The code is unable to render actual name of region, it just return None Result | Ticker | Name | Region | | -------| -------------------------- |------- | | ARKF | ARK Fintech Innovation ETF |None | | ARKK | ARK Innovation ETF |None | | KEJI |Global X China Innovation |None | I would like to have this: | Ticker | Name | Region | | -------| -------------------------- |------- | | ARKF | ARK Fintech … -
Build MultipleChoiceField form based on view request with Django
I have a table named Appointment with : timeslot id ; student id; teacher id ; date ; timeslot (integer) ; I would like to create multiple rows in the table TimeSlot based on MultipleChoiceField form. But the choice of slot at a certain date is depending of the value in the table. For example, if there is a timeslot at a certain date, the choice for this timeslot to this date will not be displaying to the client. This is my code : TIMESLOT_LIST = ( (0, '09:00 – 09:30'), (1, '09:30 – 10:00'), ) class ChooseAvailabilities(forms.Form): timeslot= forms.MultipleChoiceField( required=False, widget=CheckboxSelectMultiple, choices=TIMESLOT_LIST ) class Appointment(models.Model): teacher = models.ForeignKey(Teacher, null = True, on_delete = models.CASCADE) student = models.ForeignKey(Student, null=True, blank = True, on_delete=models.CASCADE) date = models.DateField(null = True) timeslot = models.IntegerField(null = True) In the view, I want to call the ChooseAvailabilties form with a certain date in parameter so that the form is checking if there are overlapping date or timeslot in the Appointment table to not show the timeslot in which there are overlappings but only available timeslots to this date. Something like where I can choose the timeslots. Then the selected timeslots are stored in the Appointment …