Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to django orm get value anyone in query multi dictionary
Hi I want get model data with django orm. Mymodel, Security Field have multiple dictionary in list. if group_id = sg-1111222222 , i will get below data. So, I want to find a value that matches at least one of several dictionaries. [ { "GroupId": "sg-12345", "GroupName": "test1" }, { "GroupId": "sg-1111222222", "GroupName": "test2" } ] -
when i use axios of vue,don't get session in django
When I use axios in vue to send a request, django can get the request, but it cannot return the value in request.session. The return value of axios is always null. I tried many methods on the Internet but couldn't find a solution This is my axios request import axios from "axios"; export default function(){ axios.get("/api/session/", { withCredentials: true }) .then((response) => { console.log('err:', response.data); }) .catch((error) => { console.error('err:', error); }); } This is my function to handle requests class GetSession(APIView): def get(self, request): session_data = request.session.get("self_data") return Response({"statue": True, "session": session_data}) def post(self, request): session_data = request.session.get("self_data") return Response({"statue": True, "session": session_data}) I also set settings.py in django """ Django settings for transfer project. Generated by 'django-admin startproject' using Django 3.2.10. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os ALLOWED_HOSTS = ['*'] BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-0u0t-zy!qkafw1dn65ce662z%s8o(j)_#m)ewm5)ypn7ew8=vz' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'app01.apps.App01Config', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'transfer.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
What is the best approach to handle long tasks in a django app
So I have one function where clients uploads files and does a little parsing and then proceeds to send these results using another API. Now each file takes around 30 seconds to complete and a large deal of that is a POST request im making and awaiting an answer for 25 seconds. My initial solution was that when a client sent a request about this particular function of my app I'd just loop through all those files until the task was completed and then sent back a http response. Of course I noticed that I started getting 504 error because it was taking too long. My second, and current, solution is to respond with a http response immediately containing an empty html page where I then use javascript to use fetch to make calls to this function(a django view) and continually update the page and tell the client that a file has been processed. I also introduced threads to this solution and to my surprise it made it a lot faster, I suppose that is because each thread can get to that point where it waits for the long POST request so going from one to two almost doubled the … -
TemplateSyntaxError : Could not parse the remainder: '(ticket.status' from '(ticket.status'
when i use this condition it gives an syntax error like this TemplateSyntaxError at /developers/dev_pendings/Could not parse the remainder: '(ticket.status' from '(ticket.status'Request Method: GETRequest URL: http://127.0.0.1:8000/developers/dev_pendings/Django Version: 4.2.6Exception Type: TemplateSyntaxErrorException Value: Could not parse the remainder: '(ticket.status' from '(ticket.status'Exception Location: C:\Users\x\Desktop\lspok\vnv\Lib\site-packages\django\template\base.py, line 703, in initRaised during: Developers.views.devPendingsDashboardPython Executable: C:\Users\x\Desktop\lspok\vnv\scripts\python.exePython Version: 3.11.3Python Path: ['C:\Users\x\Desktop\lspok\pokeus','C:\Users\x\AppData\Local\Programs\Python\Python311\python311.zip','C:\Users\x\AppData\Local\Programs\Python\Python311\DLLs','C:\Users\x\AppData\Local\Programs\Python\Python311\Lib','C:\Users\x\AppData\Local\Programs\Python\Python311','C:\Users\x\Desktop\lspok\vnv','C:\Users\x\Desktop\lspok\vnv\Lib\site-packages']Server time: Wed, 18 Oct 2023 11:44:14 +0530' The code i used like this : {% elif (ticket.status == 'DA' or ticket.status == "CD" ) and ticket.tester_id != '' %} Why this happening, isn't it right way in Django? I just want evaluate this condition correctly -
While using DRF APIView with drf_yasg appears additional POST query, that i have not defined
I have got this urls urlpatterns = [ path('users/', UserApiView.as_view()), path('users/<str:pk>/', UserApiView.as_view()), ] and APIView class: class UserApiView(APIView): @swagger_auto_schema( request_body=CreateUserSerializer, responses={'200': openapi.Response('response description', DetailUserSerializer(many=True))} ) def post(self, request): user_data = CreateUserSerializer(request.data) user_data.is_valid(raise_exception=True) new_user = user_data.save() return Response(DetailUserSerializer(new_user).data) @swagger_auto_schema( responses={'200': openapi.Response('response description', DetailUserSerializer)} ) def get(self, request): queryset = UserRepo().get_all() serializer = DetailUserSerializer(queryset, many=True) return Response({'data': serializer.data}) @swagger_auto_schema( responses={'200': openapi.Response('response description', DetailUserSerializer(many=True))} ) def get(self, request, pk=None): queryset = UserRepo().get_all() user = get_object_or_404(queryset, pk=pk) serializer = DetailUserSerializer(user) return Response(serializer.data) but in swagger i see extra /users/{id}/ POST query (it's the last one) enter image description here I tried to find something in drf_yasg docs, but it was not successful -
Django Rest Framework with TensorFlow: Server Error on Model Training Endpoint
I'm building a web application using Django Rest Framework (DRF) to train a TensorFlow model and then use that model for text prediction. I have separated the training and prediction into two APIViews: TrainModelView and TextGenerationView. When I hit the /train_model/ endpoint, I am getting a 500 Internal Server Error. The error logs show: ERROR:django.request:Internal Server Error: /train_model/ [17/Oct/2023 21:42:28] "POST /train_model/ HTTP/1.1" 500 72 Here's the relevant part of my DRF view: python class TrainModelView(APIView): # ... [Your Code Here] def post(self, request, *args, **kwargs): data_path = r"C:\Users\hp\Downloads\models\urlsf_subset00-7_data\0006004-f940b83d9ed9a19f39d18df04679b071.txt" train_data, train_labels, tokenizer = data_preprocessing.preprocess_txt_data(data_path) # ... [Rest of Your Code] What I have tried so far: Checked the data path and ensured that the file exists. Tested the model training function separately, and it seems to be working fine. What I have tried so far: Checked the data path and ensured that the file exists. Tested the model training function separately, and it seems to be working fine. -
dj-rest-auth - Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I am using dj-rest-auth, and after following the documentation exactly how it is, when I go to the password/reset api endpoint, and enter my email, it return this error: NoReverseMatch at /api/dj-rest-auth/password/reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/api/dj-rest-auth/password/reset/ Django Version: 4.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Exception Location: /Users/coding/Projects/django/user_template_api/.venv/lib/python3.12/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix Raised during: dj_rest_auth.views.PasswordResetView Python Executable: /Users/coding/Projects/django/user_template_api/.venv/bin/python3 Python Version: 3.12.0 Python Path: ['/Users/coding/Projects/django/user_template_api/backend', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python312.zip', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload', '/Users/coding/Projects/django/user_template_api/.venv/lib/python3.12/site-packages'] Server time: Wed, 18 Oct 2023 01:59:54 +0000 this is my accounts/urls.py from django.urls import include, path from rest_framework import routers from .views import CustomUserViewSet from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) router = routers.DefaultRouter() router.register(r'users', CustomUserViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), ] this is my settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside … -
Writing your first Django app, part 5 error import models
I’m doing the first django application tutorial, I’m in part 05 and I’m having problems with “tests.py”, when I run “python manage.py test polls”, it returns the following error message: “RuntimeError: Model class mysite.polls.models.Question doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.” However, ‘polls.apps.PollsConfig’ has already been added to INSTALLED_APPS, and the error continues to appear. I started “from polls.models import Question”, I managed to start the entire test through the shell, but in tests.py it gives this error I want the error to go away so I can run the necessary tests and continue the django tutorial -
Response Data from Django API not Fetching correctly, got an empty array #React,
I have the following data in the API in the backend (does this mean that I have backend well settled??): enter image description here And I'd like to display them in the frontend something like this: enter image description here Instead, I got the following empty page: enter image description here The structure of the folder is: enter image description here And the code of api.js file is the following: import { toast } from 'react-toastify'; function request(path,{ data = null, token = null, method = "GET"}) { return fetch(path, { method, headers: { Authorization: token ? `Token ${token}` : "", "Content-Type": "application/json", }, body: method !== "GET" && method !== "DELETE" ? JSON.stringify(data) : null, }) .then((response) => { console.log(response) // If it is success if(response.ok) { if (method === "DELETE") { // if delete, nothing return return true; } return response.json(); } //Otherwise, if there are errors return response .json() .then((json)=>{ // Handle Json Error, response by the server if (response.status === 400) { const errors = Object.keys(json).map( (k) => `${(json[k].join(" "))}` ); throw new Error(errors.join(" ")); } throw new Error(JSON.stringify(json)); }) .catch((e) => { if (e.name === "SyntaxError") { throw new Error(response.statusText); } throw new Error(e); }) … -
simplejwt token work for all tenants for django-tenants
I just want to mention about my problem. I have already researched many documents but I could not find any solution. I just try to use django-tenants. Everything seems OK. But If any user gets the token after login, that token works for all tenants. It's a big leak of security. I have been thinking about an idea SIGNING_KEY. If I can change SIGNING_KEY for each tenant, it may be fixed. But It did not. class TenantJWTAuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): tenant = Client.objects.get(schema_name=connection.schema_name) jwt_secret_key = tenant.jwt_secret_key settings.SIMPLE_JWT['SIGNING_KEY'] = jwt_secret_key This is my Middleware to change SIGNING_KEY for each tenant. class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField() on_trial = models.BooleanField() created_on = models.DateField(auto_now_add=True) jwt_secret_key = models.CharField(max_length=100, null=True, blank=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass This is my model. So, I added jwt_secret_key into my model and I got this field in Middleware and tried to set SIGNING_KEY for jwt. But still, jwt after user login can be used for all tenants. Does anyone have any idea about my problem? Any suggestion or amendment to my solution? Thanks. -
how to refresh the page without reloading, using django, ajax, jquerry?
So I am trying to delete products from cart without refreshing the entire page, I can delete an item and then I need to reload the page to delete another item. I am using Django, jQuery and AJAX to attain the desired result after going through questions of similar nature. In another branch I have implemented the auto refresh feature, whereby after deletion the page automatically reloads but it is not a great user experience. Any help will be greatly appreciated. here's my views.py delete item from cart function def delete_item_from_cart(request): cart_total_amt = 0 product_id = str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data = request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_amt += int(item['qty']) * float(item['price']) context = render_to_string("core/async/cart-list.html", {"cart_data":request.session['cart_data_obj'], 'totalCartItems':len(request.session['cart_data_obj']), 'cart_total_amount':cart_total_amt}) return JsonResponse({"data":context, "totalCartItems":len(request.session['cart_data_obj'])}) here's my function.js implementation $(document).ready(function(){ $(".delete-product").on("click", function(){ let product_id = $(this).attr("data-product") let this_val = $(this) console.log(product_id); console.log(this_val); $.ajax({ url:'/delete-from-cart', data:{ 'id':product_id }, dataType: 'json', beforeSend: function(){ console.log("IN before send"); this_val.hide() console.log("IN after send"); }, success: function(response){ console.log("Starting success"); this_val.show() $("#cart-items-count").text(response.totalCartItems) $("#cart-list").html(response.data) console.log("successfully removed"); }, error: function(response){ alert('error'); } }) }) }) To be able to delete the next item in the cart without refreshing … -
Redirect Django TemplateDoesNotExist to 404
When the template does not exist, a 500 error returns to the user. I want Django to redirect to the 404 page for any view that gets a TemplateDoesNotExistError. Is there a way to accomplish this? -
The problem of creating a relationship between database tables in Django
Hello I wrote a ticketing system for site support and created a ticket class and a ticket response class in the model MODEL.py : class Ticket(models.Model): status_choices = ( ('Active','Active'), ('Completed', 'Completed'), ('Pending', 'Pending'), ) ticket_number = models.UUIDField(default=uuid.uuid4) title = models.CharField(max_length=200,verbose_name='Title') description = models.TextField(verbose_name='Description') created_by = models.ForeignKey(User,on_delete=models.CASCADE,related_name='created_by') date_created = models.DateTimeField(auto_now_add=True) ticket_status = models.CharField(max_length=15,choices=status_choices) def __str__(self): return self.title class TicketReply(models.Model): description = models.TextField(verbose_name='Description') ticket_user = models.ManyToManyField('Ticket') date_update = models.DateTimeField(auto_now_add=True) assigned_to = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.description And I created a form to create and update tickets FORMS.py : class CreateTicketForm(forms.ModelForm): class Meta: model = Ticket fields = ['title','description'] class UplateTicketModelForm(forms.ModelForm): class Meta: model = TicketReply fields = ['description'] widgets = { 'description': forms.Textarea(attrs={ 'class': 'form-control', 'rows': 4, }), } labels = { 'description': 'Reply', } error_messages = { 'description': { 'required': 'Enter the description' } } And finally, I wrote the two function so that the user can create and track the ticket. VIEW.py : def create_ticket(request): if request.method == 'POST': form = CreateTicketForm(request.POST) if form.is_valid(): var = form.save(commit=False) var.created_by = request.user var.ticket_status = 'Pending' var.save() messages.info(request,'Your ticket has been successfully.') return redirect('all-tickets') else: messages.warning(request,'Somthing went wrong.') return redirect('create-ticket') else: form = CreateTicketForm() context = { 'form': form … -
How to render a template after a form submit?
I have a django view where i upload a CSV file in a form. In my view i have some validations like check if the file is a CSV: class SabanaFileUploadView(CreateView): http_method_names = ['get', 'post'] form_class = UploadSabanaFileForm template_name = 'reasignacion/sabana_file_upload.jade' enabled_upload = False success_url = reverse_lazy('sabana') def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class}) def get_success_url(self): return reverse_lazy('sabana') def post(self, request, *args, **kwargs): form = UploadSabanaFileForm(request.POST, request.FILES) if form.is_valid(): file = form.cleaned_data['file'] start_date = form.cleaned_data['start_date'] sabana = self.get_sabana(start_date) file_error = False // list instrucciones a validar // list unidad medida a validar // list motivos // list inicio periodo // list unidad a validar self.validate_bloqueo(request, sabana, form) try: csv_data = file.read().decode('utf-8') except: file_error = True form.add_error('file', 'El archivo debe ser CSV UTF-8') file_error, error_messages = validate_csv_data(csv_data, instrucciones_a_validar, unidad_medida_a_validar, listado_motivos, listado_inicio_periodo, central_unidad_a_validar) if file_error: for error_message in error_messages: print(error_message) form.add_error("file",error_message) else: print("CSV data is valid.") if not file_error and self.enabled_upload is True and sabana: registros_sabanas = load_tmp_registros_sabanas(sabana, csv_data) context = {'registros_sabanas': registros_sabanas} for registro in registros_sabanas: registro_model = RegistrosSabana( // vars // ... // ... ) registro_model.save() return render(request, 'reasignacion/sabana_list_masivo.jade', context) return render(request, self.template_name, {'form': form}) validating extension When the file pass every validation it loads a temporary … -
More than one initial migration file in a django project
In my project, to recreate the migrations, I removed all the migration files, leaving only the "initial.py" intact. Following that, I dropped my PostgreSQL database and executed the "makemigrations" command. In some of the applications, it generated more than one migration file, such as "0001_initial.py" and "0002_initial.py." Is this behavior considered normal? -
ImportError: cannot import name 'AdminConfig' from 'django.contrib.admin'
Why am I getting this error I am inside an app named reviews/adminconfig.py but when I run the server I get the following error: ImportError: cannot import name 'AdminConfig' from 'django.contrib.admin' (C:\Users\PERSONAL\AppData\Roaming\Python\Python310\site-packages\django\contrib\admin_init_.py) here is the code from django.contrib.admin.apps import AdminConfig class ReviewsAdminConfig(AdminConfig): default_site = 'admin.BookrAdminSite' I have already update the setting.py file notice: INSTALLED_APPS = [ 'reviews.adminconfig.ReviewsAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'reviews', ] -
Feed 100s of markdown pages into waagtail cms programmatically
I have some 1000+ page data as a markdown scrapped from a huge site. I am planning on creating a wagtail page model that has a title and a markdown. I want to feed all these scrapped page data into wagtail cms. One way I thought of doing is through admin commands. Any suggestions on how to proceed with this? -
Django Amazon RDS Tunnel Connection with Key File
When I run manage.py, I get this error. Any idea what I did wrong? django.db.utils.OperationalError: connection to server at "myserver.amazonaws.com" (XXX.XXX.XXX.22), port 56133 failed: Operation timed out Settings.py: import paramiko private_key_path = '../Mykeyfile.pem' tunnel_config = { 'ssh_address_or_host': ('XXX.XXX.XXX.XXX', 22), 'ssh_username': 'myusername', 'ssh_pkey': paramiko.RSAKey.from_private_key_file(private_key_path), 'remote_bind_address': ('myserver.amazonaws.com', 5432), } with SSHTunnelForwarder(**tunnel_config) as tunnel: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'myusername', 'PASSWORD': 'mypassword', 'HOST': 'myserver.amazonaws.com', 'PORT': tunnel.local_bind_port } } I've tried localhost and 127.0.0.1 for the addresses. I can connect easily with my datagrip with the same pam file and configuration. When I step debug, I can see pam file too. -
Order by one of two fields
I have a model that has two character fields, one or both of which may be populated. I'd like to called QuerySet.order_by something like: qs.alias(name=lambda x: if x.field1 then x.field1 else x.field2).order_by('name') That is, for each row, take the value that you're ordering by from field1 if it's defined, and from field2 if it's not. Is there any way to accomplish this with a Django queryset? -
Select * for reverse lookup
I've have three models in Django. class Product(models.Model): name = mdoels.CharField() class ProductCharateristics(models.Model): name = models.CharField() description = models.TextField() class ProductCharacteristicValues(models.Model): product_characteristic = models.ForeignKey(ProductCharacteristics) value = models.IntegerField() prduct = models.ForeignKey(Product) The list of characteristics may change, it's the same for all products and each characteristics can have multiple value. I'd like to replicate with django ORM the following SQL statement: select * from ProductCharateristics as pc left join ProductCharacteristicValues as pcv on pc.id = pcv.product_characteristics where pcv.product = 1 This query retrieves all rows and all columns from both tables. -
Django migration/model created a foreign key field that is not model_id but instead modelID?
I am trying to figure out why I get an error in my app: ProgrammingError at /admin/auth/user/ column programscheduler_proposal.program_id does not exist LINE 1: SELECT "programscheduler_proposal"."id", "programscheduler_p... ^ HINT: Perhaps you meant to reference the column "programscheduler_proposal.programID". Model: class Program(models.Model): programName = models.CharField(max_length=100) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) #should act as blackout constraints class ProposalConstraint(models.Model): objects = models.Manager() proposal = models.ForeignKey("Proposal", on_delete=models.PROTECT) date_time_constraint = models.DateTimeField() note = models.CharField(max_length=200) isPersonal = models.BooleanField(default=False) class Proposal(models.Model): objects = models.Manager() program = models.ForeignKey("Program", on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) title = models.CharField(max_length=100) #scheduler = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) scheduler = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_scheduler_related', on_delete=models.CASCADE) pi = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_pi_related', on_delete=models.PROTECT) #observers recahback to proposal observer. untrained_observer_list = models.CharField(max_length=200) #just seperate via commas collaborators = models.CharField(max_length=200) #just seperate via commas contact_information = models.CharField(max_length=200) #might break this out to a complete address? #instrument = models.ForeignKey("Instrument", on_delete=models.PROTECT) instrument = models.ManyToManyField("Instrument") #each program can have many instruments. primary_dis_grating = models.CharField(max_length=20) #is this going to be replaced by FILTER DB? or based on instrument? independent from instrument? secondary_dis_grating = models.CharField(max_length=20, null=True, blank=True) slits = models.CharField(max_length=150) #is this based on instrument? independent of instrument? several options per instrument? filters = models.CharField(max_length=150) #same as above targetofop = models.CharField(max_length =200, null=True, blank=True) #can be blank location = models.CharField(max_length=20) … -
Deleting django form field help_text after errors are shown
I'm trying to delete the password help texts once a form is being re-rendered with errors. For some reason, it keeps recreating the help_text before the form is rendered. from allauth.account.forms import SignupForm, SetPasswordForm # Helper function used to switch the password help texts # So that it appears under the second password instead of the first def switchHelpTexts(form): ### This works ### help_text = form.fields["password1"].help_text form.fields["password1"].help_text = None form.fields["password2"].help_text = help_text ### This works ### # Helper function used to delete the password help texts # when validation errors are displayed. We don't need the same info twice def deleteHelpTexts(form): ### This doesn't work ### form.fields["password1"].help_text = None form.fields["password2"].help_text = None ### This doesn't work ### class MyCustomSignupForm(SignupForm): field_order = ["username", "email", "password1", "password2"] def __init__(self, *args, **kwargs): super(MyCustomSignupForm, self).__init__(*args, **kwargs) switchHelpTexts(self) # # Commented out because deleteHelpTexts doesn't work for some reason # if self.errors and (self.errors.keys() & {"password1", "password2"}): # deleteHelpTexts(self) Even more surprising, if I do this: def deleteHelpTexts(form): form.fields["password1"].help_text = None form.fields["password2"].help_text = "Hello" print(form.fields["password2"].help_text) the console prints "Hello" like it's supposed to, but the form still re-renders with the original helptext instead of "Hello" -
Authenticate returns null always
when i authenticate it returns null and so i cant login even when i have username and password in my database from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate, login ,logout from .models import Signups from .forms import SignForm from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import get_object_or_404 from django.http import HttpResponse # Create your views here. def loginpage(request): a=Signups.objects.all() form1 = AuthenticationForm() if request.method == 'POST': form1 = AuthenticationForm(data=request.POST) username = request.POST.get('username') password = request.POST.get('password') print(username,password) user = authenticate(request,username=username, password=password) if user is not None: login(request,user) return redirect('signed', pk=user.pk) else: return HttpResponse("username or password is incorrect") return render(request, 'database/loginpage.html', {'form1': form1}) def frontpage(request): return render(request,'database/frontpage.html') def signup(request): form=SignForm() if request.method=='POST': form = SignForm(request.POST) if form.is_valid(): user=form.save() return redirect("signed",pk=user.pk) return render(request,'database/signup.html',{'form':form}) def signed(request,pk): sign=Signups.objects.get(id=pk) return render(request,'database/signed.html',{'sign':sign}) this is my views.py i want to go to a page where it shows username and password and i have written the code for that and it works but the login form is not taking me there. -
Wagtail 4 Upgrade: 'BlockWidget' object has no attribute '_block_json'
After reading through and updating possible breaking changes stated in the Wagtail changelog, I am getting the following error when viewing any edit menu for any page: 'BlockWidget' object has no attribute '_block_json' Request Method: GET Request URL: https://example.com/admin/pages/530/edit/ Django Version: 3.2.9 Exception Type: AttributeError Exception Value: 'BlockWidget' object has no attribute '_block_json' Exception Location: /home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages/wagtail/blocks/base.py, line 526, in block_json Python Executable: /home/user/.virtualenvs_dev/mysite/bin/python3.10 Python Version: 3.10.9 Python Path: ['/home/user/projects/mysite/django', '/home/user/.virtualenvs_dev/mysite/bin', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages', '/home/user/projects/mysite/django/mysite'] Server time: Tue, 17 Oct 2023 11:02:12 -0500 Error during template rendering In template /home/user/.virtualenvs_dev/mysite/lib/python3.10/site-packages/wagtail/admin/templates/wagtailadmin/panels/object_list.html, error at line 9 'BlockWidget' object has no attribute '_block_json' 1 {% load wagtailadmin_tags %} 2 3 <div class="w-form-width"> 4 {% if self.help_text %} 5 {% help_block status="info" %}{{ self.help_text }}{% endhelp_block %} 6 {% endif %} 7 {% for child, identifier in self.visible_children_with_identifiers %} 8 {% panel id_prefix=self.prefix id=identifier classname=child.classes|join:' ' heading=child.heading heading_size="label" icon=child.icon id_for_label=child.id_for_label is_required=child.is_required %} 9 {% component child %} 10 {% endpanel %} 11 {% endfor %} 12 </div> 13 I've used python poetry in attempt to have all libraries compatible. It builds just fine and the site runs. It is just this specific portion of the site that has to do with the actual Wagtail … -
django orm filter doesn't find the result but I know the result exists
I have a mySql database in server and it has about 5000 rows of data in one table. my model is like this: class Names(models.Model): title = models.CharField(max_length=100) descriptions = models.CharField(max_length=500) is_approved = models.BooleanField(default=False) count_stars = models.FloatField(default=0.0) count_visited = models.FloatField(default=0.0) count_shared = models.FloatField(default=0.0) gender = models.ForeignKey(Genders, on_delete=models.CASCADE) root = models.ForeignKey(Roots, on_delete=models.CASCADE) def __str__(self) -> str: return self.title my mission is to find a specific row in the database by the field of 'title', when the title is in the first tens of rows in the database, everything works good but when the title is in the deeper rows, it can not find it. my view function is: @api_view(["Get"]) def get_name_by_name(request, keyName): value = models.Names.objects.filter(title=keyName).first() serializedValue = serializers.nameSerializer(value) result = serializedValue.data return Response(result) database rows: 1- found 2- found . . n- not found . . 5000. not found what is the problem? I searched about async programming but it didn't work