Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make django middleware variables able to handle concurrent requests
I have to implement a custom middleware in django to count the number of requests served so far. It is a part of an assignment that I've got. I have created the middleware like this # myapp/middleware.py from django.utils.deprecation import MiddlewareMixin class RequestCounterMiddleware(MiddlewareMixin): request_count = 0 def process_request(self, request): RequestCounterMiddleware.request_count += 1 def process_response(self, request, response): return response @staticmethod def get_request_count(): return RequestCounterMiddleware.request_count Now my question is how to make the variable request_count able to handle concurrent requests and show the correct value. ChatGPT suggested using threading.Lock(). Would that be a good option? If not, please suggest some other way. Thanks :) -
fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory
running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running build_ext building 'MySQLdb.mysql' extension creating build\temp.win-amd64-cpython-312 creating build\temp.win-amd64-cpython-312\Release creating build\temp.win-amd64-cpython-312\Release\MySQLdb "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,0,'final',0) -D__version_=2.1.0 "-IC:\Program Files\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files\MariaDB\MariaDB Connector C\include" -ID:\python\ewp_django_backend\venv\include -IC:\Users\USER\AppData\Local\Programs\Python\Python312\include -IC:\Users\USER\AppData\Local\Programs\Python\Python312\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 (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win-amd64-cpython-312\Release\MySQLdb/_mysql.obj _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Failed to build backports.zoneinfo mysqlclient ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (backports.zoneinfo, mysqlclient) I … -
How to set up virtual environment in visual studio?
I am trying to start working with django and visual studio but I cannot figure out what are the instructiosns are to set up a virtual environemnt. How do you do this? I have both tried in a blank file and also in the Terminal. enter image description here I tried to both use the terminal and add the code to a blank file -
Django-Cryptography not encrypting sensitive data in models as expected
I am using django-cryptography to encrypt my sensible data, but it does not does it. ```python from django_cryptography.fields import encrypt class ComplaintModel(BaseModel): detailed_description = encrypt(models.TextField(null=False,)) <br> [![enter image description here][1]][1] <br> [![enter image description here][2]][2] [1]: https://i.sstatic.net/guv90eIz.png [2]: https://i.sstatic.net/2gEHhGM6.png -
How to add an i18n locale tag to a Nuxt api proxy?
I am currently working on an app with a Nuxt frontend and a Django backend. The Django backend is localized with i18n. Therefore, the URL contains an i18n tag (example.com/en/). I now want to take this tag from i18n in Nuxt and add it to my proxy in the Nuxt config, which currently looks like this: // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ compatibilityDate: '2024-04-03', devtools: { enabled: true }, modules: ['@nuxtjs/tailwindcss', '@nuxtjs/i18n'], nitro: { devProxy: { '/api': { target: `http://127.0.0.1:8000/`, changeOrigin: true, }, }, }, i18n: { locales: ['en', 'de'], defaultLocale: 'en', }, }); The process should be as follows: User with French Nuxt language calls example.com/hello mybackend.com/fr/hello is called via the proxy (/api). If it is Russian, mybackend.com/ru/hello is called. I tried to achieve my goal with a middleware, but could only append the tag. -
Django-Tables2 To Export Multiple Tables
I am working with Django-tables2 and Django to export multiple tables in 2 file. Is this possible? If so, how would it be done? When I try, it gives me an as_values error. -
How to include a field's display text (i.e., "get_foo_display") in a ModelSchema in django ninja?
Problem Let's say I have a django model with an IntegerField with a defined set of choices and then a django ninja schema and endpoint to update this model. How can I access the display text for the IntegerField (i.e., get_foo_display)? Example Code models.py from django.db import models from django.utils.translation import gettext_lazy as _ class PracticeSession(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False,related_name="practice_sessions", db_index=True, ) class RATING_CHOICES(models.IntegerChoices): UNHELP = 1, _('unhelpful') NEITHER = 2, _('neither helpful nor unhelpful') HELP = 3, _('helpful') rating = models.IntegerField(choices=RATING_CHOICES.choices) is_practice_done = models.BooleanField(default=False) api.py from ninja import NinjaAPI, Schema, ModelSchema from ninja.security import django_auth from practice.models import PracticeSession api = NinjaAPI(csrf=True, auth=django_auth) class UpdatePracticeSessionSchema(ModelSchema): class Meta: model = PracticeSession fields = ['is_practice_done', 'rating'] @api.put( "member/{member_id}/practice_session/{sesh_id}/update/", response={200: UpdatePracticeSessionSchema, 404: NotFoundSchema} ) def update_practice_sesh(request, member_id: int, sesh_id: int, data: UpdatePracticeSessionSchema): try: practice_sesh = PracticeSession.objects.get(pk=sesh_id) practice_sesh.is_practice_done = data.is_practice_done practice_sesh.rating = data.rating practice_sesh.save() return practice_sesh except Exception as e: print(f"Error in update_practice_sesh: {str(e)}") return 404, {'message': f'Error: {str(e)}'} Things I've tried I tried adding rating_choices = PracticeSession.rating.field.choices to my UpdatePracticeSessionSchema before class: Meta, but this triggered a pydantic error (see below), and, besides, this extra field in my Schema would have only gotten me a step closer to creating some … -
Django: How can I create code to show the question with follow levels as easy until hard
enter image description here enter image description here my system can show question have save in the table, but just random way. create code that categorizes questions by difficulty level (easy, medium, hard), and displays them in ascending order of difficulty. -
Unexpected " [] " Characters on Django Admin Log in Page
I have a Django App running on a local server. I am using the default admin features and rendering with collected static files. However, I am seeing " [] " inserted into the main content of the login form. Why is this and how do I ensure this doesn't occur? -
django 5.1 email [WinError 10061]
хочу отправить письмо с джанго вроде все настроил верно но выходит ошибка: ConnectionRefusedError: [WinError 10061] Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение. помогите пжл. вот мои настройки: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True EMAIL_HOST_USER = \['Vlad.Olegov750@yandex.ru'\] EMAIL_HOST_PASSWORD = 'пароль' RECIPIENTS_EMAIL = \['Vlad.Olegov750@yandex.ru'\] DEFAULT_FROM_EMAIL = \['Vlad.Olegov750@yandex.ru'\] SERVER_EMAIL = \['Vlad.Olegov750@yandex.ru'\] EMAIL_ADMIN = \['Vlad.Olegov750@yandex.ru'\] пробовал менять порт на 587. но без успешно -
How to use REST API in flowable-ui docker image
I have a Django Website, on this Website is a form and if I click on Submit, it should start a workflow in flowable(flowable-ui docker container). But I can't reach the API. curl 'http://admin:password@localhost:8080/flowable-ui/process-api/repository/deployments' does work, but everything else does not. It's always a 404 Error and I can't find the right URL to make this work. Can somebody please give advise on how to get this work? Greetings curl 'http://admin:passwort@localhost:8080/flowable-ui/process-api/repository/deployments' -> does work every other api call does not -
Image upload problem in django-ckeditor-5
I use django-ckeditor-5 in my Django project These are my ckeditor settings in settings.py CKEDITOR_5_CONFIGS = { 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', 'bulletedList', 'numberedList', '|', 'blockQuote', ], 'toolbar': { 'items': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough', 'subscript', 'superscript', 'highlight', '|', 'insertImage', 'fileUpload', 'bulletedList', 'numberedList', 'todoList', '|', 'blockQuote', '|', 'fontSize', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat', 'insertTable'], 'shouldNotGroupWhenFull': True }, 'image': { 'toolbar': [ "imageTextAlternative", "|", "imageStyle:alignLeft", "imageStyle:alignRight", "imageStyle:alignCenter", "imageStyle:side", "|", "toggleImageCaption", "|" ], 'styles': [ 'full', 'side', 'alignLeft', 'alignRight', 'alignCenter', ] }, 'table': { 'contentToolbar': ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties'], 'tableProperties': { 'borderColors': customColorPalette, 'backgroundColors': customColorPalette }, 'tableCellProperties': { 'borderColors': customColorPalette, 'backgroundColors': customColorPalette } }, 'heading': { 'options': [ {'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph'}, {'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1'}, {'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2'}, {'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3'} ] }, }, } CKEDITOR_5_ALLOW_ALL_FILE_TYPES = True CKEDITOR_5_FILE_UPLOAD_PERMISSION = "authenticated" This is the field where I used ckeditor: CKEditor5Field('content', config_name='news') But when I upload an image from my PC through admin panel, I get this error: This problem exists for all files, not just images Can you please advise what the problem … -
Retryable write with txnNumber 4 is prohibited on session | Django and MongoDB
How to do atomic update in below code following line of code throws an error: self._large_results.replace(json_result, encoding='utf-8', content_type='application/json') Application Code: class MyWrapper(EmbeddedDocument): # Set the maximum size to 12 MB MAXIMUM_MONGO_DOCUMENT_SIZE = 12582912 # Lock object to lock while updating the _large_result lock = threading.Lock() # The default location to save results results = DictField() # When the results are very large (> 16M mongo will not save it in # a single document. We will use a file field to store these) _large_results = FileField(required=True) def large_results(self): try: self._large_results.seek(0) return json.load(self._large_results) except: return {} # Whether we are using the _large_results field using_large_results = BooleanField(default=False) def __get_true_result(self): if self.using_large_results: self._large_results.seek(0) try: return json.loads(self._large_results.read() or '{}') except: logger.exception("Error while json converting from _large_result") raise InvalidResultError else: return self.results def __set_true_result(self, result, result_class, update=False): class_name = result_class.__name__ valid_result = self.__get_true_result() with self.lock: try: current = valid_result[class_name] if update else {} except: current = {} if update: current.update(result) else: current = result valid_result.update({class_name: current}) json_result = json.dumps(valid_result) self.using_large_results = len(json_result) >= self.MAXIMUM_MONGO_DOCUMENT_SIZE if self.using_large_results: self._large_results.replace(json_result, encoding='utf-8', content_type='application/json') self.results = {} self._large_results.seek(0) else: self.results = valid_result self._large_results.replace('{}', encoding='utf-8', content_type='application/json') Using Django with Mongo deployed in cluster and Celery to run these statements. getting … -
ATTRIBUTEERROR: module 'mysqldb.constants.er' has no attribute 'constraint_failed' [duplicate]
im trying to connect Mysql database with my django project. i get this after running my project: Traceback (most recent call last): File "C:\python\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\python\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\core\management\commands\runserver.py", line 126, in inner_run autoreload.raise_last_exception() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\contrib\auth\models.py", line 5, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\contrib\auth\base_user.py", line 40, in <module> class AbstractBaseUser(models.Model): File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\db\models\base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\db\models\base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\db\models\options.py", line 231, in contribute_to_class self.db_table, connection.ops.max_name_length() File "C:\Users\shara\source\repos\DjangoWebProject1\DjangoWebProject1\env\lib\site-packages\django\utils\connection.py", line 15, in __getattr__ … -
Why css is not updating in my django project?
I was working on django project and apparently css is not updating. It sticked to the css that I wrote last time. Help me to find solution! I tried to refresh in chrome with Ctrl+R, Ctrl+Shift+R. I tried to use it on different browser like Safari. And I also tried to make css inline in html. Nothing has worked. I want to write css in my django project and it should immediately reflect in the browser. -
how do i solve django pip dependency conflict error
I am currenlty working to integrate azureSQL to my website, but i am encountering this error that some of my packages require django version more than 4, others require version 2 what should i do. this is the error i am getting : ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts. djangorestframework 3.15.2 requires django>=4.2, but you have django 2.1.15 which is incompatible. django-cors-headers 4.4.0 requires django>=3.2, but you have django 2.1.15 which is incompatible. i tried downgrading django version but that gave me the same problem but for other packages -
Can't "test" amazon alexa custom skill in the developer console
I'm trying to develop a simple notification custom skill served on a web service using "django-ask-sdk". On the "build" tab, all the "Building Your Skill" categories are green: Invocation Name: OK Intents, Samples, and Slots: OK Build Model: OK Endpoint: OK On the "test" tab, "skill testing is enabled in" is set to "Development". On the "test" tab, in the "Alexa Simulator", it appears that I can issue a request, but the response is, "The requested skill can't be accessed". I'm using "HTTPS" endpoint type, and the endpoint set for the "Default Region" is correct. I'm not seeing any request being sent to my endpoint. Am I missing some configuration, or am I not understanding how the test tab works? How can I get a test request sent to my web skill? -
Looking for budget friendly hosting options for Django backend
I live in Turkey and plan to use Django for my backend. I’ve never rented hosting before and am looking for an affordable option that works well with Django. If you have any recommendations for reliable and budget-friendly hosting providers, I’d really appreciate your suggestions. I looked into hosting providers that support Django and compared their plans, but I haven’t been able to find a suitable and affordable option yet. -
Django Management Command Not Triggering API Update in Frontend: Debugging Connection Issues Between Django Backend and React Frontend
from django.core.management.base import BaseCommand from myapi.models import StrengthWknes, CustomUser import pandas as pd from sklearn.neighbors import NearestNeighbors from sklearn.linear_model import LinearRegression import numpy as np class Command(BaseCommand): help = 'Create study groups based on normalized percentages using k-NN and predict target score for the weakest subject' def add_arguments(self, parser): parser.add_argument('grade', type=str, help='Grade for which to create study groups') parser.add_argument('current_user_id', type=int, help='ID of the current user') parser.add_argument('n_neighbors', type=int, default=5, help='Number of neighbors to find') def handle(self, *args, **kwargs): grade = kwargs['grade'] current_user_id = kwargs['current_user_id'] n_neighbors = kwargs['n_neighbors'] user_data = self.fetch_user_data(grade) group_usernames, group_df = self.create_study_group(user_data, current_user_id, n_neighbors) if len(group_usernames) < 3: self.stdout.write(self.style.WARNING('Group is too small. Select group manually.')) else: self.stdout.write(self.style.SUCCESS(f'Created group: {group_usernames}')) # Predict target score for the weakest subject if not group_df.empty: target_scores = self.predict_target_score(group_df, current_user_id) self.stdout.write(self.style.SUCCESS(f'Target scores for the weakest subject: {target_scores}')) def fetch_user_data(self, grade): records = StrengthWknes.objects.filter(grade__grade=grade) data = [] for record in records: user = CustomUser.objects.get(pk=record.id.id) data.append({ 'user_id': user.id, 'username': user.username, 'normalized_percentage': record.normalized_percentage, 'strgth_wkness': record.strgth_wkness }) df = pd.DataFrame(data) self.stdout.write(self.style.SUCCESS(f'Fetched user data:\n{df}')) return df def create_study_group(self, df, current_user_id, n_neighbors): TOLERANCE = 10 # Tolerance percentage range for neighbor selection MAX_DIFF = 10 # Maximum allowed difference within the group if len(df) < n_neighbors: return [], pd.DataFrame() # Return … -
Can't access the Django endpoints
Can't access the various Django endpoints. Tried accessing the endpoints such as http://127.0.0.1:8000/api/line-chart-data/ http://127.0.0.1:8000/api/candlestick-data/ and etc, but got a 404. urls.py """ URL configuration for mysite project. The `urlpatterns` list routes URLs to For more information please see: https://docs.djangoproject.com/en/5.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ # mysite/urls.py from django.contrib import admin from django.urls import path from .views import line_chart_data, candlestick_data, bar_chart_data, pie_chart_data from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('charts.urls')), path('api/candlestick-data/', candlestick_data), path('api/line-chart-data/', line_chart_data), path('api/bar-chart-data/', bar_chart_data), path('api/pie-chart-data/', pie_chart_data), ] views.py # mysite/views.py from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def candlestick_data(request): data = { "data": [ {"x": "2023-01-01", "open": 30, "high": 40, "low": 25, "close": 35}, {"x": "2023-01-02", "open": 35, "high": 45, "low": 30, "close": 40}, ] } return Response(data) @api_view(['GET']) def line_chart_data(request): data = { "labels": ["Jan", "Feb", "Mar", "Apr"], "data": [10, 20, 30, 40] } return Response(data) … -
TypeError: ‘NoneType’ object is not iterable
when testing a site using pytest, I get an error in the test, and I can’t figure out what is causing the error, please tell me where exactly the problem is in my code, and how to fix it (Files with tests cannot be changed - pytest). My code views.py: from django.views.generic import ( CreateView, DeleteView, DetailView, ListView, UpdateView ) from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.contrib.auth.forms import PasswordChangeForm from django.urls import reverse_lazy from django.contrib.auth import update_session_auth_hash from django.contrib.auth.mixins import UserPassesTestMixin from blog.models import Category, Post from .models import Comment from .forms import CommentForm from .forms import PostForm from .forms import UserProfileForm User = get_user_model() class OnlyAuthorMixin(UserPassesTestMixin): def test_func(self): object = self.get_object() return object.author == self.request.user class PostListView(ListView): model = Post queryset = ( Post.published .order_by('-pub_date') ) paginate_by = 10 template_name = 'blog/index.html' class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = 'blog/create.html' def get_success_url(self): return reverse_lazy( 'blog:profile', kwargs={'username': self.request.user.username} ) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostDetailView(DetailView): model = Post template_name = 'blog/detail.html' context_object_name = 'post' def get_object(self, queryset=None): post_id = self.kwargs.get("post_id") return get_object_or_404(Post, pk=post_id) def get_context_data(self, … -
change_form.html cannot display any drop-down select fields for the ModelForm
I'm working on implementing a drop-down menu for the "add" page of Product_to_Stock_Proxy_Admin function in the Django admin interface. The options for the drop-down menu are from the Distributor model, which is a foreign key for the Product model. The output only shows the drop-down menu itself, and there are no values from the Distributor model, not even the default value "---------". I don't understand why this is happening. Sincerely thank you for your help and suggestions. The reason why I use change_form is because I use Ajax to display other columns immediately when the user fills in the barcode_number. Therefore, I need to implement the drop-down menu on my own. models.py class Product(models.Model): name = models.CharField(max_length=20, blank=True, null=True) distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE) barcode_number = models.CharField(max_length=20, blank=True, null=True) total_amount = models.IntegerField(blank=True, null=True) class Distributor(models.Model): name = models.CharField(max_length=10) admin.py class Product_to_Stock_Proxy_Admin(admin.ModelAdmin): form = Product_to_Stock_Proxy_Form change_form_template = 'admin/change_form.html' fields = ["distributor", "name", "total_amount"] admin/change_form.html This code only displays the drop-down item itself without any options, not even the default value "-------": {% block content %} <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row field-barcode_number"> <div> <div class="flex-container"> <label for="id_barcode_number">條碼號碼:</label> <input type="text" id="id_barcode_number" name="barcode_number" value="{{ form.barcode_number.value }}" /> </div> </div> </div> … -
Angular proxy not working with Django allauth
I have an angular + django project and mostly everything is working. I've setup a proxy.conf as mentioned in the documenation - example here: { "/api": { "target": "http://localhost:8000", "secure": false, "logLevel": "debug", "changeOrigin": true } } but for some reason I cannot make api calls to any django allauth endpoints. The proxy is working because i can make a request to /api/accounts/profile which is a custom view i created to fetch a users information. However, what I'm trying to do is use allauths pre-created endpoints such as /accounts/login or /accounts/logout. If I make a request to http://localhost:4200/accounts/login I get 404 errors that the page/view isn't found. If I remove the domain name so that the proxy kicks in - example: /accounts/login its the same thing. If I change the url to be http://localhost:8000/accounts/login I suddenly get cross origins errors, which means the url is recognized as existing but is not accessable. I have already added all of the cross origins settings to my settings.py and added crf token validation to eliminate some possibilities. Has anyone else experienced this and if so what have you done to fix it? I don't want to create views in Django, that would be … -
Razorpay integration error on python django
Unrecognized feature: 'otp-credentials'. error occured in browser console while razorpay integration and Method Not Allowed (POST): /checkout/ in terminal [TerminalBrowser Console](https://i.sstatic.net/Kn6QfxTG.png) HTML script and button already loaded above <script> var options = { "key": "rzp_test_THuJCWTGTSyCOm", // Enter the Key ID generated from the Dashboard "amount": "{{ razoramount }}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Anasulfiros", //your business name "description": "Purchase Product", "order_id": "{{ order_id }}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "handler": function(response){ console.log("success") var form = document.getElementById("myform"); // alert(form.elements["custid"].value); // alert(response.razorpay_payment_id); // alert(response.razorpay_order_id); // alert(response.razorpay_signature); window.location.href = "http://localhost:8000/paymentdone?order_id=${response.razorpay_order_id}&payment_id=${response.razorpay_payment_id}&cust_id=${form.elements["custid"].value}" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed',function(response){ alert(response.error.description); }); document.getElementById('rzp-button1').onclick = function(e){ console.log("button click"); rzp1.open(); e.preventDefault(); } </script> {% endblock payment-gateway %} views class checkout(View): def get(self,request): user = request.user add = Customer.objects.filter(user=user) cart_items=Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity * p.product.discounted_price famount = famount + value totalamount = famount + 40 razoramount = int(totalamount * 100) client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = {"amount":razoramount,"currency":"INR","receipt":"order_rcptid_12"} client.set_app_details({"title" : "Django", "version" : "1.8.17"}) payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status … -
Hello, can you tell me I'm writing a website on django 4
[enter image description here](https://i.sstatic.net/OmSFrl18.jpg) Вот так у меня [enter image description here](https://i.sstatic.net/ml9pLrDs.jpg) hello, you can tell me I'm writing a site on django 4 that gives the search bar select debugger in Run and Debug with the choice of only one single action, this is Python Debugger instead of the Debug Configuration search bar with a single choice of Django. Can you tell me how to solve this problem?? That's how the person I'm using to make the launch site.Our json is completely different. I don't understand how to solve this problem