Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't open deployed Django web app on Azure container instance
Run the below commands, all were successful, but can't open the web app on browser, how to fix it? virtualenv .venv .venv\Scripts\activate pip install Django django-admin startproject demoproject python manage.py runserver --notes: checked the web app was running at http://127.0.0.1:8000/ pip freeze > requirements.txt --notes: add file "Dockerfile" --notes: add file ".dockerignore" docker build -t demoproject:v1.0 . az login az acr login --name xxtestcr docker tag demoproject:v1.0 xxtestcr.azurecr.io/demoproject:v1.0 docker push xxtestcr.azurecr.io/demoproject:v1.0 az acr update -n xxtestcr --admin-enabled true az container create -g xxtestrg --name test-ci --image xxtestcr.azurecr.io/demoproject:v1.0 --ports 80 443 --cpu 1 --memory 1.5 --dns-name-label xxtest-demoproject Dockerfile: FROM python:3.10.8 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt CMD python manage.py runserver 0.0.0.0:8000 .dockerignore __pycache__ .venv/ Dockerfile The app files: Azure container instance overview: But can't open the web app on browser: 4.147.67.11 xxtest-demoproject.australiaeast.azurecontainer.io -
Can't get csrftoken in Django for ajax recently
I referenced the code provided in the official doc here https://docs.djangoproject.com/en/4.2/howto/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false It worked well until recent. I didn't make any modification to the getCookie method. But it suddenly can't work on both Chrome and Firefox. The document.cookie always return "". And CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False. How sould I debug? I need the csrftoken to be passed to the ajax request. Thanks. Referenced src is here function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue;} const csrftoken = getCookie('csrftoken'); -
Your connection is not private When used tried for https ssl with certbot
i have been deploying my django rest api backend in digitalocean but when the certificate is generated and i tried to call https://domain-name there was an issue from the chrome saying Your connection is not private Attackers might be trying to steal your information from www.tabsulbackendsolutions.in (for example, passwords, messages, or credit cards). Learn more NET::ERR_CERT_COMMON_NAME_INVALID server { server_name domain_name; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/akhil/tabsul/TabsulBackEnd; } location / { include proxy_params; proxy_pass http://unix:/home/akhil/tabsul/TabsulBackEnd.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/tabsulbackendsolutions.in-0001/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/tabsulbackendsolutions.in-0001/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 = domain_name) { return 301 https://$host$request_uri; } # managed by Certbot server_name domain_name; listen 80; return 404; # managed by Certbot } can anybody please ? -
please help me in integrating a code that performs facial detection and recognition in this views.py code for django and chnages in urls.py if needed
This is the code for the view as of now, which captures an image of the student at signup and opens up a screen of live video capture when the student starts taking the exam. I wish to integrate facial detection and recognition in this code such that the picture of the user captured during sign up is compared with the video steam during examination and an alert is given if it doesnot match. from django.shortcuts import render,redirect,reverse from . import forms,models from django.db.models import Sum from django.contrib.auth.models import Group from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required,user_passes_test from django.conf import settings from datetime import date, timedelta from exam import models as QMODEL from teacher import models as TMODEL import cv2 import os from django.http import StreamingHttpResponse import threading from django.views.decorators import gzip #### Initializing VideoCapture object to access WebCam face_detector = cv2.CascadeClassifier('static/haarcascade_frontalface_default.xml') # cap = cv2.VideoCapture(0) #for showing signup/login button for student def studentclick_view(request): if request.user.is_authenticated: return HttpResponseRedirect('afterlogin') return render(request,'student/studentclick.html') def extract_faces(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face_points = face_detector.detectMultiScale(gray, 1.3, 5) return face_points def student_signup_view(request): userForm=forms.StudentUserForm() studentForm=forms.StudentForm() mydict={'userForm':userForm,'studentForm':studentForm} if request.method=='POST': userForm=forms.StudentUserForm(request.POST) studentForm=forms.StudentForm(request.POST,request.FILES) username = request.POST.get('username') userimagefolder= 'static/profile_pic/Student/'+ username if not os.path.isdir(userimagefolder): os.makedirs(userimagefolder) cap = cv2.VideoCapture(0) i,j = 0,0 count=0 … -
How to host django app on ionos's VPS, i get invalid page on my ip:8000
How to host django app on ionos's VPS I have purchased the cheapest VPS plan of ionos and now i want to host my django app, but when i execute 'python manage.py runserver' command and go to my_ip:8000 it shows invalid page on the browser, can anyone help me??? -
Django Pytest Failing In GitHub Workflow - How to mimic production environment?
I'm using GitHub Actions to create a CI/CD pipeline that tests production settings before deploying. The tests pass in my local environment, and all of the code works in production. However, any tests related to views fail in my GitHub workflow. I believe the tests are failing because GitHub's testserver defaults to http protocol, I assume. And I have SECURE_SSL_REDIRECT = True in my production settings. Errors: _________________________ test_register_user_view_get __________________________ client = <django.test.client.Client object at 0x7fa8101e9e10> @pytest.mark.django_db def test_register_user_view_get(client): response = client.get(reverse("accounts:register")) > assert 200 == response.status_code E assert 200 == 301 E + where 301 = <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="https://testserver/account/register/">.status_code accounts/tests/test_views.py:11: AssertionError _________________________ test_register_user_view_post _________________________ client = <django.test.client.Client object at 0x7fa80f8b2650> django_user_model = <class 'accounts.models.User'> @pytest.mark.django_db def test_register_user_view_post(client, django_user_model): response = client.post( reverse("accounts:register"), data={ "username": "PostTest", "first_name": "User", "last_name": "Name", "email": "user@email.com", "password1": "zxceefF1238", "password2": "zxceefF1238", }, follow=True, ) assert 200 == response.status_code > assert django_user_model.objects.count() == 1 E AssertionError: assert 0 == 1 E + where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x7fa810f1b910>>() E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x7fa810f1b910>> = <django.contrib.auth.models.UserManager object at 0x7fa810f1b910>.count E + where <django.contrib.auth.models.UserManager object at 0x7fa810f1b910> = <class 'accounts.models.User'>.objects accounts/tests/test_views.py:30: AssertionError When changing: response … -
How can I add a form to edit Comments to each Instance on a Django DetailView?
I am new to Django and trying to figure out how to build a webapp where I have Assets, attached Instances (of these Assets), and Comments attached to these instances, so basically in terms of simplified models.py models.py class Asset(models.Model) class Instance(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE, related_name='instances') class Comment(models.Model): instance = models.ForeignKey(Instance, on_delete=models.CASCADE, related_name='comments') I know I will have to use forms based on the Instance class so I prepared this: forms.py class InstanceComment(ModelForm): class Meta: model = Instance fields = '__all__' I use the generic list view to display the list of Assets, when I click on one of them, I then display a list of the Instances attached to it using a Detail view. What I would like, is that on this page, have for each of the Instances, a form to edit the comment (there can be only one comment per Instance). I am struggling to see how to pass multiple forms to the view. I guess this is a very standard question with Django but I could not figure it out so far... Could I get any guidance on this? So far, I do not see how to effectively send a list of forms to the … -
Why am I getting a TypeError when passing HTTP method dictionaries to Django REST Framework's as_view() method in ViewSets?
I created a ViewSet, in which I need to use in two URL Patterns, one is for getting the list of items and other is for getting the detail of single item. The problem is, when I pass {"get": "retrieve"} and {"get": list", "post": "create"} dictionaries in as_view() methods of my ViewSets in URL Patterns, I get the following error: TypeError: APIView.as_view() takes 1 positional argument but 2 were given Below is my ViewSet code: class LungerItemViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, generics.GenericAPIView): permission_classes = [permissions.AllowAny,] def get_queryset(self): """Retrieves and returns all Lunger Items""" return LungerItem.objects.all() def get_serializer_class(self): """Returns serializer class""" return LungerItemSerializer and below are my URL Patterns for this ViewSet: urlpatterns = [ path('lungar-items/', views.LungerItemViewSet.as_view({'get': 'list', 'post': 'create'}), name='lunger-item-list'), path('lungar-items/<int:pk>/', views.LungerItemViewSet.as_view({'get': 'retrieve'}), name='lunger-item-detail'), ] I tried to search this issue on ChatGPT, but it did not help much. However, it helped me finding the cause of this error. As per ChatGPT and my own research this error appears, when: We use as_view instead of as_view(). Basicaaly as_view() is a method and we should treat it like that. We pass the HTTP Methods dictionary like {"get": "list"} in an APIView class instead of a ViewSet If there are any custom Middleware used … -
How to define Django model datefield
I am new in python django, i am creating app model and wants to define a field(date of birth) to input date from user form but unable to understand how to define date field in model so that i can capture the date(date of birth) using form. Here is model # Create your models here. class funder(models,Model): user_name = models.CharField(max_length=150) user_mobile = models.CharField(max_length=12) user_dob = models.DateField('none' = true) user_address = models.TextField() user_status = models.PositiveIntegerField(default='1') thanks -
Django date range filtering from url parameters returns empty queryset
I'm currently trying to do date range filtering from url parameters with get_queryset on a generics class based view, however I am receiving an empty array after doing date range filtering. It's a bit weird since I can print the queryset, just not able to return it. url parameter: http://127.0.0.1:8000/budget-filter?budget_date=2023-6-7&budget_end_date=2023-6-13 Below is the views.py @permission_classes([IsAuthenticated]) class BudgetFilter(generics.ListAPIView): serializer_class = BudgetSerializer paginator = None filter_backends = [DjangoFilterBackend] filterset_fields = ['budget_category', 'budget_account', 'budget_date', 'budget_end_date'] def get_queryset(self): user = self.request.user.username budget_date_url = self.request.GET.get('budget_date', None) budget_end_date_url = self.request.GET.get('budget_end_date', None) if budget_date_url is not None: queryset = BudgetModel.objects.filter(current_user = user).filter(budget_date__gte=budget_date_url, budget_date__lte=budget_end_date_url).values() print (queryset) return queryset Below is the serializers.py class BudgetSerializer(serializers.ModelSerializer): class Meta: model = BudgetModel fields = '__all__' models.py class BudgetModel(models.Model): budget_description = models.CharField(max_length=150) budget_price = models.DecimalField(max_digits=35, decimal_places=2) budget_account = models.CharField(max_length=100) budget_category = models.CharField(max_length=100) budget_currency = models.CharField(max_length=150) budget_date = models.DateField(auto_now=False) budget_end_date = models.DateField(auto_now=False, blank=True) budget_display_date = models.CharField(max_length=15) current_user = models.CharField(max_length=200) Response with print (queryset) <QuerySet [{'id': 20, 'budget_description': 'adassd', 'budget_price': Decimal('22.00'), 'budget_account': 'Main', 'budget_category': 'Education', 'budget_currency': 'AED', 'budget_date': datetime.date(2023, 6, 10), 'budget_end_date': datetime.date(2023, 6, 10), 'budget_display_date': '10 Jun 2023', 'current_user': 'myname'}]> I tried using different ways of date range filtering, however __gte and __lte method is the one that seemed to do the trick. … -
How can I make my newsletter form success message consistently display after clicking send?
Newsletter form Console shows this error After clicking send button, success message shows and email gets saved in database but after the message disappears and I click send again, the success message doesn't show but the data gets sent to database Also I have set fadeOut time to 2 seconds and during that 2 seconds, the message shows everytime I click send but the message won't show up after it disappears How can I make the message show even after the message disappears? Help!!! This is my ajax code: $("#newsletter_form").submit(function(e){ e.preventDefault() var serializedData = $(this).serialize(); $.ajax({ type: "POST", url: "{% url 'newsletter' %}", data: serializedData, success: function(response){ $("#newsletter_msg").append( `${response.message}` ).delay(2000).fadeOut('slow') }, error: function(response){ $("#newsletter_msg").append( `${response.responseJSON.message}` ).delay(2000).fadeOut('slow') }, }); }); -
Stop automatic encoding by FileField
I am using the FileField of django model. class Drawing(models.Model): drawing = models.FileField(upload_to='uploads/') For example I try uploading 2byte charactor filename such as 木.pdf, then filename is encoded into , %E6%9C%A8_sBMogAs.pdf automatically. However, I want to keep 2byte characters, so I override the FileField.py. Just copy and paste from here and put some print to check where the filename is changed. I put print in def pre_save(self, model_instance, add):, def generate_filename(self, instance, filename):``def save_form_data(self, instance, data): and def save(self, name, content, save=True): functions to see the filename However in every checkpoint, filename is still 木.pdf or 木_sBMogAs.pdf not %E6%9C%A8_sBMogAs.pdf Where the filename is changed? and how can I surpass the change of filename ? import datetime import posixpath from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import Storage, default_storage from django.core.files.utils import validate_file_name from django.db.models import signals from django.db.models.fields import Field from django.db.models.query_utils import DeferredAttribute from django.db.models.utils import AltersData from django.utils.translation import gettext_lazy as _ class FieldFile(File, AltersData): def __init__(self, instance, field, name): super().__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be … -
How Can I Apply ToastUI Editor in Django Application?
Has anyone heard of ToastUI Editor? It's so difficult to find resource concerning it. With Django ModelForm, I am trying to use ToastUI Editor as form's content field. I have implemented it through JS, but I am trying to find more pythonic and simpler way to do it. Here's how I have implemented it: base.html <!DOCTYPE html> <html lang="en"> <head> ... {# ToastUI #} <link rel="stylesheet" href="https://uicdn.toast.com/editor/latest/toastui-editor.min.css" /> </head> <body> ... {# ToastUI #} <script src="https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js"></script> </body> </html> create.html {% extends 'base.html' %} {% block content %} <form id="journal-form" action="{% url 'notes:create' %}" method="post" enctype='multipart/form-data'> {% csrf_token %} {% with journal_form.title as title %} <div class="form-group"> <label for="{{ title.id_for_label }}">{{ title.label }}</label> <input type="{{ title.field.widget.input_type }}" class="form-control" id="" placeholder="{{ title.label }}" name="{{ title.name }}" /> </div> {% endwith %} {% with journal_form.content as content %} <div class="form-group" style="display: none;"> <label for="{{ content.id_for_label }}">{{ content.label }}</label> <textarea id="{{ content.id_for_label }}" class="form-control" placeholder="{{ content.label }}" name="{{ content.name }}"></textarea> </div> {% endwith %} <div id="editor"></div> <div> {{ journal_image_form.as_p }} </div> <button type="submit" class="btn btn-primary">Create</button> </form> <script> document.addEventListener('DOMContentLoaded', (event) => { const editorDiv = document.getElementById('editor'); const editor = new toastui.Editor({ el: editorDiv, height: '500px', initialEditType: 'markdown', previewStyle: 'vertical', initialValue: editorDiv.value, }) const journalForm = … -
Button Click Fails to Redirect to Intended URL
I'm attempting to click on a button that should lead me to a specific page in my URLs but it's not functioning as expected. mainpage.html: <form method="POST"> <input type="button" name="Show Result" onclick="location.href='{% url 'get_result' %}'" value="Show Result"></input> </form> my pages in view : def get_result(request): def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("a",) result = None def on_message(client, userdata, msg): global result result = msg.payload.decode("utf-8") print("Received message:", result) client = mqtt.Client("p1") client.connect("127.0.0.1", 1883) client.publish("test", 'C:/Users/HP/Desktop/reallifeviolencesituation/NV_4.mp4') client.on_connect = on_connect client.on_message = on_message client.loop_forever() context = {'result': result} return render(request, "result.html", context) my urls: urlpatterns = [ path('admin/', admin.site.urls), path('', showvideo, name='showvideo'), path('get_result/', get_result, name='get_result') ] thanks -
Django Google reCAPTCHA not working - form data submits but page redirects to 404 page, how to solve?
I build a contact page with a django where is two forms. When I submit contact page form with google reCaptcha verification form data is submitting to the backend or admin panel but it redirecting my page to 404 page after submitting the form with google recaptcha. my html forms for contact.html {% block contactpage %} <!--====== PAGE TITLE PART START ======--> {% for cslider in cslider %} <div class="page-title-area"> <div class="section__bg" style="background-image: url('{{cslider.slider_image.url}}');"></div> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="page-title-content text-center"> <h3 class="title">Contact</h3> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="#">Accueil</a></li> <li class="breadcrumb-item active" aria-current="page">Contact</li> </ol> </nav> </div> </div> </div> </div> </div> {% endfor %} <!--====== PAGE TITLE PART ENDS ======--> <!--====== CONTACT US PART START ======--> <section class="contact-us-area contact-us-page"> <div class="section__bg" style="background-image: url('{% static 'images/black-elegant-background-with-copy-space.jpg' %}');"></div> <div class="container"> <!--Hidden Message Alert Area--> <div class="container"> {% for message in messages %} <div class="alert alert-primary alert-dismissible fade show" role="alert"> <svg xmlns="http://www.w3.org/2000/svg" class="bi bi-exclamation-triangle-fill flex-shrink-0 me-2" viewBox="0 0 16 16" role="img" aria-label="Warning:"> <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 … -
How to reduce duplicate queries in Django?
My problem is in optimization Django queries. I'm working on school project: web-app when you can get some tasks. I wrote code for generate variants with tasks, each variant have 25 tasks. The problem is that django sent 54 queries, i can understood 4 of them, and 25 of them, but somehow django sent 25 queries additionally. Here are query sets(4-53: are almost same queries, but with another numbers): Sent queries: 54 1:{'sql': 'SELECT "SolveGiaApp_category"."id", "SolveGiaApp_category"."name", "SolveGiaApp_category"."edges", "SolveGiaApp_category"."max_type_number" FROM "SolveGiaApp_category"', 'time': '0.016'} 2:{'sql': 'SELECT "SolveGiaApp_category"."id", "SolveGiaApp_category"."name", "SolveGiaApp_category"."edges", "SolveGiaApp_category"."max_type_number" FROM "SolveGiaApp_category"', 'time': '0.000'} 3:{'sql': 'SELECT "SolveGiaApp_category"."id", "SolveGiaApp_category"."name", "SolveGiaApp_category"."edges", "SolveGiaApp_category"."max_type_number" FROM "SolveGiaApp_category" WHERE "SolveGiaApp_category"."name" = 'Informatika' LIMIT 21', 'time': '0.000'} 4:{'sql': 'SELECT "SolveGiaApp_task"."id", "SolveGiaApp_task"."type_number", "SolveGiaApp_task"."text", "SolveGiaApp_task"."answer", "SolveGiaApp_task"."photos", "SolveGiaApp_task"."files", "SolveGiaApp_task"."rating", "SolveGiaApp_ task"."category_id" FROM "SolveGiaApp_task" WHERE ("SolveGiaApp_task"."rating" <= 5 AND "SolveGiaApp_task"."type_number" = 1) ORDER BY "SolveGiaApp_task"."rating" DESC LIMIT 1', 'time': '0.062'} 5:{'sql': 'SELECT "SolveGiaApp_task"."id", "SolveGiaApp_task"."type_number", "SolveGiaApp_task"."text", "SolveGiaApp_task"."answer", "SolveGiaApp_task"."photos", "SolveGiaApp_task"."files", "SolveGiaApp_task"."rating", "SolveGiaApp_ task"."category_id" FROM "SolveGiaApp_task" WHERE ("SolveGiaApp_task"."rating" <= 5 AND "SolveGiaApp_task"."type_number" = 1) ORDER BY "SolveGiaApp_task"."rating" DESC', 'time': '0.063'} 6:{'sql': 'SELECT "SolveGiaApp_task"."id", "SolveGiaApp_task"."type_number", "SolveGiaApp_task"."text", "SolveGiaApp_task"."answer", "SolveGiaApp_task"."photos", "SolveGiaApp_task"."files", "SolveGiaApp_task"."rating", "SolveGiaApp_ task"."category_id" FROM "SolveGiaApp_task" WHERE ("SolveGiaApp_task"."rating" <= 5 AND "SolveGiaApp_task"."type_number" = 2) ORDER BY "SolveGiaApp_task"."rating" DESC LIMIT 1', 'time': '0.047'} 7:{'sql': 'SELECT "SolveGiaApp_task"."id", "SolveGiaApp_task"."type_number", "SolveGiaApp_task"."text", "SolveGiaApp_task"."answer", "SolveGiaApp_task"."photos", … -
Why am I getting Error 405 - Method not allowed when trying to save data from Django custom form?
Error 405 - Method not allowed when trying to save a data to a custom form using Django. Method Not Allowed (POST): /create-establishment/ Method Not Allowed: /create-establishment/ I created a class, and the associated views and URL patterns. The HTML displays fine, and I can see the data in the Request. However, it just won't go through. Model: class Establishments(models.Model): org_name = models.CharField(max_length=255) address = models.TextField() epfo_code = models.CharField(max_length=20) esic_code = models.CharField(max_length=15) employer_name = models.CharField(max_length=60) employer_phone = models.CharField(max_length=10) contact_name = models.CharField(max_length=60) contact_phone = models.CharField(max_length=10) epfo_username = models.CharField(max_length=30) epfo_password = models.CharField(max_length=30) esic_username = models.CharField(max_length=30) esic_password = models.CharField(max_length=30) created_on = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Establishments" def __str__(self): return self.org_name Views: ``class CreateEstablishmentView(TemplateView): def get(self, request): form = CustomEstablishmentRegistrationForm() return render(request, 'create_establishment.html', {'form': form}) class EstablishmentDetailView(TemplateView): template_name = "establishment_detail.html" def post(self, request): form = CustomEstablishmentRegistrationForm(request.POST) if form.is_valid(): establishment = form.save() return redirect('establishment_detail', pk=establishment.pk) return render(request, 'create_establishment.html', {'form': form}) def establishment_detail(request, pk): establishment = Establishments.objects.get(pk=pk) return render(request, 'establishment_detail.html', {'establishment': establishment})` ` URL: path("create-establishment/", views.CreateEstablishmentView.as_view(), name="create-establishment"), path('establishment-detail/<int:pk>/', views.establishment_detail, name='establishment_detail'), The code should enter the data in the Establishments table. I have tried including both POST and GET methods, but the error persists. I initially used the POST method to extract the data from the … -
How to use proxy server in my django local development?
I am trying to create a web project which need to make a request to another API which use a kind DATADOME capcha system. To bypass it, I need to use a rotating proxy API. When I use that on a simple script it works but when I use django I am locked by this CAPCHA. So, how it is possible to use proxy in my project development.In my projet, I need to make a request in order to catch the data. Thanks for your help everyone! here is the format of my proxy: username = "********" password = "********" ADDRESS_DNS = "***********:9000" proxy = {"http":"http://{}:{}@{}".format(username, password, ADDRESS_DNS)} -
Why is 'b' being added to my Django app's varchar data after upgrading to Django 4.2?
I am migrating an application from Django1.11/Python2.7/Postgres9.2 to Django4.2/Python3.11/Postgres14.3 (FYI I am also migrating the data from postgres 9 to 14). I am running into an issue where I call a form where the varchar data that is displayed in my app gets a "b'" and "'" appended to the data displayed by the form. Example (John is now 'bJohn') and modifies the data in the postgres database by adding the "b'" and "'" to the data. I have tried to clean the data, removed migrations, dropped the database, etc. FYI when I type() the fields everything returns as type 'str', even after the b' is added to the data. Here is my Model class User(TimeStampedModel): number = models.CharField(max_length=6, primary_key=True, verbose_name="Number") moniker = models.CharField(max_length=32) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) full_name = models.CharField(max_length=128) department = models.CharField(max_length=32) location = models.CharField(max_length=32) employee_type = models.CharField(max_length=32) title = models.CharField(max_length=128, blank=True) mail = models.EmailField(max_length=32) Here is my form class UserForm(forms.ModelForm): class Meta: model = User fields = ['number', 'first_name', 'last_name', 'department', 'location', 'employee_type', ] labels = { 'number': _('Number'), 'first_name': _('First Name'), 'last_name': _('Last Name'), 'mail': _('E-Mail Address'), } Here how I call the form in my template. {% block mainblock %} <h1>System</h1> <p>Please select … -
Redirecting to post detail page after editing a comment in Django causes 'NoReverseMatch' error. What am I doing wrong?
I want to do 2 redirects with url having 1 pk is that possible? please help i am getting error I am working on a blog application. I have a views function for the user to edit his comment. my problem is this: when user clicks save button after editing, i can't redirect him to post detail page. my views.py @login_required def comment_edit(request, pk): comment = Comment.objects.get(id=pk) form = CommentUpdateForm(instance=comment) if request.method == 'POST': form = CommentUpdateForm(request.POST, instance=comment) if form.is_valid(): form.save() return redirect('blog-post-detail') context = {'form':form,} return render(request, 'comment_edit.html', context) @login_required def post_edit(request, pk): post = Post.objects.get(id=pk) if request.method == 'POST': form = PostUpdateForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect('blog-post-detail', pk=post.id) else: form = PostUpdateForm(instance= post) context = { 'post': post, 'form': form, } return render(request, 'post_edit.html', context) my urls.py from django.urls import path from .import views urlpatterns=[ path('blogs/', views.blog, name="blog"), path('post_detail/<int:pk>/', views.post_detail, name="blog-post-detail"), path('post_edit/<int:pk>/', views.post_edit, name="blog-post-edit"), path('post_delete/<int:pk>/', views.post_delete, name="blog-post-delete"), path('comment_delete/<int:pk>/', views.comment_delete, name="blog-comment-delete"), path('comment_edit/<str:pk>/', views.comment_edit, name="blog-comment-edit"), ] my html: {% extends 'blog.html' %} {% load crispy_forms_tags %} {% block title %}Yorumu Düzenle{% endblock %} {% block content %} <div style="margin-top: 10%;" class="container"> <div class="row mt-5 pt-3 fluid"> <div class="col-md-8 offset-md-2"> <div class="card"> <div class="card-body"> <form method="POST"> {% csrf_token %} {{ … -
VSCode debugger in Django only hits once - on initial load
I am trying to make the debugger hit a breakpoint when Django handles a request. I set a breakpoint in a View and start the debugger in VSCode. The breakpoint get's hit when I start the app and continues when I press play. However, it never hit's the breakpoint again if I make requests to that view. It looks like the debugger works on load and then the code runs in the normal terminal and the debug console is just blank. So it seems like the code is not actually running inside the debugger. Any suggestions? { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/src/python/.../manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true, "justMyCode": true }, ] } # urls.py router.register("products", ProductViewSet) # products.py class ProductViewSet(viewsets.ReadOnlyModelViewSet): queryset = ... breakpoint() # Trying to hit a breakpoint here when a request is made serializer_class = ProductSerializer @extend_schema(request=None, responses=ProductPriceSerializer()) -
How can I ensure correct grouping in a Django subquery annotation?
When I'm writing Django Subquery expressions, sometimes I have no idea how Django is going to group the result. Example: subquery = ( RelatedModel.objects.filter( category="some_category", grandparentmodel=OuterRef("relatedmodel__grandparentmodel"), mymodel__created_at__date=OuterRef("created_at__date"), ) .values("grandparentmodel", "mymodel__created_at__date") .annotate(net=Sum("mymodel__amount")) .values("net")[:1] ) query = ( MyModel.objects.annotate( net=Coalesce( Subquery(subquery), Decimal("0.00") ) ) ) With this, my goal is to group a bunch of ParentModel instances (with category "some_category") by grandparentmodel and mymodel__created_at__date. This seems to work only if I include the .values("mymodel__created_at__date") before my annotation. If I do not include that before my annotation of net, the subquery still runs and just gives incorrect net. However, the .values("grandparentmodel") seems not required to get the correct grouping; I can exclude it and I still get the values I'm expecting. What's going on behind the scenes? How would I know to use a .values() call before my annotation to group correctly? How would I know what to include in said values() call? Is there some rule of thumb to follow when aggregating in subqueries? -
How to fix this issue in django & mysql It is impossible to change a nullable field 'description' on item to non-nullable without providing a default
i am having this problem where when i try to make migrations in python it shows this error -> It is impossible to change a nullable field 'description' on item to non-nullable without providing a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now. Existing rows that contain NULL values will have to be handled manually, for example with a RunPython or RunSQL operation. Quit and manually define a default value in models.py. Select an option: -
Problema al guardar los datos actualizados de una tabla de Django (Vinculada a MySQL) a través de un formulario HTML
estoy tratando de llevar a cabo la función de actualizar de mi CRUD, sin embargo cuando intento guardar los cambios me da un error indicando que el formulario fue invalido (Sin importar si se cambiaron o no los valores de los campos). Estoy utilizando Python con el framework Django junto a HTML y Bootstrap 5. El modelo que estoy implementando es este: #LIBRERIAS NECESARIAS PARA QUE TODO FUNCIONE CORRECTAMENTE from django.db import models from django import forms from django.contrib.auth.models import User #CREACIÓN DE LOS MODELOS class Arbol(models.Model): #Defino las opciones de estado ESTADO = [ ("AJOV","Árbol joven"), ("AADU","Árbol adulto"), ("AANC","Árbol anciano") ] #Defino las opciones de salud SALUD = [ ("ASAN","Árbol sano"), ("AHER","Árbol herido"), ("AENF","Árbol enfermo"), ("AMUE","Árbol muerto") ] #Campos que lleva la tabla en la base de datos id = models.AutoField(primary_key=True, verbose_name="Identificador") especie = models.CharField(max_length=100, null=True, verbose_name="Especie") # estado = forms.ChoiceField(choices=ESTADO, required=True, label="Estado") # salud = forms.ChoiceField(choices=SALUD, required=True, label="Salud") estado = models.CharField(max_length=20, choices=ESTADO, null=True, verbose_name="Estado") salud = models.CharField(max_length=20, choices=SALUD, null=True, verbose_name="Salud") edad = models.DecimalField(max_digits=10,decimal_places=2 ,null=True, verbose_name="Edad [Años]") altura = models.DecimalField(max_digits=10, decimal_places=2, null=True, verbose_name="Altura [Metros]") encargado = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Encargado") #INFORMACIÓN DEL OBJ PRESENTADA EN EL ADMINISTRADOR (TO STRING) def __str__(self): info = f"Especie: {self.especie} - Estado: {self.estado} - Salud: … -
typeError: fromisoformat: argument must be str,
I trie many solutions from the internet nothing worked.. thanks in advance Error typeError: fromisoformat: argument must be str view.py def notes(request): now = datetime.datetime.now() month = now.month year = now.year cal = HTMLCalendar() events = Note.objects.filter(date_month=month, date_year=year) notes = Note.objects.all() return render(request, 'notes/home.html',{ 'cal': cal, 'events': events, }