Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Resolve a related field to QuerySet type
Based on the official documentation: # Declare the ForeignKey with related_name class Tag(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="tags" ) name = models.CharField(max_length=255) # Return all tags Article.tags.all() My linter (django-pylint) is unable to type it porperly: Article.tags is Any, I expected a QuerySet[Tag]. Can I declare the Article.tags reference in the Article class? (preferred approach) from django.db.models.query import QuerySet class Article(models.Model): ... # Related field declaration tags: QuerySet[Tag] Article.tags.all() Or maybe I need to convert it every time I need it? tags_qs: QuerySet[Tag] = Article.tags tags_qs.all() In both scenarios, it looks heavy to implement for each related field. Of course, it's more a question for comfortable development experience than a critical issue. The goal is to allow my linter and other autocompletion/discovery tools to resolve related fields as QuerySet[T] type. Maybe I can't due to the design of the Python implementation, more than a Django issue. Is there any other alternative to fix this problem? -
I need help Template Django "for" "if"
I need to search for a particular object with the if conditions, in case nothing is found, the else is executed, the problem with this is that the else is executed for each object in the array, and I need it to only be executed after having traversed the entire array and the if condition has not been met, I have 4 objects in that array {% for horario in horarios %} <!--Lunes--> {% if horario.dia == 'Lunes' and horario.hora_inicio == '8:00' %} <td> Asignatura: {{horario.id_asignatura.nombre}}<br> Profesor: {{horario.rut_profesor.p_nombre}} {{horario.rut_profesor.ap_paterno}}<br> Sala: {{horario.id_sala.id_sala}} </td> {% else %} <td>Horario no disponible</td> {% endif %} {% endfor %} how I want it to look with the else what it actually looks like: -
Retrieving a child model's annotation via a query to the parent in Django?
I have a concrete base model, from which other models inherit (all models in this question have been trimmed for brevity): class Order(models.Model): state = models.ForeignKey('OrderState') Here are a few examples of the "child" models: class BorrowOrder(Order): parts = models.ManyToManyField('Part', through='BorrowOrderPart') class ReturnOrder(Order): parts = models.ManyToManyField('Part', through='ReturnOrderPart') As you can see from these examples, each child model has a many-to-many relationship of Parts through a custom table. Those custom through-tables look something like this: class BorrowOrderPart(models.Model): borrow_order = models.ForeignKey('BorrowOrder') part = models.ForeignKey('Part') qty_borrowed = models.PositiveIntegerField() class ReturnOrderPart(models.Model): return_order = models.ForeignKey('ReturnOrder') part = models.ForeignKey('Part') qty_returned = models.PositiveIntegerField() Note that the "quantity" field in each through table has a custom name (unfortunately): qty_borrowed or qty_returned. I'd like to be able to query the base table (so that I'm searching across all order types), and include an annotated field for each that sums these quantity fields: # Not sure what I specify in the Sum() call here, given that the fields # I'm interested in are different depending on the child's type. qs = models.Order.objects.annotate(total_qty=Sum(???)) So I guess I have two related questions: Can I annotate a child-model's data through a query on the parent model? If so, can I conditionally specify the … -
What is stored in database for Dropdown Single Select Box? (Django)
I have the Dropdown Single Select Box "Month" with 3 options "January", "February" and "March" as shown below: This is the code for the Dropdown Single Select Box "Month" in "Date" class below: # "store/models.py" from django.db import models class Date(models.Model): class Months(models.TextChoices): JANUARY = 'JAN', 'January' FEBRUARY = 'FEB', 'February' MARCH = 'MAR', 'March' # Here month = models.CharField(max_length=100, choices=Months.choices) And this is the old version code for the Dropdown Single Select Box "Month" in "Date" class below which is equivalent to the above code: # "store/models.py" from django.db import models class Date(models.Model): JANUARY = 'JAN' FEBRUARY = 'FEB' MARCH = 'MAR' MANTHS = [ (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March') ] # Here month = models.CharField(max_length=100, choices=MANTHS) Now, if I choose "February" and click on "SAVE", what is stored in database? "FEBRUARY"? "FEB"? or "February"? adf -
Django - How to create sub entries for each object in Models?
Example: Item Version S# abc1 abc1V abc1S# abc2 abc2V abc2S# Model class Hw(models.Model): item= models.CharField(max_length=30,default='') version= models.CharField(max_length=30,default='') serianlnumber= models.CharField(max_length=30,default='') now abc2 item has subitems and it has its subitems in it with their respective Versions and S#s Item Version S# abc2 abc2V abc2S# abc2sub1 abc2sub1V abc2sub1S# abc2sub_sub1 abc2sub1V abc2sub1S# abc3 abc3V abc3S# How do i create model/table like that or do i need to create different tables for each sub entries ? I could not find any specific documentation on this. Thanks -
CKeditor not working on template CreateVIew in Django
I just install Ckeditor and I try to add something new. I can see the Ckeditor is showing but I can not render on the template Create View. Anyone can give me some advice Model.py enter image description here Form.py enter image description here Views.py enter image description here Template enter image description here -
How Can I Reset User Password Using Django Class Based Views with Gmail Account
I want to implement a User Reset Password functionality in my Django application and I am getting this error : SMTPConnectError at /password_reset/ (421, b'Service not available'). I have done everything on my Gmail account by setting the 2 Steps Verification and Application Password which I used in my Django settings for the email. Here is my urls code: path('password_reset/', auth_view.PasswordResetView.as_view(), name = 'password_reset'), path('password_reset_done/', auth_view.PasswordResetDoneView.as_view(), name ='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path('reset_password_complete/', auth_view.PasswordResetCompleteView.as_view(), name = 'password_reset_complete'), Here is my setting.py code for the email: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_googlemail@gmail.com' EMAIL_HOST_PASSWORD = 'my_gmail_account_app_password' EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = 'Support Team <noreply@support.org>' Thanks in anticipation to your solutions/answers. -
Does Django is models property hit the database more than once?
I've searched in several places but I haven't found a satisfactory answer anywhere. I have these models: App bar class Bar(models.Model): name = models.CharField(max_lenth=50) text = models.TextField() App xyz class Xyz(models.Model): bar = models.ForeingKey(Bar, on_delete=models.CASCADE, verbose_name='Bar') App foo class Foo(models.Model): xyz = models.OneToOneField(Xyz, on_delete=models.CASCADE, verbose_name='Xyz') def bar_name(self): return self.xyz.bar.name def bar_text(self): return self.xyz.bar.text My first question is, on self.xyz.bar.name and on self.xyz.bar.text does hit in the database? If yes, how can i optimize it? I already tried this, but I'm not sure if it improves anything: def bar_name(self): return Xyz.objects.select_related('bar').get(pk=self.xyz_id).bar.name def bar_text(self): return Xyz.objects.select_related('bar').get(pk=self.xyz_id).bar.text And here comes my second question, using select_related(), I would create a single method like Sigleton pattern, something like this: def singleton_bar(self): return Xyz.objects.select_related('bar').get(pk=self.xyz_id) def bar_name(self): return self.singleton_bar().bar.name def bar_text(self): return self.singleton_bar().bar.text -
mysqlclient problem with python Python 3.10.4
(medinaenv) PS D:\medina> pip install mysqlclienty ERROR: Could not find a version that satisfies the requirement mysqlclienty (from versions: none) ERROR: No matching distribution found for mysqlclienty (medinaenv) PS D:\medina> pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [29 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win32-cpython-310 creating build\lib.win32-cpython-310\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\release.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\times.py -> build\lib.win32-cpython-310\MySQLdb creating build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-cpython-310\MySQLdb\constants running build_ext building 'MySQLdb.mysql' extension creating build\temp.win32-cpython-310 creating build\temp.win32-cpython-310\Release creating build\temp.win32-cpython-310\Release\MySQLdb "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x86\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,0,'final',0) -D__version_=2.1.0 "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include" -ID:\medina\medinaenv\include -IC:\Users\pc\AppData\Local\Programs\Python\Python310-32\include -IC:\Users\pc\AppData\Local\Programs\Python\Python310-32\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files … -
Django ListView class pagination filter query not effecting in pagination
i failed to include pagination in django list view pagination count shows without filter query any idea about to include fileter query in pagination calculation? assets_list = Assets.objects.filter(site=self.site,type__icontains="Asset") page = self.request.GET.get('page', 1) paginator = Paginator(assets_list, self.paginate_by) try: asset_data = paginator.page(page) except PageNotAnInteger: asset_data = paginator.page(1) except EmptyPage: asset_data = paginator.page(paginator.num_pages) context['assets'] = asset_data -
ckeditor not working on heroku deployment
I deploy my django blog to heroku but my ckeditor dosent work and after turning DEBUG = False and Add X_FRAME_OPTIONS = 'SAMEORIGIN' . This happend on when trying to runserver aswell when it was working with no problem before when i dident have DEBUG = False or X_FRAME_OPTIONS = 'SAMEORIGIN' . img1 img2 -
Django expected css(css-rparantexpected) when trying to add image to <body id ="bg" >
https://paste.pics/H6N16 So here is how my project is organised, I followed a youtube tutorial and for me it shows that paretentheses are missing, maybe that can be due to the bad folder management, I'm not sure <body id = "bg" style="background-image: url('{% static "image/patient_doctor.png" %}');"> Dont know what to do :/ -
Django - Handle two forms in CBV
I've been struggling the past few days with how to process two forms in the same Class Based View. I cannot get it working. I tried to play with get_context_data and post but I can't get the two forms working. In views.py, the get_context_data method: class UserViewReport(LoginRequiredMixin, TemplateView): """ View to access ONE report """ model = Report template_name = 'tool/single-report.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug = self.kwargs['slug'] report_id = get_object_or_404(Report, slug=slug) context['report_title'] = report_id.title reports_details = ReportDetails.objects.filter(report=report_id) dict_errors = {} missing_transporters = [] #Getting supplements and transporter names supplements = Supplement.objects.filter(company=self.request.user.company) context['supplements'] = supplements #Company file form ''' Testing if COMPANY file already exists in REPORT database ''' if not CompanyFile.objects.filter(report=report_id).exists(): context['company_form'] = CompanyFileForm(self.request.POST or None) #Transporter file form context['transporter_form'] = TransporterFileForm(self.request.POST or None) And the post method: def post(self, request, *args, **kwargs): report_id = get_object_or_404(Report, slug=self.kwargs['slug']) transporter_form = TransporterFileForm(request.POST, request.FILES) company_form = CompanyFileForm(request.POST, request.FILES) if transporter_form.is_valid(): obj = transporter_form.save() transporter_name = request.POST.get('transporter_name') transporter = get_object_or_404(Transporter, name=transporter_name) cd = transporter_form.cleaned_data file_name = cd.get('file') transporter_file = TransporterFile.objects.filter(pk=obj.pk).update(name=file_name, transporter=transporter, report=report_id, company=report_id.company, user=request.user) return redirect('tool:single-report', slug=self.kwargs['slug']) elif company_form.is_valid(): obj = company_form.save() cd = company_form.cleaned_data file_name = cd.get('file') company_file = CompanyFile.objects.filter(pk=obj.pk).update(name=file_name, user=request.user, company=report_id.company, report=report_id) return redirect('tool:single-report', slug=self.kwargs['slug']) return render(request, self.template_name, {'company_form': … -
how to configure django-froala-editor to upload images to aws S3 bucket
I am working on Django2.2.6 apps and one of the model filed is FroalaField where users can upload images from their machine local storage, the default Django models.FileField has a defualt upload_to attribute like this models.FileField(upload_to=get_blog_filepath, null=True, blank=True), how can I configure FroalaField to upload images to S3 by passing the url, I have looked at the docs and didn't find something useful in my case. from django.db import models from froala_editor.fields import FroalaField class BlogPost(models.Model): short_title = models.CharField(max_length=200, null=True, blank=False, db_column='db_short_title') title = models.CharField(max_length=200) blurb = FroalaField(max_length=300) # how I can do upload_to S3 report_file = models.FileField(upload_to=get_blog_filepath, null=True, blank=True) -
Django form filter not selecting output
My form shows all the ce_hostname objects in the database with a dropdown. I want to filter the ce_hostname to ones which only have a common order reference. I can't get this working. My dropdown is currently blank. forms.py class Cx_BaseForm(ModelForm): class Meta: model = Cx_Base fields = ['cx_hostname', 'new', 'ce_hostname', 'location', 'manged_module_model', 'slot'] def __init__(self, *args, **kwargs): super(Cx_BaseForm, self).__init__(*args, **kwargs) self.fields['ce_hostname'].queryset = Ce_Base.objects.filter(order_reference=self.instance.order_reference) models.py class Ce_Base(models.Model): ce_hostname = models.CharField(max_length=15, validators=[CE_HOSTNAME_REGEX], verbose_name="CE Hostname", help_text="Hostname of router.") order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) class Cx_Base(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) cx_hostname = models.CharField(max_length=15, validators=[CX_HOSTNAME_REGEX], verbose_name="CX Hostname", help_text="Hostname of Switch.") new = models.BooleanField(help_text="Select if installing new hardware. Leave blank if switch exists on DCN.") ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE, verbose_name="CE Hostname", help_text="Hostname of router in which the module will be inserted.") location = models.TextField(null=True, blank=True, help_text="Address of site. Leave blank if not new.") manged_module_model = models.CharField(max_length=200, null=True, blank=True, choices=MANAGED_MODULES, help_text="Hardware model of switch. Leave blank if not new.") slot = models.CharField(max_length=200, null=True, blank=True, choices=SLOT, help_text="Slot in which the module will be inserted. Leave blank if not new.") l2_interfaces = JSONField(null=True) def __str__(self): return self.cx_hostname -
ModuleNotFoundError: No module named 'froala_editor'
I am running django v2.2.6 on docker container, I entered django container and ran installed pip install django-froala-editor and when I run pip freeze it shows django-froala-editor is installed. and add I it into my installed apps INSTALLED_APPS = [ ...., 'froala_editor', ] and I used it into my model files, and actually is working fine but I still get this error every time I run the containers docker compose up and there is a volumes attached to the containers, please note that is working fine but I am curios why it still throwing this error -
How do i upload libraries django app to hosting by cPanel
I want upload django app to hosting by cPanel but i have problem when setup python app configuration files after add requirements.txt gives me an error these libraries are not accepted: matplotlib==3.5.1 pandas==1.3.5 Pillow==9.0.0 psycopg2==2.9.1 scipy==1.7.3 seaborn==0.11.2 Is there a solution? -
Django Project with TWO frontend VUE 3 apps
Django project has two apps. Customers & Operations. I want to separate access to the apps with separated front ends. The user authorization strategy I will follow to achieve this is where I am stuck. My research has is advising against two user models. And I recently found out about Proxy models. I need opinions on best approach for above requirement. the access links requirements are e.g app1 customers.example.com app2 operations.example.com Customers will have its own set of users and authorization. Operations will have its own set of users and authorization. Operations app will create Customers[eg Cust_X, Cust_Y]. Cust_X will have users[eg User_X1, User_X2] Cust_Y will have users[eg User_Y1, User_Y2] -
Django Python List Postmark API
I'm trying to send a list of items to Postmarks API to display items on a template receipt. Here is my query in Python/ Django. items = order.orderitem_set.all() data = items.values("product__name","quanity","product__point_price", "order_id") data_list = list(data) Here is the output: [{'product__name': 'Pokemon 25th Anniversary', 'quanity': 1, 'product__point_price': 100.0, 'order_id': 31}, {'product__name': 'Minecraft - Nintendo Switch', 'quanity': 1, 'product__point_price': 100.0, 'order_id': 31}] [ So what I am trying to do is list these items individually on the postmark API template. Here is the HTML code for this. <table class="purchase" width="100%" cellpadding="0" cellspacing="0"> <tr> <td> <h3>Order ID: {{receipt_id}}</h3></td> <td> <h3 class="align-right">Date: {{date}}</h3></td> </tr> <tr> <td colspan="2"> <table class="purchase_content" width="100%" cellpadding="0" cellspacing="0"> <tr> <th class="purchase_heading"> <p class="align-left">Description</p> </th> <th class="purchase_heading"> <p class="align-right">Amount</p> </th> </tr> {{#each receipt_details}} <tr> <td width="60%" class="align-left purchase_item">{{description}} Quanity: {{quanity}}</td> <td width="40%" class="align-right purchase_item">{{amount}}</td> </tr> {{/each}} <tr> <td width="80%" class="purchase_footer" valign="middle"> <p class="purchase_total purchase_total--label">Total Points</p> </td> <td width="20%" class="purchase_footer" valign="middle"> <p class="purchase_total">{{points}}</p> </td> </tr> </table> Here are my Django views where you send the data to the postmark template. How do I get the items individually out of the list? "receipt_details": [ { "description": data_list.product__name, <--- This obviously doesn't work. How would I do this? "quanity": "quanity_Value", "amount": "amount_Value" } ], -
Django - Using single list objects from a model class
So Create_Watchlist is a model with a Foreignkey to the User Model and 'ticker' is a CharField of Create_Watchlist. Here is my views.py function for the approach def watchlist_one(request, pk): Create_Watchlist.objects.get(id=pk) list_ticker = list(Create_Watchlist.objects.all().values_list('ticker', flat=True)) At the moment list_ticker equals ['AAPL, BTC'] I want to access in this case 'AAPL' and 'BTC' as different list objects, because I want to make an API request with each list item. The list_ticker variable changes with the users input from a form . So there could be smt like ['AAPL, BTC'], but as well smt like ['FB'] (etc.) If I've made a mistake here, an explanation of how to deal with query sets and data types would also help me! Thanks a lot :) -
Django SocketIo problems
I am trying to do a chat app in django with socketio. I tried to do it from this video. I did it but how can I add history to the chat with consume the least space in my computer? With history I mean even for example if I refresh the page or close the computer If I go again I will see the same conversation. But I don't want the messages consume much space in my computer. Also should I don't use socketio and do the chat with something other? Thanks. -
Django 'ModuleNotFoundError: No module named 'blog/wsgi' when deploying to Elastic Beanstalk, as well as 'Error while connecting to Upstream'
I am trying to deploy a static Django website to Elastic Beanstalk via the UI 'upload your code' and not the EB CLI. I have created a zip file of all of my contents and have tried uploading it a million times, only to be met with the errors 'ModuleNotFoundError: No module named 'blog/wsgi' when deploying to Elastic Beanstalk, as well as 'Error while connecting to Upstream'. I think it is an error with the 'django.config' file in my .ebextensions folder. The contents of the 'django.config' file is: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: blog/wsgi:application. The contents of my 'wsgi.py' file is import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.blog.settings') application = get_wsgi_application(). I have attached a screenshot of my folder structure as well. I can attach any other files if necessary. Thank you. -
Trouble saving empty Base64ImageField in Django Restframework
I am using a custom class to store base64 images that are coming via API requests. The class looks like this: class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, six.string_types): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') file_name = str(uuid.uuid4())[:16] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension def to_representation(self, instance): if instance.name: return(settings.BASE_URL+reverse('download', args=[instance.name])) else: return None In my serializer.py file I am using it like this: logo = Base64ImageField(max_length=None, use_url=True, required=False, allow_null=True, allow_empty_file=True) Lets assume a logo has already been saved and now I am deleting it, I want to send an empty string. Unfortunately this is always ending up in an error message: The submitted file is empty. I am thankful for any clue. -
Delete an object in django by passing two id parameters by ajax call
When I try to delete an object by ajax call both ID's are not passing to url Am getting url like 127.0.0:8000/delete// urls.py path('delete/<int:a_id>/<int:b_id>',views.delete,name="delete") views.py def delete(request,a_id,b_id): obj=Table.objects.get(a_id=a_id,b_id=b_id) obj.delete() return render(request,"delete.html") delete.html <input type="hidden" id="a_id" data-value="{{obj.a_id}}"> <input type="hidden" id="b_id" data-value="{{obj.b_id}}"> script.js var a_id=$("#a_id").data("value"); var b_id=$("#b_id").data("value"); #some code $.ajax({ url:'delete/'+ a_id +'/' + b_id, #some code }); -
How to serialize large query set and write it to json?
Django 3.2.10, python 3.9 I have a QuerySet of 100 000 users. I need to serialize them and write into json file. queryset = Users.objects.all() # 100 000 users with open('output.json', 'w') as f: serializer = MySerializer(queryset, many=True) dump(serializer.data, f) I tried a .iterator() method, but I didn't understand how it should work. Also I tried next, but it is to slow. queryset = Users.objects.all() # 100 000 users with open('output.json', 'w') as f: for user in queryset: serializer = MySerializer(user) dump(serializer.data, f)