Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-waffle does not show proper flag status on waffle_status endpoint
I have created this flag: I'm trying to get the flag status using the waffle_status endpoint, but no matter if the user is logged or not I get the same response: { "flags": { "test_flag": { "is_active": false, "last_modified": "2023-12-21T16:03:38.922Z" } }, "switches": {}, "samples": {} } It is supposed that I have to get this flag as True for the user farid, the one with id 1, isn't? I made this exercise using django 4, django-waffle 4.1.0, and I have made this configs on settings.py . . . INSTALLED_APPS = [ 'django.contrib.admin', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.auth', 'waffle', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'exammple' ] . . . MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'waffle.middleware.WaffleMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] . . . REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } . . . and in project's url.py file urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path( 'api/v1/', include( [ path('', include(example_urls)) ] ) ), path('waffle/', include('waffle.urls')), ] Is this a bug/missing feature on waffle? or I'm missing some config in somewhere? P.S. The purpose of this is that I have to give this flag status to a FrontEnd app to show or hide some visual components depending … -
Django - Filter by Foreign Key
I have 2 models class Project(models.Model): name = models.TextField(max_length=150) class Asset(models.Model): name = models.TextField(max_length=150) project = models.ForeignKey('Project', related_name='ass') I can use this command to get a Project with all its Assets, it's cool. proj = Project.objects.get(pk='QQ') But I just want to get a Project with a specific Asset, this is my command: proj = Project.objects.get(pk='QQ', ass__pk=50) But it still returns all Assets. Then I turn on the SQL debug mode and find Django runs 2 SQLs. It executes 'SELECT project.* FROM project INNER JOIN asset ON ... WHERE project.pk='QQ' AND asset.pk=50 It executes 'SELECT asset.* FROM asset WHERE asset.project = 'QQ' I think the 1st SQL is enough, I have no idea why 2nd SQL is executed. I use Django 4.2 with Python 3.8.10, can anybody help it? -
Django not responding when i change DataBase to PostgreSQL
i changed the Django database to postgresql and when i command runserver or migrate or makemigrations, django wont response. also no error occurs im using Django 5 and PostgreSQL 10 i tried restarting the postgres server and making new projects but still stays that way -
Django Rest Framework Token Auth > Remove user foreign Key from POSTs while keeping it for GETs
I'm struggling to make this work. I have the following model: class Message(models.Model): text = models.CharField(max_length=500) date = models.DateTimeField("date published") user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return self.text Here is my serializer: class MessageSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Message fields = ['id', 'text', 'date', 'user', 'room'] I've changed the serializer to have the user "expanded" when I retrieve my Message list with a GET request. So what I hoping to achieve - with my token authentication - is to avoid passing the user in my POST request. As I pass the token for authentication, there should be a way to retrieve the user with it. Here are my ViewSets: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class MessageViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer def get_queryset(self): authentication_classes = [] room_id = self.request.query_params.get('room_id') return Message.objects.filter(room=room_id) My settings: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } How can I do this? Thanks! -
Python - Django Beginner - Form to submit data to my database - Cannot find answer
I am quite new to Python - Django and I have only spent my spare time learning. I have successfully created a user registration form that posts data to my postgresql database: My code looks like this: Views: def signupr(request): if request.method == 'POST': username = request.POST\['username'\] email = request.POST\['email'\] password = request.POST\['password'\] password2 = request.POST\['password2'\] if password == password2: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Already Exists') return redirect('registration') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Already Exists') return redirect('registration') else: user = User.objects.create_user(username=username, email=email, password=password) user.save(); return redirect('dashboard') else: messages.info(request, 'Passwords Do Not Match') return redirect('registration') else: return render(request, 'registration_form.html') (very basic but it works) I have a form that successfully creates users to a database. Note that Django understands "User.objects.create_user" and creates a new user row for me. The problem comes in when I try to use the same logic to create a property listing for example I have a basic version of my model called "Properties" : ` class Properties(models.Model): title = models.CharField(max_length=100, default='Not Set') feat_image = models.ImageField(upload_to='images', default='/images/scrolltop.png') gallery_images = models.ImageField(upload_to='images', default=False) external_property_listing_url = models.CharField(max_length=255) property_rules = models.CharField(max_length=500) ` Now when I try to create this in my views: def addpropertylisting(request): if request.method == 'POST': title = request.POST['title'] property = … -
Svelte menu with Django rest framework
The menu I made in django works correctly in html. But I want to implement the same code in svelte using django rest. How should I do this using django rest? Of course, I prepared django rest, I just want it to work properly in svelte. This is my code: HTML DJANGO {% load static %} <nav class="menu__main menu__vtl"> <ul class="menu"> {% for html_category in html_categories %} {% if not html_category.parent %} <li class="dropdown"> <a href="javascript:void(0);" class="dropdown__link{% if request.path == html_category.get_absolute_url %} active{% endif %}"> {% if html_category.select_svg.title_svg %} <svg class="dropdown__image"><use href="#{{ html_category.select_svg.title_svg }}"></use></svg> {% endif %} <span class="dropdown__text">{{ html_category.title }}</span> <svg class="dropdown__arrow"><use href="#arrow-down"></use></svg> </a> {% if html_category.subs.all %} <ul class="dropdown__list"> {% for html_category in html_category.subs.all %} {% if html_category.subs.all %} <li class="sub"> <a href="javascript:void(0);" class="sub__link"> <svg class="sub__arrow"><use href="#arrow-add"></use></svg> <span class="sub__text">{{ html_category.title }}</span> </a> <ul class="sub__list"> {% for child in html_category.subs.all %} <li class="sub__list__item"> <a href="{{ child.get_absolute_url }}" class="sub__list__link{% if request.path == child.get_absolute_url %} active{% endif %}"> <span class="sub__list__text">{{ child.title }}</span> </a> </li> {% endfor %} </ul> </li> {% else %} <li class="dropdown__list__item"> <a href="{{ html_category.get_absolute_url }}" class="dropdown__list__link{% if request.path == html_category.get_absolute_url %} active{% endif %}"> {% if html_category.select_svg.title_svg %} <svg class="dropdown__image"><use href="#{{ html_category.select_svg.title_svg }}"></use></svg> {% endif %} <span class="dropdown__list__text">{{ … -
How to filter the choice list in Django Forms?
I have 2 models: class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) end_user_id = models.CharField(max_length=8, help_text=u"Please enter the end user id, like ABC1WZ1") email = models.EmailField(max_length = 254, help_text=u'with domain ...@boschrexroth.pl', blank=True) history = HistoricalRecords() def __str__(self): return self.name + ' ' + self.lastname def save(self, *args, **kwargs): self.end_user_id = self.end_user_id.upper() super().save(*args, **kwargs) and class BDO_Procedor(models.Model): id = models.AutoField(primary_key=True) bdo_procedor = models.ForeignKey(Employee, verbose_name='bdo_procedor', on_delete = models.DO_NOTHING) def __str__(self): return self.bdo_procedor.name + ' ' + self.bdo_procedor.lastname class BDO_ProcedorAdmin(SimpleHistoryAdmin): list_display = ('id', 'bdo_procedor') list_filter = ('bdo_procedor',) search_fields = ['bdo_procedor'] At the view.py I have an assign function which assign some form to the user which also exists at the BDO_Procedor def form_assign_bdo(request, pk): current_form = get_form(pk) if request.method == 'POST': form = AssignForm(request.POST, instance=current_form) form.fields["assigned_to"].queryset = Employee.objects.filter(end_user_id__in=BDO_Procedor.objects.values_list('bdo_procedor__end_user_id', flat=True)) if form.is_valid(): form.save(commit=True) return redirect('material_request', pk=pk) else: form = AssignForm(request.POST, instance=current_form) return render(request, 'app/forms/form_assign.html', {'form':form}) Everything working but I want to filter this list also in form, so: class AssignForm(ModelForm): def __init__(self, request, *args, **kwargs): super(AssignForm, self).__init__(*args, **kwargs) self.fields["assigned_to"].queryset = Employee.objects.filter(end_user_id__in=BDO_Procedor.objects.values_list('bdo_procedor__end_user_id', flat=True)) class Meta: model = MissFormModel fields = ( 'assigned_to', ) Everything is looking good, but when I've cliked Submit nothing is going on. What I am dooing … -
How can I do mocked reverse_lazy from django.urls?
# views.py from django.contrib.auth import get_user_model from django.urls import reverse_lazy from django.views import generic from accounts import forms User = get_user_model() class UserRegisterView(generic.FormView): model = User template_name = 'accounts/register_form.html' form_class = forms.UserRegisterForm success_url = reverse_lazy('accounts:user-register-first-success') def form_valid(self, form): form.save() return super().form_valid(form) # test_views.py from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse User = get_user_model() class UserRegisterViewTest(TestCase): def setUp(self) -> None: self.url = reverse('accounts:user-register') self.data = { 'email': 'rick.sanchez@test.com', 'password': 'qwe123!@#', 'confirmed_password': 'qwe123!@#', } @patch('accounts.views.reverse_lazy', return_value='mock_url') def test_view_redirects_to_correct_page_POST(self, mock): response = self.client.post(self.url, self.data) self.assertRedirects(response, 'mock_url') @patch('django.urls.reverse_lazy', return_value='mock_url') def test_view_redirects_to_correct_page_POST_(self, mock): response = self.client.post(self.url, self.data) self.assertRedirects(response, 'mock_url') File "/home/branya/Документи/My Projects/Django/hotel/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 848, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'user-register-first-success' not found. 'user-register-first-success' is not a valid view function or pattern name. I don't understand why mock isn't work on reverse_lazy. I need it work without the made view with the url by name "user-register-first-success". Help me to find a solution. I used @patch('accounts.views.reverse_lazy', return_value='mock_url') and @patch('django.urls.reverse_lazy', return_value='mock_url'). I try to find a solution with chatGPT, but its answers raised that error. -
Django Razorpay integration working on test server but This payment has already been captured error in live session
I'm first time to use razorpay live mode, transaction is sucessful but get error Payment has already been captured.The payment collection works fine but when it comes to verifying the payment it seems to break on the live server. The order amount and details sent to razorpay seem to be working fine but response capture is maybe breaking. Below is my copy of views.py def process_booking_payment(self, request, *args, **kwargs): if request.method == "POST": params = request.POST razorpay_order_id = params.get('razorpay_order_id') razorpay_payment_id = params.get('razorpay_payment_id') razor_signature = params.get('razorpay_signature') MD = MasterData.objects.get() RAZORPAY_CLIENT = razorpay.Client(auth=(MD.razorpay_key, MD.razorpay_secret)) RAZORPAY_CLIENT.set_app_details({"title": MD.company_name, "version": "1.0"}) params_dict={ 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': razorpay_payment_id, 'razorpay_signature': razor_signature } bookin = get_object_or_404(Booking,payment_id = kwargs.get('payment_id'), razorpay_order_id=razorpay_order_id) bookin.razorpay_payment_id = razorpay_payment_id bookin.razorpay_signature = razor_signature bookin.save() RAZORPAY_CLIENT.utility.verify_payment_signature(params_dict) try: with transaction.atomic(): rp_capture = RAZORPAY_CLIENT.payment.capture( razorpay_payment_id,float(bookin.booked_amount * 100) ) bookin.payment_status = '1' confirm = create_booking(request,payment_id = bookin.payment_id) if 'errorDetails' in confirm: bookin.booking_status = '6' else: bookin.booking_status = '2' bookin.booking_details.is_confirmed = True bookin.booking_details.save() bookin.save() messages.success(request, 'Payment Successful') log = LOG.objects.create( user = request.user, function = 'payment', response = 'payment success' ) log.save() return JsonResponse({ 'success': True, 'redirect_to': reverse('my-booking',args=[request.user.slug]) }) except Exception as e: bookin.booking_status = '6' bookin.payment_status = '2' bookin.save() print(e) log = LOG.objects.create( user = request.user, function = 'payment', response = … -
django.template.library.InvalidTemplateLibrary
im tried to install django-jalali-date module on Django5.0 . But I encountered the following error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'jalali_date.templatetags.jalali_tags': No module named 'distutils' i am tried install this module for convert Gregorian calendar to solar calendar. I installed it with pip install django-jalali-date and put it in the installed apps -
Please explain me this. I cant understand it
A common gotcha to be aware of is that the field type dictates how to use these values. Whenever you have a string-based field like CharField or TextField, setting both null and blank as we’ve done will result in two possible values for “no data” in the database. Which is a bad idea. The Django convention is instead to use the empty string "", not NULL I cant understand what will go wrong for charfiel and textfield? -
upload image and encode face with opencv and face_recognition
I want to take the photo file selected in the form using opencv and encode the face using face_recognition in Django before my information is saved in the database. But I can't get the photo file from cleaned data. please Help me my views.py from django.shortcuts import render, redirect from django.views import View from .models import ImageEncode from .forms import CreateEncodeImage from django.contrib import messages import cv2, os import face_recognition from django.conf import settings class AddCustomFaceView(View): form_class = CreateEncodeImage path = os.path.join(settings.BASE_DIR, 'face_lib/') def get(self, request, *args, **kwargs): form = self.form_class return render(request, 'home/custom-face.html', {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): new_face = form.save(commit=False) img_name = form.cleaned_data['imgname'] img_add = form.cleaned_data['imgaddress'] img_face = cv2.imread(f'{img_add}') img_face = cv2.cvtColor(img_face, cv2.COLOR_RGB2BGR) face_loc = face_recognition.face_locations(img_face) y1, x2, y2, x1 = face_loc y1, x2, y2, x1 = y1, x2, y2, x1 image_frame = img_face[y1:y2, x1:x2] encode = face_recognition.face_encodings(img_face) if encode: new_face.imgencode = encode[0] new_face.imgname = img_name new_face.imgaddress = form.cleaned_data('imgaddress') new_face.save() cv2.imwrite(self.path + img_name, image_frame) messages.success(request, 'New Custom Face Saved', 'success') else: messages.warning(request, 'could not save this face', 'success') return redirect('home:face_custom') return redirect('home:list_img') else: messages.warning(request, 'not valid data', 'warning') return redirect('home:face_custom') my forms.py from django import forms from .models import ImageEncode … -
django.core.exceptions.AppRegistryNotReady and import models
My django project structure is like below. watcher |-config |-__init__.py |- asgi.py |- config.ini |- settings.py |- urls.py |- wsgi.py |-tower |-__init__.py |-admin.py |-apps.py |-models.py |-tests.py |-views.py |-manage.py My apps.py code is like below. # import os # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "watcher.settings") # import django # django.setup() from .models import CryptoTicker, CryptoTrade, CryptoOrderbookMain, CryptoOrderbookSub class TowerConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'tower' def ready(self): print("Hello") socket = SocketClient() socket.start() class SocketClient(threading.Thread): def __init__(self): super().__init__() self.url = "wss://api.upbit.com/websocket/v1" self.ws = websocket.WebSocketApp( url=self.url, header=headers, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open ) self.step = 0 def run(self): while True: self.ws.run_forever() def on_message(self, ws, message): data = message.decode('utf-8') self.process(data) if self.step < 0: print("----- ----- ----- ----- ----- ----- -----") print() print(data) print() print("----- ----- ----- ----- ----- ----- -----") self.step += 1 def on_error(self, ws, err): print(err) def on_close(self, ws, status_code, msg): print("closed!") def on_open(self, ws): print("connected!") ws.send('[{"ticket":"siren1"}, {"type":"ticker","codes":["KRW-BTC", "KRW-SOL"]}, {"type":"trade","codes":["KRW-BTC", "KRW-SOL"]}, {"type":"orderbook","codes":["KRW-BTC", "KRW-SOL"]}, {"format": "DEFAULT"}]') def process(self, data): pass After running 'python manage.py runserver --noreload 0.0.0.0:8000', I got below errors. File "D:\git\crypto-siren\venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. My suspicion is that importing models make errors. (from .models import CryptoTicker, CryptoTrade, CryptoOrderbookMain, CryptoOrderbookSub) Could you give me some … -
DRF Serializer field's queryset not updating
I have a Django models: class Author(Model): name = CharField(max_length=256) class Library(Model): address = CharField(max_length=256) books = ManyToManyField(Book) class Book(Model): name = CharField(max_length=256) created_by = ForeignKey(Author, on_delete=CASCADE) I want Author to create new Libraries with Books by sending array with IDs, but limit book choices to only the ones created by author making request. I want this serializer to reject all books if author is not given. I have a serializer: class LibrarySerializer(ModelSerializer): books = PrimaryKeyRelatedField(many=True, queryset=Book.objects.none()) class Meta: model = Library fields = ("books", "address") def __init__(self, *args, **kwargs) self.author = kwargs.pop("author", None) super().__init__(*args, **kwargs) if self.author: self.fields["books"].queryset = Book.objects.filter(created_by=self.author) Now I run: author = Author(name="John") author.save() book = Book(created_by=author, name="book_one") book.save() serializer = LibrarySerializer(data={"books": [book.id], "address": "address_one"}, author=author) But when I validate the serializer by calling serializer.is_valid() there is an errors saying that given book does not exist. Do you know why it is rejected or how can I investigate that? -
while i am trying to access the files from postman and find patterns accordingly i am not getting the file from the pdf_file field
can anyone tell me how to get the file and extract data from it from postman class ReadPDFView(APIView): def post(self, request): data = request.data.get('pdf_file') # Assuming you want to extract text from the first page with pdfplumber.open(data) as pdfs : first_page_text=pdfs.pages[0] first_page_text= extract_text(pdfs) print(first_page_text) return Response(first_page_text) i tried this to get the result -
Is there a way to bind with DN using django-python3-ldap
Because there are some AD migrations coming up in our organization, I want to find the user using a specific field and binding with the corresponding DN rather than the sAMAccountName or userPrincipalName in our Django environment. When reading the django-python3-ldap docs I couldn't find if the package supports this. Is this true? Should I try to use another package that does supports this? -
condition for the uniqueness of the input data
I need names and surnames of the employees to not match. and so that an error occurs after trying to save changes if the same person is specified 2 times. What's wrong? class JrtnPerson(models.Model): rtn = models.ForeignKey(Drtn, verbose_name='Подразделение Ростехнадзора', on_delete=models.CASCADE) name = models.CharField(max_length=200, verbose_name='Имя и Отчество') surname = models.CharField(max_length=200, verbose_name='Фамилия') tel_mob = PhoneNumberField(verbose_name="Номер телефона мобильный", blank=True, null=True) tel_rab = PhoneNumberField(verbose_name="Номер телефона рабочий", blank=True, null=True) email = models.EmailField(max_length=100, verbose_name="Электронная почта", blank=True, null=True) # def str(self): # return '%s %s' % (self.surname, self.name) def save(self, *args, **kwargs): if not self.JrtnPerson.objects.filter(surname=self.surname, name=self.name).exists(): super(surname,name,self).save(*args, **kwargs) -
CSRF Missing Error in DRF + React + SimpleJWT
I have my backend deployed at http://11.11.11.11/api/ for APIs devloped with DRF. Django Admin panel is running at http://11.11.11.11/admin/ and my react frontend is running at http://11.11.11.11/. I am using SimpleJWT for the Authentication. When I login to the react frontend without logging out from the django admin panel It gives me the error CSRF token is missing (Error 403). However If i logout from the admin panel (which deletes the sessionID saved in cookies) I am able to login from my react frontend and here I am not sending any CSRF token or anything. Why this is happening? Why cant I login simultaneously in frontend and the backend? I tried creating an endpoint where frontend can get the CSRF token and pass it to the login api in X-CSRFToken header in order to get the access token and refresh token.. I didnt work. -
What can I do to optimize speed?
There are 5400 rows of data in the database and it takes too long to calculate them. In order to increase the calculation speed, I saved all possible combinations according to the filters in the database and I want to calculate on them. This function I wrote does not work fast enough and responds very late. I give random numbers with the random library but there will be real calculations. Example: score and history How can I make this calculation faster? Django==1.11 Python==3.5 from random import randint def ees_calculate(request): if request.user.is_superuser: if request.is_ajax() and request.method == 'POST': survey=request.POST['survey'] language=request.POST['language'] organization=request.POST['organization'] year=request.POST['year'] answer=request.POST['answer'] table=request.POST['table'] filters = { 'organization_filter': organization, 'survey_filter': survey, 'language_filter': language, 'year_filter': year, 'answer_filter': answer, 'table_filter': table } ees_combinations = models.Combination.objects.filter(**filters).values('id', 'demographic', 'gender', 'division', 'tenure', 'career_type_level') for combination in ees_combinations: dev0 = 0 avg_history = 0 answer_count = 0 answer_history_count = 0 combination_filter = { 'age_group': combination['demographic'], 'gender': combination['gender'], 'division': combination['division'], 'tenure': combination['tenure'], 'career_type': combination['career_type_level'], 'organization_filter': organization, 'survey_filter': survey, } filtered_answers = models.Answer.objects.filter(year_filter=year, **combination_filter).values('score') filtered_answer_history = models.Answer.objects.filter(year_filter__lt=year, **combination_filter).values('score') answer_count = len(filtered_answers) answer_history_count = len(filtered_answer_history) if answer_count > 0: avg_score = int(sum(answer['score'] for answer in filtered_answers ) / answer_count) if answer_history_count > 0: avg_history = int(sum(answer['score'] for answer in filtered_answer_history … -
In Django I can't see the user registration form on the home page
I'm new to Django, i would like to display the register.html registration form on the home page (index.html) and NOT on http://127.0.0.1:8000/register or similar. On the home page I want to see the various input textboxes. What am I doing wrong? How can I solve it? In the index.html page I don't use anything to call the form (register.html). Maybe I'm doing this wrong? App1/templates/registrazione/register.html {% extends "index.html" %} {% block content %} <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form.as_p }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> {% endblock %} App1/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user App1/urls.py from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index'), App1/views.py from .forms import NewUserForm from django.contrib import messages from django.contrib.auth.decorators import login_required def index(request): """View function for home page of site.""" return render(request, 'index.html') def register_request(request): if request.method == "POST": form = … -
Same records being added on unique constraints
I have added a unique together (badge_id, speech_id, badge_type) however I can still add data with same information, Attaching my schema as well I can explain one thing. unique constrain was applied and those column relation was DO_NOTHING and then in next migrations I updated it to CASCADE not sure if that is causing this misleading behavior of adding same rows. I double check if my django migrations were successful by extracting schema info from mysql, attached image. -
Django CORS cannot set cookie in HTTP
Premise I wanna use Django sessionid feature to identify which user was sending request. Therefore I need the user to login first and expect the user will bring the sessionid in their request header cookie then. What's wrong now login/ response header shows: This attempt to set a cookie via a Set-Cookie header was blocked because it had the "Secure" attribute but was not received over a secure connection. I'd like to find a way NOT to use https since it's just not quite a big project so I don't want to make too much effort on configuring https environments. Not sure if I set CORS or use sessionid feature correctly either. Related environment and codes I have a Django backend server in my local network Django 4.2.7 django-cors-headers 4.3.0 ip: http://192.168.10.200:8000 and my frontend dev environment (vue2.x) is on my own laptop ip: http://192.168.10.101:8888 my setting.py is like below # settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_SECURE = False SECURE_SSL_REDIRECT = False SESSION_COOKIE_HTTPONLY = True CORS_ALLOWED_ORIGINS = ["http://localhost", "http://127.0.0.1", "http://192.168.10.101"] views.py this … -
Challenges with Celery: Managing Long-Running Tasks and Communication Loss in Solo Mode
Good day to all. I've encountered an intriguing issue. I've developed a microservice using Celery that communicates with the main application through REDIS, where the main application also uses Celery. The problem is that I had to run the microservice worker in solo mode because certain functionalities don't operate properly in the regular mode (it's quite complex to explain what and why). Due to the solo mode and the extended task execution time, there is a loss of communication between the workers, causing tasks to re-enter the queue. This occurs because Celery assumes something has gone wrong when the worker doesn't respond for an extended period (tasks take up to 5 hours to complete). Increasing the task execution waiting time isn't feasible, as tasks re-enter the queue due to connection disruption. To avoid tasks re-entering the queue, the heartbeat was disabled. Despite my efforts, tasks still repetitively re-enter the queue even if the process is ongoing My Settings: app.conf.broker_connection_timeout = 10 app.conf.broker_connection_retry = 10 app.conf.result_extended = True app.conf.task_acks_late = True app.conf.task_track_started = True app.conf.task_publish_retry = False app.conf.broker_transport_options = {"visibility_timeout": 86400} app.conf.worker_max_memory_per_child = 10000 app.autodiscover_tasks() The following solutions to the problem were tried, but they did not help Running the microservice … -
crispy form height does not change
I have this problem with my {{ form|crispy }} it works just fine for one of my view but for the other one the fields are too thin and whatever I so the width does change but the height which I want to increase does not what should I do? if I need to post another part of code please let me know it looks like this Thanks in advance views.py from django.forms.models import BaseModelForm from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .forms import PostForm from .models import post from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from users.models import Profile from django.views.generic import UpdateView from django.views import View from django.contrib.auth import get_user_model @login_required() def new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.instance.author = request.user form.save() messages.success(request, f'Post created!') return redirect("/") else: form = PostForm() return render(request, "posts/new.html", {"form": form }) class PostUpdateView(LoginRequiredMixin, UpdateView): model = post fields = ['title','body'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) forms.py from django import forms from django.forms import ModelForm, Textarea from .models import post class PostForm(ModelForm): class Meta: model = post fields = '__all__' exclude = ('author',) widgets = { … -
How to check the details are correct or not without rendering the page in django?
I have created a registration form using django framework and in the phone number content how can I check the number is only equal to 10 digits without rendering the page, because when i render the page if the phone number condition is wrong whole input's will be deleted and return the page how can i handle that without deleting the data?? i have explained as above