Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Order by name with number Django
I have approximately 500 device objects in an sqlite db, with a name field such as: Device-0 Device-1 Device-2 Device-3 ... ... Device-500 When listing these with django, I want it to list based on the number after the semicolon in the name, as shown above. I tried: queryset = Device.objects.all().order_by('name') Also from this question: queryset = Device.objects.annotate(int_sort=Cast("name", IntegerField())).order_by("int_sort", "name") Both of these produce this result: Device-0 Device-1 Device-10 Device-100 Device-101 ... Any help would be greatly appreciated. -
Django how to create a table with sum of two different queryset
I have the following model: class Budget_Vendite(models.Model): product=models.ForeignKey() byproduct=models.ForeignKey() quant_jan=models.DecimalField() quant_feb=models.DecimalField() quant_mar=models.DecimalField() price_jan=models.DecimalField() price_feb=models.DecimalField() price_mar=models.DecimalField() I want to create in my view a function that give me the possibility to have a new variable that is the monthly product of quant and price for each byproduct. Ad example: byproduct | jan | jan | byproduct_1 | quant_jan*price_jan | quant_feb*price_feb | -
Django import error when trying to import a model from a different app
I've gone through just about every Python/Django import StackOverflow question and I still can't fix this issue. In Django I am trying to create a new model that has a foreign key of a model in a different app. I don't appear to be able to import this. I am running Python 3.8 on Windows 10, running within a clean virtual environment Steps: > pip install django > django-admin startproject django1 > cd django1 > python manage.py startapp app1 > python manage.py startapp app2 Add both apps to the INSTALLED_APPS in django1/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', 'app2' ] Create a model in app1/models.py: from django.db import models class App1Model1(models.Model): val1 = models.BooleanField() val2 = models.BooleanField() Create a model in app2/models.py: from django.db import models from ..app1.models import App1Model1 class App2Model1(models.Model): ref1 = models.ForeignKey(App1Model1, on_delete=model.CASCASE) Pycharm is fine with the relative import, but as soon as I run manage.py I get: django1>python manage.py runserver ... File "C:\DEV\sherpytest\django1\app2\models.py", line 2, in <module> from ..app1.models import App1Model1 ValueError: attempted relative import beyond top-level package If I change the import in app2\models.py to this: from django.db import models from django1.app1.models import App1Model1 class App2Model1(models.Model): ref1 = models.ForeignKey(App1Model1, on_delete=model.CASCASE) … -
How to set Infinity in DecimalField for Postgresql in Django orm?
>>> e = DjangoModel(minimum=180,maximum=float('inf'),target=5,sales_team_type='Fresh Team') >>> e.save() Traceback (most recent call last): File "<input>", line 1, in <module> e.save() File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/base.py", line 869, in _do_insert using=using, raw=raw) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/query.py", line 1136, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1288, in execute_sql for sql, params in self.as_sql(): File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1241, in as_sql for obj in self.query.objs File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1241, in <listcomp> for obj in self.query.objs File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1240, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1182, in prepare_value value = field.get_db_prep_save(value, connection=self.connection) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1563, in get_db_prep_save return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/backends/base/operations.py", line 521, in adapt_decimalfield_value return utils.format_number(value, max_digits, decimal_places) File "/home/punitsingh/django-env/lib/python3.6/site-packages/django/db/backends/utils.py", line 239, in format_number value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context) -
How to create a popup view in django?
I'd like to create a popup to see the detailed information coming from a view when I click on the link. kpiMonitoring.html {% extends 'base.html' %} {% load humanize %} {% block refresh %} <meta http-equiv="refresh" content="240"> {% endblock refresh %} {% block title %} <title>SMD/PBA - SMD KPI MONITORING</title> {% endblock title %} {% block content %} <h3>SMD-CE KPI MONITORING</h3> <h5><input type="button" onclick="window.location.reload()" class="btn btn-dark" style="float:left;" value="REFRESH"> <button class="btn btn-success" id="copy-table-button" data-clipboard-target="#mytable1" style="float:left;">COPY TO EXCEL </button> <a href="" bgcolor="#0080ff" style="float:right; font-weight:bold; color:Red;">Over: {{ timeOverOver }} </a> {% if timeOverWaitSAOI > 0 %} <a href="" bgcolor="#0080ff" style="float:right; font-weight:bold; color:blue;">SAOI: {{ timeOverWaitSAOI }} &nbsp</a> {% else %} <a></a> {% endif %} {% if timeOverWaitMAOI > 0 %} <a href="" bgcolor="#0080ff" style="float:right; font-weight:bold; color:blue;">MAOI: {{ timeOverWaitMAOI }} &nbsp</a> {% else %} <a></a> {% endif %} {% if timeOverWaitPAOI > 0 %} <a href="" bgcolor="#0080ff" style="float:right; font-weight:bold; color:blue;">PAOI: {{ timeOverWaitPAOI }} &nbsp</a> {% else %} <a></a> {% endif %} <a style="float:right; color:black;">Time Over + 2hs &nbsp</a> </h5> views.py from kpi.models import TimeOver def kpiMonitoringView(request): timeOver = TimeOver.objects.filter(mfg_part_code='P12121', over_status='Time Over') timeWait = TimeOver.objects.filter(mfg_part_code='P12121', over_status = 'Wait') timeOverWait = timeWait.count() timeOverWaitPAOI = timeWait.filter(insp_loc ='P').count() timeOverWaitMAOI = timeWait.filter(insp_loc='M').count() timeOverWaitSAOI = timeWait.filter(insp_loc='S').count() timeOverOver = timeOver.count() return render(request,'kpi/kpiMonitoring.html','timeOverWait':timeOverWait, … -
Form Validation error for required field in Dajango
I have a html page where I am displaying text fileds are shown image . Html code for this screen given below. I want to display error message on screen if user enters invalid email id or email id existing on text filed of "Enter your Email" using forms validation error message. Currently I have written below piece of code display form validation error message. But this error message always displays just beside "New Password" test field. Is there any way I can display form validation error message beside "Email Your Mail" if user enters invalid email id or existing email id? HTML Code: <fieldset class="module aligned wide"> {% csrf_token %} <div class="form-row"> {{ form.old_password.errors }} <label for="{{ form.id_old_password.id_for_label }}">Old password:</label> {{ form.old_password }} </div> <div class="form-row"> {{ form.new_password1.errors }} <label for="{{ form.id_new_password1.id_for_label }}">New password:</label> {{ form.new_password1 }} </div> <div class="form-row"> {{ form.new_password2.errors }} <label for="{{ form.id_new_password2.id_for_label }}">Password (again):</label> {{ form.new_password2 }} </div> <div class="form-row"> {{ form.email_reset.errors }} <label for="{{ form.email_reset.id_for_label }}">Enter Your Email (optional):</label> <input id="id_email_reset" placeholder="Enter your email" name="email_reset" type="email" pattern=".+@.+\.com"/> </div> </fieldset> Forms.py class CustomPasswordChangeForm(PasswordChangeForm): """ This is a customized class to validate the password by overriding the existing function "clean_new_password1" from base class PasswordChangeForm. """ MIN_LENGTH … -
How can I make my employee model populate data from my user model just by selecting it. I want to get the first_name and last_name
class Employee(models.Model): staff_id = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True ) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) position = models.CharField(max_length=150) office = models.CharField(max_length=150) profile_picture = models.ImageField(upload_to='profile_image', blank=True, null=True) age = models.PositiveIntegerField() start_date = models.DateField() yearly_salary = models.PositiveIntegerField() user = self.model( staff_id=staff_id, email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, ) #user is my a custom user -
Publish Django Project on Windows Server
I have a home server(OS: WindowsServer 2016 STD) with ip static and i want publish my Django project on a windows server from my home server. What should i do to other people can access my project using my ip static!? -
TemplateSyntaxError at endfor in jinja django coding
The program is not recognizing {% endfor %} below is the code snippet Here dest is a list which is displaying the content {% for dest in dests % } <!-- Destination --> <div class="destination item"> <div class="destination_image"> <img src="{{im}}/{{dest.img}}" alt=""> <div class="spec_offer text-center"><a href="#">Special Offer</a></div> </div> <div class="destination_content"> <div class="destination_title"><a href="{% static 'destinations.html' %}">{{dest.name}}</a></div> <div class="destination_subtitle"><p>{{dest.desc}}</p></div> <div class="destination_price">From ${{dest.price}}</div> </div> </div> {% endfor %} -
How can i implement coalesce query in django?
I'm trying to build an ecom website using django and djngo rest framework. My model Item contains price and sale_price column: class Item(models.Model): price = models.FloatField() sale_price = models.FloatField(null=True,blank=True) I want to filter them by max active price So in order to do that in sqlite i would write something like SELECT coalesce(sale_price,price) < maxPrice FROM item; How can i do this in Django? -
Make sure data lands in correct tabe collumn in django template
I have a model: class UserReport(models.Model): user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) period = models.ForeignKey(Period, on_delete=models.SET_NULL, blank=True, null=True) points = models.PositiveSmallIntegerField(default=0) My goal is to make a table: Periods on top of the table, then each row is for user and points corresponding to period. _______________________________ Periods | 1 |2 |3 _________________________________ user 1 | 74 | 84 | 84 user 2 | 74 | | 84 user 3 | | 84 | 84 The problem: There might me no data entry for every period. How do I make sure, that points goes into right place (collumn) On top of that, periods might start form any number. what i did tried: in views i have: users_data.append(UserReport.objects.filter(user=user).order_by('period')) then in template: <table class="table"> <thead> <tr> <th>User</th> {% for period in periods %} <th>{{period}}</th> {% endfor %} </tr> </thead> <tbody> {% for user in users_data %} <tr> <td>{{user.0.user}}</td> <!-- Some smart logic should go here. Tis is my attempt which does not work --> {% for period in periods %} {% for entry in user %} {% if period == entry.period %} <td>{{entry.period}}-{{entry.points}}</td> {% endif %} {% endfor %} {% endfor %} </tr> {% endfor %} </tbody> </table> </div> I could probably achieve this making … -
Added summernote settings into project
I'm currently using django summernote in my project. It works well and these are my settings. 'summernote': { # As an example, using Summernote Air-mode 'airMode': False, 'fontSizes': ['8', '9', '10', '11', '12', '14', '16', '18'], 'toolbar': [ ['style', ['style']], ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'picture', 'video', 'hr']], ['view', ['fullscreen', 'codeview']], ['help', ['help']], ], # Change editor size 'width': '100%', 'height': '480', }, I'd like to add some settings that pertains to the widget the opens when you select an image within summernote. The official summernote documentation specifies that you can update the settings with the following, but I'm not sure how to put this into a format that my settings.py file will like. popover: { image: [ ['image', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']] ], } Thanks for your help! -
Django ListView: 'this_object_id' is not defined
I keep having issues when I want to refer to a specific object in ListView. My views: class SongList(generic.ListView): model = models.Song template_name = 'videos/song_list.html' context_object_name = 'song_list' def get_context_data(self, **kwargs): context = super(SongList, self).get_context_data(**kwargs) user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True) song = models.Song.objects.get(pk=this_object_id) #works if hard-coded lyrics_list = models.Song.objects.get(song=song).lyrics_as_list() user_word = list(set(user_flash) & set(lyrics_list)) context['percent_known'] = (len(user_word)/len(set((lyrics_list))))*100 return context I get the following error: name 'this_object_id' is not defined I've tried various variations, but I keep getting errors, e.g. self.kwargs['pk'] self.kwargs.get['pk'] Then I get the error: KeyError 'pk' It works when I hard-code the pk, so the problem is not elsewhere my code. It also works when I do it in my DetailView (using self.kwargs['pk']), but I need access to percent_known for every object in my ListView. How can I do this? I can sort of understand why it doesn't work, ListView is for a list of objects, so it doesn't know for what object I want to get this info for... but there must be a way I can do it for every object? Or is there another way to get access to percent_known for every object? -
forloop.counter problem with page pagination
I am very beginner in django. I have used {% forloop.counter %} for counting in HTML template.Its properly work in first page in html template but when I go to next page it again shows me form 1 to 5. I want to see results from the next one 6 to 10 .... How can I solve this problem ? -
Django and requests JSON response
How do I get JSON response in django using requests library? I currently have something of the following form: def predict(self, form): image = form.instance.input_image image_data = bytes(image.read()) img = Image.open(io.BytesIO(image_data)) data_dict = {'input': np.array(img).tolist()} data = requests.post( 'http://localhost:5000/predict', json=data_dict) return JsonResponse({'prediction': list(data)}) but this just returns <Response [200]> and the error TypeError: Object of type bytes is not JSON serializable? -
how to add space between a string in python. I am fetching the data from ms access database
def buildprofilepage(result): data = { "Street": str(result[11]).replace("", " "), "City": str(result[12]).replace("", " "), "State": result[13], "Street1": str(result[16]).replace("", " "),"City1": str(result[17]).replace("", " ") } return data In place of underscore I want to display space between string. But everytime I try it display first few character then spaces -
i do not have idea to fix. what is a problem i got? NotImplementedError: This backend doesn't support absolute paths
when i typed heroku run bash python manage.py createsuperuser -
I want to display User videos and Other's videos separately. I am not getting output from the following code, Is my approach correct?
My view goes something like this class Test(ListView): model = VideoUpload template_name = 'videoTube/videoTube.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["my_video_list"] = VideoUpload.objects.filter(user=self.request.user) context["other_video_list"] = VideoUpload.objects.exclude(user=self.request.user) print(context) return context Template code {% for vid in my_video_list %} {% if forloop.counter < 5 %} {{ vid.video }} {% endif %} {% endfor %} {% for vid in other_video_list %} {% if forloop.counter < 5 %} {{ vid.video }} {% endif %} {% endfor %} I am not getting anything in the output. I am expecting my_video_list and other_video_list should be displayed separately -
Inheriting a field from a model in django
I'd like the user_image, email and name field in my Comments model to be inherited from the UserProfile model. I tried using UserProfile.profile_image as the base class in my ForeignKey field, and it obviously didn't work. I know that's wrong, but any alternative would do. class UserProfile(AbstractUser): username = None bio = models.TextField(null=True, blank=True) profile_image = models.FileField(upload_to="profile_pic", blank=True, null=True) USERNAME_FIELD = 'email' def __str__(self): return self.email class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments', null=True) name = models.CharField(max_length=150) user_image = models.ForeignKey(UserProfile, on_delete=models.CASCADE) email = models.ForeignKey(UserProfile, on_delete=models.CASCADE) body = models.TextField() created_date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_date'] def __str__(self): return '{} comment made by {}'.format(self.body, self.name) -
Cannot get instance value in Django rest update view
I am using Django 3.0 djangorestframework==3.11.0. I have created a task update view and passing the pk to url. The problem is - Although I have set the serializer instance to the model object I want to update. The serializer instance is not showing up. models.py from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.apiOverview, name='api-overview'), path('task-list/', views.taskList, name='task-list'), path('task-detail/<str:pk>/', views.taskDetail, name='task-detail'), path('task-create/', views.taskCreate, name='task-create'), path('task-update/<str:pk>/', views.taskUpdate, name='task-update'), ] views.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Task from .serializers import TaskSerializer @api_view(['POST']) def taskUpdate(request, pk): task = Task.objects.get(id=pk) serializer = TaskSerializer(instance=task, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) expected behavior on url http://localhost:8000/api/task-update/4/ actual behaviour on http://localhost:8000/api/task-update/4/ as you can see the content field is empty but I want the already associated json to be shown there with pk = 4. -
database modeling with attributes and variants
Before working on django models, I first design the database schema of products which contains the following tables with relationships (correct me if the relationship is wrong). Here is the example as per my design Product Type - Clothing, Shoes, Bags Collection - Summer Collection, Winter Collection Category - Men - Tees, Polo Tshirts, Hoodies & Sweatshirts. Women, Kids Product - Super Soft Tees with product type clothing and of Men's category(tees) Designer Polo Tshirt with product type clothing and of Men's category(polo) Attribute - Material, Size, Color AttributeValue - Material - 100% cotton, 95% cotton 5%spandex Color - Black, Maroon, White Size - S, M, L, XL, XXL ProductTypeAttributeValue - Clothing - small, large, Black, maroon ProductAttributeValue - super soft tees - small, large, black, maroon, 100% cotton Option - Size, Color, Material OptionValue - Size = Small, Medium, Large. Color = Black, Maroon ProductOption - Super soft tees - size, color ProductVariant - Super Soft tees, Designer Polo Tshirt VariantValues - Super soft tees - small, maroon Super soft tees - small, black Super soft tees - large, maroon I did product app modeling in the following way from django.db import models from django.utils.text import slugify from mptt.managers … -
Accessing a parent's model attributes from child model in django
here is the model am trying to access class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ref_code = models.CharField(max_length=20) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) order_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey('Address',on_delete=models.SET_NULL,related_name='shipping_address',blank=True,null=True) payment = models.ForeignKey('Payment',on_delete=models.SET_NULL,blank=True,null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) here is the model am using to access it class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ordered_order = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) -
How To Integrate 2 Checkout With Django?
I Want To Know How To Integrate 2 Checkout With Django? I see their docs but their documentation is not well written if anybody integrates it please teach me also how to integrate 2 checkout I can't understand their doc -
How to select and delete multiple objects on Wagtail admin UI?
What I wanted should be the so-called bulk-operations, i.e. on Django admin, for a Django model there could be many objects created, and we can select multiple of them and delete. However, when I registered Django models in Wagtail, the Wagtail admin doesn't show anything similar to Django bulk operations. And I searched for a while, looks like bulk operations are not supported in Wagtail admin? Any other alternative we could use for Wagtail? -
Django how return to previous page after render pdf file
i've one view that combine some element keep from one database and some element chosen by user , all these elements are taken and trasformed into pdf file. For show the pdf the view return a call function , like this " return Rapportino_restituzione(request,user,pc,ticket1,user2,l) " All work well, but what i would like is that the view return also at the previous page or at home . Some ideas? I need to change the logic of the view ? Many thanks,