Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Icons from DigitalOcean spaces can't load with my Django settings
I am using Django summernote, but icons aren't showing, this is the structure of my digitalocean spaces : When it comes to Django settings, I pointed to the res folder with AWS_LOCATION, but am not sure if the path I provided is correct, I used : AWS_LOCATION = 'res/' I also enabled CORS in the DigitalOCean spaces section, but I am still getting this error : DevTools failed to load source map: Could not load content for https://fra1.digitaloceanspaces.com/guio_space/res/vendor/adminlte/css/adminlte.min.css.map: HTTP error: status code 403, net::ERR_HTTP_RESPONSE_CODE_FAILURE DevTools failed to load source map: Could not load content for https://fra1.digitaloceanspaces.com/guio_space/res/vendor/adminlte/js/adminlte.min.js.map: HTTP error: status code 403, net::ERR_HTTP_RESPONSE_CODE_FAILURE DevTools failed to load source map: Could not load content for https://fra1.digitaloceanspaces.com/guio_space/res/vendor/bootstrap/js/bootstrap.min.js.map: HTTP error: status code 403, net::ERR_HTTP_RESPONSE_CODE_FAILURE all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-solid-900.woff2 net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-regular-400.woff2 net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-solid-900.woff net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-regular-400.woff net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-solid-900.ttf net::ERR_ABORTED 403 all.min.css:1 GET https://fra1.digitaloceanspaces.com/guio_space/res/vendor/fontawesome-free/webfonts/fa-regular-400.ttf net::ERR_ABORTED 403 logo.png:1 -
how to Customize error message when Schema format is not matching with django Ninja?
``` @router.post("/addUser", response={200: responseStdr, 404: responseStdr,422: responseStdr}) def addUser(request, user: userRegister): try: return 200, {"status": 200, "isError": "True", "data": user, "msg": "user crée avec succès", "method": "POST"} except : return {"status": 201, "isError": "True", "data": "erreur format", "msg": "erreur", "method": "POST"} ``` I'm getting this error : ``` { "detail": [ { "loc": [ "body", "user", "last_name" ], "msg": "field required", "type": "value_error.missing" } ] } ``` How to send a custom message instead of this error when a field is not matching with the expected format ? -
HTML doesn't load all CSS properties
I am making a website using django and I need to edit some things on frontend using CSS but I don't know why CSS doesn't load all things I added. It loads some of the tags but rest just doesn't show at all here is the code. index.html: {% extends 'gym_app/base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> {%load static%}{%block content%} <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}" /> <link rel="script" href="{% static 'javascript/index.js' %}"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" /> </head> <body class="body"> <div class="container"> <div class="text-center"> <h1>Supreme</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, debitis!</p> </div> <!--Image slideshow--> <div class="container-slide"> <div class="swiper"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> <div class="swiper-slide"><img src="{% static 'images/gym_1.jpg' %}" alt=""></div> <div class="swiper-slide"><img src="{% static 'images/gym_1.jpg' %}" alt=""></div> <div class="swiper-slide"><img src="{% static 'images/gym_1.jpg' %}" alt=""></div> </div> <!-- If we need pagination --> <div class="swiper-pagination"></div> <!-- If we need navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.js"></script> <script src="{% static 'javascript/index.js' %}"></script> <!--Ends--> <!--About section--> <div class="container"> <p class="h1 text-center">About us</p> <section class="row mb-5"> <img src="{% static 'images/gym_1.jpg' %}" alt="" class="col-7" style="height: 350px;"> <div class="col-5"> <p>Lorem ipsum … -
Heroku not deployingr: This error originates from a subprocess, and is likely not a problem with pip
I am trying to deploy a demo of my simple django app on heroku, but when I try to deploy the app, the following error occurs. pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I reviewed the error and it turned out it is due to the version of pip, and I should downgrade it, but I don't know if I can change Heroku's pip version. So what should I do? Here is requirements.text: absl-py==0.12.0 altair==4.2.0 argon2-cffi==21.3.0 argon2-cffi-bindings==21.2.0 asgiref==3.5.2 astroid==2.5.1 asttokens==2.0.5 attrs==21.2.0 backcall==0.2.0 backports.entry-points-selectable==1.1.1 beautifulsoup4==4.9.3 bleach==5.0.0 blinker==1.4 bokeh==2.4.2 cachetools==5.2.0 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.9 click==8.0.3 colorama==0.4.4 commonmark==0.9.1 crypto==1.4.1 cvzone==1 cycler==0.11.0 debugpy==1.6.0 decorator==5.1.1 defusedxml==0.7.1 distlib==0.3.4 Django==4.1 entrypoints==0.4 executing==0.8.3 fastjsonschema==2.15.3 filelock==3.4.0 Flask==2.0.2 fonttools==4.29.1 gitdb==4.0.9 GitPython==3.1.27 gunicorn==20.1.0 idna==3.3 imageio==2.13.3 importlib-metadata==4.11.4 ipykernel==6.15.0 ipython==8.4.0 ipython-genutils==0.2.0 ipywidgets==7.7.0 isort==5.8.0 itsdangerous==2.0.1 jedi==0.18.1 Jinja2==3.0.3 jsonschema==4.6.0 jupyter-client==7.3.4 jupyter-core==4.10.0 jupyterlab-pygments==0.2.2 jupyterlab-widgets==1.1.0 keyboard==0.13.5 kiwisolver==1.3.2 lazy-object-proxy==1.6.0 lxml==4.9.0 MarkupSafe==2.0.1 matplotlib==3.5.1 matplotlib-inline==0.1.3 mccabe==0.6.1 mediapipe==0.8.9.1 mistune==0.8.4 MouseInfo==0.1.3 multitasking==0.0.10 mysql==0.0.3 mysql-connector==2.2.9 mysqlclient==2.1.0 Naked==0.1.31 nbclient==0.6.4 nbconvert==6.5.0 nbformat==5.4.0 nest-asyncio==1.5.5 networkx==2.6.3 nnfs==0.5.1 notebook==6.4.12 numpy==1.20.2 opencv-contrib-python==4.5.2.52 opencv-python==4.5.2.52 packaging==21.3 Panda3D==1.10.10 panda3d-gltf==0.13 panda3d-simplepbr==0.9 pandas==1.3.5 pandocfilters==1.5.0 parso==0.8.3 pickleshare==0.7.5 Pillow==8.4.0 pipenv==2022.1.8 platformdirs==2.4.0 plotting==0.0.7 prometheus-client==0.14.1 prompt-toolkit==3.0.29 protobuf==3.16.0 psutil==5.9.1 pure-eval==0.2.2 pyarrow==8.0.0 PyAutoGUI==0.9.53 pycparser==2.21 … -
Is it possible to sub-parametrize pytest parameters values?
I'm working on a DRF (REST API) project and I'm using pytest. Quite often I find myself writing almost identical test parameters and I've been wondering if there's something I'm missing. I haven't read the entire pytest docs, although I definitely did read the entire django docs chapter on tests (not very helpful in my case) and I've now spent a few hours trying to find a solution. Let's assume I have a view like this: from rest_framework import generics from myapp.permissions import IsStaff, IsAdmin class MessagesListView(generics.ListAPIView): permission_classes = [IsStaff | IsAdmin] # ... and for this view I wrote a test: import pytest from rest_framework.reverse import reverse_lazy from pytest_lazy_fixture import lazy_fixture class TestMessagesListViewPermissions: def get_response(self, client): url = reverse_lazy("api:messages-list") return client.get(url) @pytest.mark.parametrize( argnames=["client", "expected_response_status"], argvalues=[ pytest.param( "anonymous_client", status.HTTP_403_FORBIDDEN, ), pytest.param( "authenticated_client", status.HTTP_403_FORBIDDEN, ), pytest.param( "staff_client", status.HTTP_200_OK, ), pytest.param( "admin_client", status.HTTP_200_OK, ), ], ) def test__permissions(self, client, expected_response_status): # WHEN response = self.get_response(client) # THEN assert response.status_code == expected_response_status And there are 4 different client values, but 1+2nd and 3+4th result in the same response status code. As I said, it's a simplified example, but what if there are 10 parameters? What I'd like to be able to do is … -
How to replace the algorithm thingy in my edit profile page, with a decent bootstrapified input bar - Django
So I have an Edit profile page that looks like this: What I want is to replace this: algorithm: pbkdf2_sha256 iterations: 390000 salt: pZEUwO**************** hash: M7qIWG************************************** Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. from under the Password column with a proper form that looks like the format of the Username, First Name, Last Name, etc. My views: class NormalUserEditView(generic.UpdateView): form_class = EditProfileFormNormal template_name = 'authentication/edit_normalprofile.html' success_url = reverse_lazy('profile') def form_valid(self, form): messages.success(self.request, f'Account Edit: Successful') return super().form_valid(form) def get_object(self): return self.request.user class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangeForm success_url = reverse_lazy('profile') def form_valid(self, form): messages.success(self.request, 'Password Change: Successful') return super().form_valid(form) My urls: from django.urls import path from . import views from .views import UserEditView, NormalUserEditView, PasswordsChangeView from django.contrib.auth import views as auth_views urlpatterns = [ path('register', views.register_user, name='register'), path('login', views.login_user, name='login'), path('logout', views.logout_user, name="logout"), path('confirm_address_page', views.cap, name="confirm-address-page"), path('activate/<uidb64>/<token>', views.activate, name="activate"), path('edit_user_profile/', UserEditView.as_view(), name="edit-profile"), path('password/', PasswordsChangeView.as_view(template_name='authentication/change-password.html')), path('edit_profile/', NormalUserEditView.as_view(), name="edit-normalprofile"), path('profile', views.profile, name="profile"), ] My forms: from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.contrib.auth.models import User from django import forms class RegisterUserForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) class … -
Why Django get result list from query_set too late?
I am studying about Django ORM. I couldn't get an answer from the search, but I'd appreciate it if someone could tell me the related site. My model is as follows. user1 has2 accounts, and 500,000 transactions belong to one of the accounts. class Account(models.Model): class Meta: db_table = 'account' ordering = ['created_at'] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account = models.CharField(max_length=20, null=False, blank=False, primary_key=True) balance = models.PositiveBigIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class AccountTransaction(models.Model): class Meta: db_table = 'account_transaction' ordering = ['tran_time'] indexes = [ models.Index(fields=['tran_type', 'tran_time', ]), ] account = models.ForeignKey(Account, on_delete=models.CASCADE) tran_amt = models.PositiveBigIntegerField() balance = models.PositiveBigIntegerField() tran_type = models.CharField(max_length=10, null=False, blank=False) tran_detail = models.CharField(max_length=100, null=True, default="") tran_time = models.DateTimeField(auto_now_add=True) The query time for the above model is as follows. start = time.time() rs = request.user.account_set.all().get(account="0000000010").accounttransaction_set.all() count = rs.count() print('>>all') print(time.time() - start) # 0.028000831604003906 start = time.time() q = Q(tran_time__date__range = ("2000-01-01", "2000-01-03")) rs = request.user.account_set.all().get(account="0000000010").accounttransaction_set.filter(q) print('>>filter') print(time.time() - start) # 0.0019981861114501953 start = time.time() result = list(rs) print('>>offset') print(time.time() - start) # 5.4373579025268555 The result of the query_set is about 3500 in total. (3500 out of 500,000 records were selected). I've done a number of things, such as setting offset to the result (rs) of query_set, … -
Semgrep: A scalable way of catching all cases in a multiline f-strings
I have some logs in my codebase that have multiline f-strings, such as: ... logger.error( f'...' f'...' f'...' f'...' f'...' f'...' ) And some only have two f'...'s on separate lines while others 3 f'...'s, and so on. I am currently duplicating patterns to catch such logs. For example: ... patterns: - pattern-either: - pattern: | logger.$METHOD( f'...' f'...' f'...' ) - pattern: | logger.$METHOD( f'...' f'...' f'...' f'...' f'...' ) Catch those with 3 and 5 f'...'s on multiple lines. I have to write another pattern for those with 4, 2 and so on. Is there a scalable way to capture all of these with fewer patterns? The current implementation won't scale as there might be logs with 6, 7, 8, 9 and so on multiline f-strings. -
Django orm subquery - in clause without substitution
I need to build a query using Django ORM, that looks like this one in SQL: select * from A where id not in (select a_id from B where ... ) I try to use such code: ids = B.objects.filter(...) a_objects = A.object.exclude(id__in=Subquery(ids.values('a__id'))).all() The problem is that instead of nested select Django generates query that looks like select * from A where id not in (1, 2, 3, 4, 5 ....) where in clause explicitly lists all ids that should be excluded, making result sql unreadable when it is printed into logs. Is it possible to adjst this query, so nested select is used? -
Как динамически обновлять данные на странице, по ходу выполнения кода в web приложении Django
Возможно ли по мере выполнения кода из цикла, передавать данные на страницу? При нажатии кнопки в форме, выполняется долгий процесс, хотелось бы отображать на странице ход выполнения данного процесса, а после выполнения, возвращать рендер с финальными результатами Я новичок в django, огромная просьба хотя бы подсказать примерно как это сделать, перерыл весь интернет в поиске решения, предполагаю, что нужно использовать вэбхуки, но как это реализовать не представляю Спасибо! index.html {% extends 'base.html' %} {% block content %} <form action="" method="post"> {% csrf_token %} <select name="employee_name"> <option selected="selected" disabled>ВЫБЕРИ СОТРУДНИКА:</option> <option value="сотрудник1">сотрудник1</option> <option value="сотрудник2">сотрудник2</option> <option value="сотрудник3">сотрудник3</option> </select> <input type="submit" value="Проверить"> </form> {% endblock %} views.py from django.shortcuts import render from .CRM import crm_driver def index(request): if request.POST: data = crm_driver.get_data(request.POST.get("employee_name")) return render(request, 'calculation/calculation.html', {"employee_name": str(request.POST.get("employee_name")).upper(), "file_count": data[0], "verified_count": data[1], "count_complited": data[2], "count_refusal": data[3], "count_order": data[4], "today_verified_count": data[5], "today_complited": data[6], "today_refusal": data[7], "count_today_order": len(data[8]), "today_order": data[8], "count_today_in_work": len(data[9]), "today_in_work": data[9], "renewal_full": data[10], "FOR_TODAY_renewal_full": data[11], "renewal_paid": data[12], "FOR_TODAY_renewal_paid": data[13], "sp_complited": data[14], "sp_order": data[15], "refusal": data[16], "count_error": len(data[17]), "error_list": data[17]}) else: return render(request, 'calculation/index.html') crm_driver.py import csv import time from .crm_module import init_driver, siebel_login, quote_search_init, get_quote_data, siebel_exit from .Refusal import failure_statistics from .utils import to_float complited_list = ['ОТПРАВЛЕНО', 'ОТПРАВЛЕН В СС', 'ОТПРАВЛЕНО В СС', … -
is there a way to run a function all the time in django?
Model.py class QualityControlCheck(models.Model): types_choices = ( ('PASS-FAIL', 'Pass-Fail'), ('MEASUREMENT', 'Measurement'), ('INSTRUCTION', 'Instruction'), ('TAKE A PICTURE', 'Take a Picture') ) quality_control_point = models.ForeignKey(QualityControlPoint, on_delete=models.CASCADE) pass_fail = models.CharField(max_length=50, null=True, blank=True) picture = models.FileField(upload_to='media/QCC/', null=True, blank=True) instruction = models.TextField(max_length=1000, null=True, blank=True) norm = models.FloatField(null=True, blank=True) tolerance_from = models.FloatField(null=True, blank=True) tolerance_to = models.FloatField(null=True, blank=True) note = models.TextField(max_length=1000, default=None, null=True, blank=True) status = models.CharField(max_length=50, default='To Do') mrv = models.ForeignKey(MaterialReceiptVoucher, on_delete=models.CASCADE, null=True, blank=True) returned = models.ForeignKey(MaterialReturnNote, on_delete=models.CASCADE, null=True, blank=True) production = models.ForeignKey(ProductionPlan, on_delete=models.CASCADE, null=True, blank=True) reject = models.ForeignKey(MaterialRejectionNote, on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) next_check_date = models.DateTimeField(blank=True, null=True) def __str__(self): if self.quality_control_point.raw_product is not None: return str(self.id) + '-' + str(self.quality_control_point.raw_product) elif self.quality_control_point.spare_product is not None: return str(self.id) + '-' + str(self.quality_control_point.spare_product) elif self.quality_control_point.bom_product is not None: return str(self.id) + '-' + str(self.quality_control_point.bom_product) else: return self.quality_control_point.title next_check_date is checking for the current time in Views.py: current_time = timezone.now() if current_time >= next_check_date: doSomething() i manage to do this only in one View i would like to run this with every view i have? -
in pyecharts, how to bring line to front of bar when using bar.overlap(line)?
unfortunatly there is no tag for pyecharts in stackoverflow site , I'm not sure if I will get a helpful answer , hopefully I will get I have the following chart that consists of two bars and one line, I need 2 things : I need to bring the line to front of bar , its under the bar by default I need to shorten the value number to the nearest thousand (e.g 80,000 = 80K) code :- from pyecharts.charts import Bar, Gauge, Line from pyecharts import options as opts from pyecharts.globals import ThemeType bar = ( Bar(init_opts=opts.InitOpts(width='100%', theme=ThemeType.VINTAGE)) .add_xaxis(["Category-1" , "Category-2", "Category-3", "Category-4", "Category-5"]) .add_yaxis('No. Of Investments', [100,700,900,500,400,50], label_opts=opts.LabelOpts(is_show=False),) .add_yaxis('No. Of Investors', [24,65,30,41,88], label_opts=opts.LabelOpts(is_show=False),) .extend_axis( yaxis=opts.AxisOpts( name="Value", type_="value", name_textstyle_opts=opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') ) ) .set_global_opts(legend_opts=opts.LegendOpts(is_show=True , pos_right = 0, textstyle_opts = opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') ), yaxis_opts=opts.AxisOpts( name='Count', name_location='middle', name_gap=50, type_="value", axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), axispointer_opts=opts.AxisPointerOpts(is_show=False), name_textstyle_opts=opts.TextStyleOpts( font_size=14, font_weight='bold', font_family='Dubai') ), xaxis_opts=opts.AxisOpts( type_="category", axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"), name_textstyle_opts=opts.TextStyleOpts(font_size=14, font_weight='bold', font_family='Dubai') , axislabel_opts = opts.LabelOpts(font_family='Dubai' , rotate = 30, font_size= 11, ) ), tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", textstyle_opts = opts.TextStyleOpts( font_family='Dubai') ) , toolbox_opts = opts.ToolboxOpts(is_show=True , pos_left= '5%', feature=opts.ToolBoxFeatureOpts( data_zoom = opts.ToolBoxFeatureDataZoomOpts(is_show=False) , data_view = opts.ToolBoxFeatureDataViewOpts(is_show=False) , brush=None ) ) ) ) line = ( Line() … -
Django - How to iterate queryset object in template
I am trying to developed quiz app in django class base view. here i am get all question in questions and render to template. i want access one by one questions using html next button. so suggest me any backend code required or by using javascript we can iterate? View.py -
The function get_form_kwargs doesn't work, it doesn't return anything
I have a CreateView and i want to save as a kwarg the user, and i don't understand what is wrong with my code. I wrote my get_form_kwargs in my create view(this is from my view.py): class ItemCreateView(CreateView): template_name = 'menus/form.html' form_class = ItemForm def form_valid(self, form): instance = form.save(commit=False) instance.user = self.request.user return super(ItemCreateView, self).form_valid(form) def get_form_kwargs(self): kwargs=super(ItemCreateView, self).get_form_kwargs() kwargs['user']=self.request.user return kwargs def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) context = { 'form' : form, 'var' : 'Add an Item' } return render(request, self.template_name, context) I introduced the init function in my form(this is my form.py): class ItemForm(forms.ModelForm): class Meta: model = Item fields = [ 'name', 'article', 'description', 'exceptions', 'bl', ] def __init__(self,*args, **kwargs): print(kwargs.pop('user', None)) super(ItemForm, self).__init__(*args, **kwargs) The problem is that the print from the init function returned None value. It should returned the user. I'm mentioning that I am logged in. I don't understand what is wrong here. Thanks in advance for your help !!! -
Django- get "parameters" from HTML form in views
I have a template which has this form: template.html <form action="{% url addcart %}" method="POST" class="btn-block"> {% csrf_token %} <input type="number" name="quantity" min="1" max="100"> <input type="submit" class="float-right btn btn-success form-control" value="Add To Cart"> </form> Now, I want to know how to implement the function "addcart()" in the views. How can I get the form variables? -
What is the best paradigm for django rest framework unit testing?
I have a Django project (drf) and I want to implement some unit tests for it. I found some different scenarios in implementations. Some of them define a class for each django model containing different methods for CRUD APIs: class FooTestCase(TestCase): def setup(self): pass def test_foo_create(self): pass def test_foo_update(self): pass . . . . Some others define a class for each API view: class FooListCreateTestCase(TestCase): def setup(self): pass def test_foo_create(self): pass class FooRetriveUpdateDeleteTestCase(TestCase): def setup(self): pass def test_foo_update(self): pass and so on ... what is the best paradigm among them? -
js function is not defined in django template
I have just started learning Django and I tried to add simple js static file to my Django template. However I am not able to execute function in Django template due to Uncaught ReferenceError: myFunction is not definedat HTMLButtonElement.onclick. My function is very simple and it is within static folder at the project level static/js/script.js function myFunction() { alert("This is result of JS function!"); } At the project level I have the base.html within templates/base.html. Here it is: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <script type="text/javascript" scr="{% static 'js/script.js' %}"></script> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div class="nav-bar"> <a href="{% url 'myapp:home' %}">Home</a> | <a href="{% url 'myapp:about' %}">About Us</a> | <a href="{% url 'myapp:services' %}">Our Sevices</a> | <a href="{% url 'myapp:info' %}">Info</a> | </div> <div class="page-content"> {% block content %} {% endblock %} </div> <div class="page-footer"> <a href="#" >Usefull links</a> | <a href="#" >Follow Us</a> | <a href="#" >Address</a> | <p id="copyright">&copy; 2022 Learning Django</p> </div> </body> </html> At the app level I have folder templates and inside several html files like myapp/templates/myapp/services.html. {% extends … -
Why do I get TypeError when running my Django project with Debug off?
So I've been running my Django project with Debug on, I know it's wrong, and now trying to make the change. But then, the project returned TypeError when I turned the Debug off: TypeError: expected str, bytes or os.PathLike object, not NoneType I tried digging into the issue a little more, and found out that the variable absolute_path of admin/js/jquery.js was None, as you can see in the Traceback below. I've got three clues regarding this issue: It happens in the django-cloudinary-storage library. It probably happened after running python manage.py collectstatic. I did not run this command up until now.. The project ran perfectly with Debug = True. It only happened with Debug=False. What do you think is the problem? Below is a part of my settings.py and full Traceback. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] Full Traceback: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 31, in get_handler handler … -
Django how to get object in one query to database
models.py class Post(models.Model): pass @property def views_count(self): return PostViews.objects.filter(post=self).count() class PostViews(models.Model): IPAddres= models.GenericIPAddressField(default="") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_views_count",) date = models.DateTimeField(auto_now_add=True) views.py def get_posts(request, topic=""): posts = Post.objects.filter(status=Post.OPEN).select_related('author').prefetch_related('tags').select_related('category').select_related('post_views_count') posts.hml {% for post in posts %} {{ post.views_count }} {% endfor %} Due to the call of views, the number of sql queries grows by 10 hits.How do I get this data in place with the data received by the model Post? -
Unable to POST with ListCreateAPIView
Thank you very much for all your help. We are currently using Django to create a blog with membership features. I would like to allow only members to post articles, but I can't use POST while logged in. When not logged in, POST is available. What is wrong? models.py class Post(models.Model): title = models.CharField(max_length=100, blank=True, default='') content = models.TextField(blank=True, default='') def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=100, blank=False, null=True, default='') posts = models.ManyToManyField(Post, related_name='categories', blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title','content', 'categories'] class CategorySerializer(serializers.ModelSerializer): name = serializers.CharField(required=False, allow_null=True, allow_blank=True) posts = PostSerializer(many=True, read_only=True) new_posts = serializers.PrimaryKeyRelatedField( queryset=Post.objects.all(), many=True, write_only=True, required=False) class Meta: model = Category fields = ['id', 'name', 'posts', 'new_posts'] def create(self, validated_data): category = Category.objects.create() category.name = validated_data.pop('name', None) new_posts = validated_data.pop('new_posts', None) category.posts.set(new_posts) category.save() return category def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.posts.set(validated_data.get('new_posts', instance.posts)) instance.save() return instance views.py class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = (IsAdmin,) # permission_classes = (AllowAny,) permissions.py class IsAdmin(permissions.IsAdminUser): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: role_slug = None if not request.user.is_anonymous and request.user.role is not None: role_slug = request.user.role … -
How does distinct parameter work with the Count method in annotate?
I got a problem with annotate method when I was using the Count method to count multiple columns that come from the database which have a relationship with one of the tables. let me give you a quick example: match_session_instance = MatchSessionInstance.objects.filter(match_session=match_session, status="main") match_instances = MatchSessionInstance.objects.filter(match_session=match_session) action_counts = match_instances.values(player_number=F("player_pk__number"), player_name=F("player_pk__player"))\ .annotate(pass_count=Count("live_match_pass__id", distinct=True), corner_count=Count("live_match_corner__id", distinct=True)) in the meantime I'm not facing any problems I caught my issue and I addressed it but that is the problem now. I don't know How could "disticnt=True" parameter helps me to fix that problem! I googled a bit and found this source that has helped me: Count on multiple fields in Django querysets I know what does distinct as a method in ORM but actually, I get no idea how it works in that format special when I used columns that never have duplicated data. Can anyone help me to understand, please? thanks in advance -
Change reason field (django-simple-history) populated in django admin panel
I use django-simple-history in the project. The documentation https://django-simple-history.readthedocs.io/en/2.7.0/historical_model.html is clear as to how to pass changeReason value while updating the object. I wonder if it is possible to populate history_change_field in django admin panel when making changes? -
Appending all for loop dicts into single list
I just learnt django and I am getting data from api and looping through the json and appending the data into the list. but When I use .map() function in react then the data is appending in list (from for loop) like [ { "results": { "id": 544, "name": "User_1", } }, { "results": { "id": 218, "name": "User_2", } }, { "results": { "id": 8948, "name": "User_3", } }, { "results": { "id": 9, "name": "User_4", } }, ] It is not appending like (Like I want) [ results : [ { "id": 544, "name": "User_1" }, { "id": 218, "name": "User_2" }, { "id": 8948, "name": "User_3" }, { "id": 9, "name": "User_4" } ] ] views.py def extract_view(request): results_list = [] // api url for explanation only get_response = "https://api.punkapi.com/v2/beers" if get_response.status_code == 200: for result in get_response.json(): results_list.append({"results": result}) return Response({"data": results_list}) I know, In for loop it is appending every result within it with every iteration but I also want to assign all the responses within results list. I have tried many times but it is still not working. -
Customizing calendar.HTMLCalendar in a Django Project
I am using HTMLCalendar to add a calendar to my project. The calendar is showing perfectly fine but I want to add some customization to it. As a simple example I want to add a legend after the month and I want to add a condition so that if an event is on a specific date to have a button around the number of the month. I have found some very old answers but I am not sure how to actually implement. Similar answers:python calendar.HTMLCalendar Here is the current view: class home(ListView): model = Workout template_name = 'app/home.html' context_object_name = 'workouts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) year= datetime.now().year month=datetime.now().month cal=HTMLCalendar().formatmonth(year,month) context['cal']=cal print(cal) return context here is the current outcome: Here is the template I am sure there is an easier way that I did not yet find to add padding: <center>{{ cal|safe }}</center> <style> .month{ text-align: center; } .mon{ padding-left:15px; } .tue{ padding-left:15px; } .wed{ padding-left:15px; } .thu{ padding-left:15px; } .fri{ padding-left:15px; } .sat{ padding-left:15px; } .sun{ padding-left:15px; } </style> </div> This is the required outcome or similar to it: My question: How can I customize the HTMLCalendar so that I can reach the image showing and where should … -
TypeError: connect() argument 4 must be str, not WindowsPath
When I run this python manage.py migrate return Connection(*args, **kwargs) File "C:\Users\WyndhamKeitA\AppData\Roaming\Python\Python310\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) **TypeError: connect() argument 4 must be str, not WindowsPath** my DB under settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': BASE_DIR / 'db.crudpy', 'USERNAME': 'root', 'PASSWORD': '1234', 'PORT': '3306', 'HOST': 'localhost' } } How do I get rid of the error? crudpy is the schema I've created on mysql