Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve possibly conflicting urls in webpage rendering
When I try to load a page, I get another page instead... I try to load a page called wikiPage as shown in my urls description that follows, but I get another url patterns linking to a view called newPageb instead, though the two urls have same parameters and the one that is first in order gets called, But how do I make them distinct where I can call them irrespective of order. Here is my urls.py... app_name= "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("randomPage", views.randomPage, name="randomPage"), path("<str:pagetitle>", views.newPageb, name="newPageb"), path("<str:pagetitle>", views.wikiPage, name="wikiPage"), path("<str:z>", views.wikiPage, name="wikiPage"), path("newPage", views.newPage, name="newPage"), path("<str:pageSearch>", views.search, name="search"), path("", views.search, name="search") Here are the conflicting views.. def newPageb(request, pagetitle) ... ... def wikiPage(request, pagetitle): ... ... and here is the template where the pagetitle parameter was declared {% extends "encyclopedia/layout.html" %} " {% block title %} Encyclopedia {% endblock %} {% block body %} <h1> {{title}} </h1> <ul> {% for pagetitle in entries %} <li> <a href="{% url 'encyclopedia:wikiPage' pagetitle=pagetitle%}"> {{ pagetitle }} </a> </li> {{entrie|safe}} {% endfor %} </ul> {% endblock %} -
I'm trying to create vendor user API that has one-to-one relationship with the user it throws integrity error, pls help me
Integrity error in Django rest framework project. I am trying to register a vendor user, that has a one-to-one relationship with the user, but it throws an integrity error. The error code IntegrityError at /API/accounts/signup/vendor/ NOT NULL constraint failed: accounts_vendor.user_id Request Method: POST Request URL: ``http://127.0.0.1:8000/api/accounts/signup/vendor/ Django Version: 4.2.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: accounts_vendor.user_id Exception Location: C:\Users\Moses Ogiri\Desktop\medic-ecommerce\env\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: accounts. views.VendorSignupView Python Executable: C:\Users\Moses Ogiri\Desktop\medic-ecommerce\env\Scripts\python.exe Python Version: 3.12.0 model.py class User(AbstractBaseUser, PermissionsMixin): ADMIN = 1 VENDOR = 2 HEALTHCARE = 3 LOGISTIC = 4 CUSTOMER = 5 ROLE_CHOICES = ( (ADMIN, 'Admin'), (VENDOR, 'Vendor'), (HEALTHCARE, 'Healthcare'), (LOGISTIC, 'Logistic'), (CUSTOMER, 'Customer'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False, unique=True) first_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], null=False) last_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], null=False) email = models.EmailField(_('email address'), max_length=100, unique=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at= models.DateTimeField(auto_now=True) auth_provider = models.CharField(max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) objects = UserManager() REQUIRED_FIELDS = ["first_name", "last_name"] USERNAME_FIELD = 'email' ordering = ('-created_at ',) def __str__(self): return self.email @property def get_full_name(self): return f"{self.first_name.title()} {self.last_name.title()}" serializer.py class VendorSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=True) class Meta: model = Vendor fields = [ 'id', 'company_name', 'company_logo', 'company_files', 'company_email', … -
Has anyone seen this error before? ODBC Error code 0x68
My manager updated our test database data and ever since I've been getting this error ever since while trying to access our test system. We are currently making a python Django web application. Does anyone know why this would be happening? ('08S01', '[08S01] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x68 (104) (SQLExecDirectW)') -
CommandError: errors happened while running msguniq
C:\Users\Boss\OneDrive\İş masası\ask>django-admin makemessages --locale 'en' --ignore=myenv/* CommandError: errors happened while running msguniq msguniq: error while opening "C:\Users\Boss\OneDrive\Is masasi\ask\locale\django.pot" for reading: No such file or directory in main folder: locale en LC_MESSAGES settings.py LANGUAGES = ( ('az', _('Azerbaijan')), ('en', _('English')), ) LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGE_CODE = 'az' MODELTRANSLATION_DEFAULT_LANGUAGE = 'az' TIME_ZONE = 'Asia/Baku' SITE_ID = 1 USE_I18N = True USE_TZ = True and i use gettext 0.21 and iconv 1.16 - Binaries for Windows in ubuntu server i can makemessages but in windows i only get error django.pot" for reading: No such file or directory,msguniq: error while opening in django project i try to py manage.py makemessages -l en -
I have the next error Reverse for 'solicitud_detail' with keyword arguments
I am trying to see the details of my created requests but the url to enter the details is not recognized. I don't know what it could be. I will attach the views of my code. If you can help me, please. html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'nav.html' with active='new1' %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" /> <!-- DataTable.js --> <link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap5.min.css" /> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" /> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/index.css' %}" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css"> <br> <br> <div class="hstack gap-3"> <div class="p-2"><h3>Solicitudes </h3></div> <div class="p-2 ms-auto"></div> <div class="p-2"><a class="btn btn-primary btn-md" href="{% url 'crear_solicitud' %}">Crear OC</a> </div> </div> <br> <div class="container"> <table id="datatable-programmers" class="table table-hover"> <thead class="table table-primary"> <tr> <th>#</th> <th>Código</th> <th>Asunto</th> <th>Descripción</th> <th>Estado</th> <th>Plazo de Pago</th> <th></th> </tr> </thead> <tbody id="tableBody_programmers"> <!-- Los resultados se mostrarán aquí --> </tbody> <br> <br> </div> <!-- Bootstrap --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- DataTable.js --> <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.1/js/dataTables.bootstrap5.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <script > let dataTable; let dataTableIsInitialized = false; const dataTableOptions = { columnDefs: [ { className: "centered", targets: [0, 1, 2, 3, 4, 5, … -
Django Database query optimization on filter() same QuerySet and assigning to different variables
I have a base queryset and the goal is to build a dashboard statistic using the base queryset but filtered by different values for each variable. My simplified code for better understanding: class Transaction(models.Model): """ Invoice model. Represents a basic income/outcome transaction. """ user = models.ForeignKey(CustomUser, related_name="transactions", on_delete=models.CASCADE) title = models.CharField(max_length=32, verbose_name="Title") category = models.ForeignKey(Category, related_name="transactions", on_delete=models.CASCADE, null=True, blank=True) operation = models.CharField(max_length=8, choices=OPERATION_TYPE, verbose_name="operation") value = models.DecimalField(max_digits=14, decimal_places=2, verbose_name="value") date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Category(MPTTModel): """ Category model. Represents a category where money have been spent/earned.""" name = models.CharField(max_length=54, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='children') Having the models above I've created ClassBasedView(ListView) : class DashboardView(ListView): """ View implements dashboard functionality. """ model = Transaction template_name = "invoices/dashboard.html" ordering = "-date_created" def get_queryset(self) -> QuerySet[Any]: queryset = super().get_queryset() queryset = queryset.filter(user=self.request.user).select_related("category__parent") return queryset def get_context_data(self, **kwargs: Any) -> dict[str, Any]: data = super().get_context_data(**kwargs) # retrieving all transactons transactions_all = self.get_queryset() # retrieving incomes/expenses summary for current month incomes_this_month = transactions_all.filter(transaction_filter.transaction_date_filter(month="current"), operation="incomes") incomes_this_month_sum = incomes_this_month.aggregate(Sum("value")).get("value__sum") expenses_this_month = transactions_all.filter(transaction_filter.transaction_date_filter(month="current"), operation="expenses") expenses_this_month_sum = expenses_this_month.aggregate(Sum("value")).get("value__sum") # retrieving incomes/expenses summary for previous month transactions_prev_month = transactions_all.filter(transaction_filter.transaction_date_filter(month="previous")) incomes_previous_month = transactions_prev_month.filter(operation="incomes") incomes_previous_month_sum = incomes_previous_month.aggregate(Sum("value")).get("value__sum") expenses_previous_month = transactions_prev_month.filter(operation="expenses") expenses_previous_month_sum = expenses_previous_month.aggregate(Sum("value")).get("value__sum") You can see transaction_date_filter in … -
Django Sessions Login
in the following code section of my Django project, I have a function login_view. This function is supposed to log in a user. My question would be how I can use Django's sessions to start a separate session at each login: def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/login.html", { "message": "Invalid credentials" }) return render(request, "users/login.html") This is what i tried: def login_view(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: request.session['username'] = username request.session['password'] = password request.session['user'] = user login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/login.html", { "message": "Invalid credentials" }) return render(request, "users/login.html") -
Django - Is there a possibility to somehow combine multiple foreign keys into 1 field value from another model?
I want to create a model called DailyPerformance with following fields: class DailyPerformance(models.Model): date = models.DateField() driver = models.ForeignKey(Employee, on_delete=models.CASCADE) TYPE_OF_GOODS_CHOICES = ( ("Excavated soil", "Excavated soil"), ("Sand", "Sand"), ("Crushed stone", "Crushed stone"),... ) type_of_goods = models.CharField(blank=True, null=True, max_length=30, choices=TYPE_OF_GOODS_CHOICES) place_of_loading = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE) place_of_unloading = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE) number_of_rounds = models.IntegerField(blank=True, null=True) My biggest problem is with fields place_of_loading and place_of_unloading. Place of loading could be Construction site, Gravel pit, Sand pit, etc., while place of unloading could be Construction site or Landfill. Since I already have ConstructionSite model, I wanted to create models GravelPit, SandPit, Landfill and combine all of them in DailyPerformance model. This is the idea: Our drivers will need to fill the form at the end of working day, and I want for place_of_loading drop-down menu to have values from ConstructionSite, GravelPit and SandPit. The same goes for place_of_unloading. place_of_loading = models.ForeignKey(ConstructionSite, GravelPit, SandPit) place_of_unloading = models.ForeignKey(ConstructionSite, Landfill) I know this doesn't work, but wanted to know if there is any other solution. -
(Django 5.03] problem with django.contrib.auth.views.LogoutView
Today i am reviving an old django project. After creating all the needed things and importing the database, i could login and it worked (Or so i thought!) Everything works like it was when i abandoned the project a year or so ago, except the logout link in my header. I looked for people with similar problems and i found this: As per the Django 5.0 release notes, support for logging out via GET requests in the django.contrib.auth.views.LogoutView is removed. You must issue a POST in order to log out and be redirected. But that doesn't help me at all. I will show some of the code i use below: header.html <li class="nav-item "> <a class="nav-link " href="logout "> {{user.username.capitalize}} uitloggen</a> </li> views.py from django.contrib.auth.models import User, auth def logout(request): auth.logout(request) return redirect('/') urls.py from django.contrib.auth import views from members import views as member_views path('logout/', views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'), logout.html {% extends 'index.html' %} {% block css %}<meta http-equiv="refresh" content="5;{% url 'index' %}">{% endblock %} {% block title %}Logout{% endblock title %} {% block content %} <div class="container bground2"> <div class="form"> <h2>You are logged out</h2> <h6>You will be redirected to the Home Page</h6> <div class="border-top pt-3 pb-5"> <small class="text-muted text-center"> Login again<a … -
Accessing the development server over HTTPS, but it only supports HTTP error in django rest framework
I implemented it and it seems to have given me a error(I currently do not have that exact error in my logs. It might even be same to the error I am currently encountering). I tried to reverse it. It didn't worked. I went to ChatGPT. It gave me some troubleshooting methods and some solutions. Nothing worked. Here is my settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'later' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'api', # api is my app name 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.contenttypes', ] MIDDLEWARE = [ # 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'pythonRestApi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pythonRestApi.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # This is the code which was reversed. It was all set to True … -
I need assistance on how to get X-API-KEY in mtn API documentation for data sharing
I Am trying to make an automation software that can automatically share data and airtimes from my mtn line to my end users I tried using the mtn developer API and I got stuck at the X-API-KEy, I do not know how to go about that and if there's an alternative route to automate things I'm in Nigeria I will love to know. Thank you @api_view(['POST']) @permission_classes([AllowAny]) def datame(request): url = "https://api.mtn.com/v1/oauth/access_token?grant_type=client_credentials" payload = "client_id=sOO7K85Q9F5XKA5bxZ8zCQzESY3dluv2&client_secret=q0FLPsgZV2m6nhS7" headers = { 'Content-Type': "application/x-www-form-urlencoded" } token_response = requests.request("POST", url, data=payload, headers=headers) # get access token using get() method token = token_response.json().get('access_token') print(token_response.text) print('token: ', token) url = "https://api.mtn.com/v1/datashare/providers/2348131116906" payload = { "consumerMsisdn": "2348062596273", "threshold": "string", "unit": "string", "nodeId": "string", "input": "string", "paymentOption": "string", "targetSystem": "CIS", "operationType": "MAKE_UNLIMITED_ALL" } headers = { "Content-Type": "application/json", "transactionId": "1256", "X-API-Key": token } response = requests.request("POST", url, json=payload, headers=headers) print(response.text) return JsonResponse({"res":response.json()}) -
Django ForeignKey model not working with serializer
I am trying to build a django app that takes a record file as an uploaded file and then generates data for that record file and saves it to a local directory in the "server" local pc at the moment so for now i have this: models.py: class Sensor(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) OwnerCompany = models.CharField(max_length=50) def __str__(self): return self.name class Bag(models.Model): name = models.CharField(max_length=255) sensor = models.ForeignKey("Sensor",on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) bag_file = models.FileField(upload_to="bag_files/") def __str__(self) -> str: return self.name views.py : class BagView(APIView): #to be changed to viewset parser_classes = [MultiPartParser] def get(self, request): bags = Bag.objects.all() serializer = BagSerializer(bags, many=True) return Response(serializer.data) def post(self, request): print(request.FILES,request.data) serializer = BagSerializer(data=request.data) if serializer.is_valid(): bag_upload = request.FILES['bag_upload'] if bag_upload: bag_name = os.path.basename(bag_upload.name) serializer.create(serializer.validated_data,bag_name) return Response({'message': 'Bag File Created and Data Extracted', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py : class SensorSerializer(serializers.ModelSerializer): class Meta: model = Sensor fields = "__all__" class BagSerializer(serializers.ModelSerializer): bag_upload = serializers.FileField(write_only=True) class Meta: model = Bag fields = ['id', 'sensor', 'date_created', 'bag_upload'] def create(self, validated_data,bag_name): print("HIIII") bag_upload = validated_data.pop('bag_upload', None) sensor_data = validated_data.pop('sensor', None) # Get 'sensor' data from validated data print(sensor_data) bag_name = bag_name # Check if 'sensor' data is provided if sensor_data is None: … -
Django-React not staying logged in
I have a React JS - Django site and I implemented the login functionality. But I have seen that the user does not stay logged in even though it authenticates and moves to the home page after log in. I tried displaying the username once it navigates to the home page and it returns empty. Views.py class Login(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') # Authenticate user user = authenticate(request, username=username, password=password) if user is not None: # If authentication succeeds, log in the user login(request, user) return JsonResponse({"message": "Login successful"}) else: # If authentication fails, return error response return JsonResponse({"error": "Invalid username or password"}, status=status.HTTP_400_BAD_REQUEST) Login.js const handleSubmit = async (e) => { e.preventDefault(); try { const response = await fetch("http://localhost:8000/login/", { method: 'POST', withCredentials: true, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const data = await response.json(); if (response.ok && data.message === "Login successful") { // Redirect to the home page upon successful login navigate('/'); } else { // Set error state with the error message setError(data.error); } } catch (error) { // Handle network or server errors setError("An error occurred during login. Please try again later."); } I have the … -
Is there any way to optimize get_or_create() to make the program faster?
The functionality I want to achieve is to create a new class and import users. Since I don't want the same user to be imported multiple times and a user can join different classes, I have used get_or_create(). However, I have noticed that the program becomes slow when importing a large number of users at once (using CSV to import users). def post(self, request): class_data = request.data class_data["start_time"] = dateutil.parser.parse(class_data["start_time"]) class_data["end_time"] = dateutil.parser.parse(class_data["end_time"]) class_data["created_by"] = request.user if class_data["end_time"] <= class_data["start_time"]: return self.error("Start time must occur earlier than end time") user_data = class_data.pop("users") # Retrieve user data and remove it from the class data try: with transaction.atomic(): if Class.objects.filter(title=class_data["title"]).exists(): return self.error("Class with the same title already exists") class_obj = Class.objects.create(**class_data) # Create the class object # Add the creator to the class members if not class_obj.users.filter(id=request.user.id).exists(): class_obj.users.add(request.user) for data in user_data: if len(data) != 4 or len(data[1]) > 32: return self.error(f"Error occurred while processing data '{data}'") username = data[1] user, created = User.objects.get_or_create(username=username, defaults={ "password": make_password(data[1]), "college": data[3], "student_number": data[1] }) if created: profile = UserProfile(user=user, real_name=data[2]) profile.save() # class_obj.users.add(user) if not class_obj.users.filter(id=user.id).exists(): class_obj.users.add(user) return self.success(ClassAdminSerializer(class_obj).data) except IntegrityError as e: return self.error(str(e).split("\n")[1]) I have identified three areas that slow down the … -
Django drf-yasg API versions switch from drop down
Is there a way to show available API versions in drop down using drf_yasg without overwriting the template? I checked their docs but seems like i have to use versionized URL to see different version of API, or i can show all API version URLs on same page. But I want to have a drop down to show only selected version paths. -
Have to run python manage.py collectstatic everytime I make change in my static files to show the changes in Django
I am creating a Django application and right now it's in development phase. I am using Google Cloud Storage, so I have to change settings accordingly, but after that I have to always run python manage.py collectstatic to show the changes in css or js file, no matter how small they are. settings.py STATIC_URL = 'static/' DEBUG = True DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'videovogue' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' service_account_key_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") GS_CREDENTIALS = service_account.Credentials.from_service_account_file(service_account_key_path) What is going wrong? MAX_FILE_SIZE = 209715200 # 200 MB -
How can I authenticate a user based on correct/incorrect credentials, but ignore their "is_active" state if I want to handle it separately?
Currently with django's default auth.authenticate method, it will return None if the credentials are correct, but user.is_active is false. This means that users who have correctly entered their credentials will receive the same error message as users who have incorrectly entered their credentials. I am looking to provide users with an error message for an edge case when they've entered the correct credentials, but haven't activated their account via email verification and thus user.is_active=False. My question is how do I implement this safely and efficiently? views.py: ... from django.contrib.auth import authenticate class LoginView(View): def get(self, request): return render(request, 'accounts/login.html') def post(self, request): username = request.POST['username'] password = request.POST['password'] if username and password: user = auth.authenticate(username=username, password=password) if user: if user.is_active: auth.login(request, user) return redirect('accounts:home') else: uidb64 = Base64.get_uidb64(user) message = format_html("Please check your email for a verification link, or <a href='{}'>click here to request a new one.</a>", reverse('accounts:verify', kwargs={'uidb64':uidb64})) messages.error(request, message) else: messages.error(request, 'Invalid account credentials. Please try again.') return render(request, 'accounts/login.html') return render(request, 'accounts/login.html') -
An error occurred (XMinioInvalidObjectName) when calling the PutObject operation: Object name contains unsupported characters
I've the following class class Foo: def value_to_filename(self, validated_data : dict): file_name = json.dumps(validated_data, cls=Encoder) file_name = self.convert_to_valid_s3_name(file_name) full_name = f"{file_name}.json" return full_name @classmethod def convert_to_valid_s3_name(cls, text : str): "value to cleaned filename" return base64.urlsafe_b64encode(text.encode()).decode() when uploading this to s3 it raises object name contains unsupported characters even if it doesn't measuring the name size it was less than 450 byte and max is 1024 so that can't be the issue but when splitting the name and using each half separately to check what part of the string is invalid, both halves worked perfectly example string: path/path/path/eyJhZGRsick12456IDEsICJtb2RpZmllZF9ieSI6IDEsICJjaGF0X2lkIjogIiIsICJjcmVhdGVkX2F0IjogIjIwMjotMDMtMjQgMjA6MjU6MjkuNzY1NzM0KzAwOjAwIiwgIm1vZGlmaWVkX2F0IjogbnVsbDwgInT4cGUQOiAic2FwZm9rYXBma2FwZnNkcFtsZnNkYVsgbGFmcGFkc29mIGthc1tvWyBscWVhLWZwIGRzW3BscjJbM3IncWUseHouZiwsengvZix6eCA7LGFzLGZhcydmIiwgImNhcmVQcm92aWRlciI6ICJhb3BrZmFwZiIsICJzdGFydF9kYXRlIjogIjIwMjQtMDMtMTQgMSQ6MTE6NDcuNjAxMDAwKzAwOjAwIn1=.json -
How can I optimize creating an xlsx file?
I have created an API that reads a file we recieve and then gives me back the information I need. I now need to create a new .xlsx file with this new data I have recieved. Currently it's working, but it is really not optimized. Creating a file with 4000 lines pretty much instant, but we will need to create files with up to hundreds of thousands of lines. At the moment, creating a file with 140,000 lines took 14 minutes. I am not very experienced in algoritm optimization so i'm not sure where look for optimizing. This is a project written with a Django backend. Here is the views.py function def vannmiljo(request): survey_id = request.GET.get('surveyID', None) if not survey_id: return JsonResponse({'error': 'SurveyID parameter is missing'}, status=400) instanceID = request.GET.get('m_instanceID', None) if not instanceID: error = "No datafile" return JsonResponse({'error': error}, status=400) instance = SurveyInstance.objects.get(id=instanceID) if not instance.survey_file: error = "No datafile" return JsonResponse({'error': error}, status=400) else: excel_file_url = instance.get_survey_file_url response = requests.get(excel_file_url) if not response.status_code == 200: print(f'Failed to download Excel file: {response.status_code}') excel_data = BytesIO(response.content) try: dfs = pd.read_excel(excel_data, engine="openpyxl") start_row = dfs[dfs.eq('Sal.').any(axis=1)].index[0] dfs = dfs.iloc[start_row:] dfs.reset_index(drop=True, inplace=True) dfs.columns = dfs.iloc[0] dfs = dfs[1:] data_list = [] columns_to_keep … -
Django returns AnonymousUser despite authenticating earlier
I have a problem where I call the login() function within Django and despite the user ID being set in the request session, whenever in another view I call request.user.is_authenticated which returns True. My login view: class LoginView(APIView): serializer_class = LoginUserSerializer def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): username = serializer.data.get('username') password = serializer.data.get('password') # If username is not present in the database at all user_exist_query = User.objects.filter(username=username) if not user_exist_query.exists(): return JsonResponse({"error": "Username does not exist"}, status = 401) # If username and password match user_auth_query = authenticate(username=username, password=password) if user_auth_query is not None: login(request, user_auth_query) return JsonResponse({"message": "Login Successful"}, status = 200) else: return JsonResponse({"error": "Username and Password combination is incorrect"}, status = 401) return JsonResponse({"error": "Bad Request"}, status=400) The other view where authentication actually works: class CheckAuthView(APIView): def get(self, request): if request.user.is_authenticated: return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) I use this view to protect a route (using React as a frontend). The home page is only accessible to logged in users and whenever I am logged in, I am able to view that page and when I am logged out, a different page is showed therefore proving that here, getting the request.user does return an actual user. … -
Encountering "requires_payment_method" Error When Implementing Stripe Payment Method
I am encountering an issue while integrating the Stripe payment method into my website. The error message I'm receiving is "requires_payment_method". Below, I've provided the relevant JavaScript, HTML, and Python (Django) logic for handling payments. `<script> var stripe = Stripe('my_stripe_public_key'); function submitPaymentForm() { var cardholderName = document.getElementById('cardholder').value; var cardElement = elements.create('card'); stripe.createToken(cardElement).then(function(result) { if (result.error) { console.error(result.error.message); } else { document.getElementById('stripeToken').value = result.token.id; document.form_payment.submit(); } }); } </script>` ``` ` def checkout_payment(request): if request.method == "POST": payment_method_token = request.POST.get('stripeToken') print(payment_method_token) cardholder = request.POST.get('cardholder') cardnumber = request.POST.get('cardnumber') expiration_month = request.POST.get('mm') expiration_year = request.POST.get('yy') csc = request.POST.get('csc') # payment_type =request.POST.get('payment_type') user = request.user cart_items = Cart.objects.filter(user=user, is_ordered=False) cart_total = sum(float(item.product.discounted_price()) * item.quantity for item in cart_items) total = int(cart_total * 100) stripe.api_key = settings.STRIPE_SECRET_KEY try: customer = stripe.Customer.create( email = request.user.email, ) # Create PaymentIntent with retrieved payment method payment_intent = stripe.PaymentIntent.create( amount=total, currency='pkr', payment_method_types=["card"], customer=customer.id, description="Payment for items in cart", metadata={'integration_check': 'accept_a_payment'}, ) # Check for successful payment if payment_intent.status == 'succeeded': print(payment_intent) return redirect('checkout_complete') else: # Handle failed payment print(f"Payment failed with status: {payment_intent.status}") messages.error(request, 'Payment failed. Please try again.') except Exception as e: print(e) messages.error(request, 'An error occurred while processing the payment. Please try again.') return render(request, 'checkout_payment.html') Issue: … -
How to connect to Neo4J's AuraDB (free tier) from Django?
I have added the the following lines to my settings.py as follows: from neomodel import config import dj_database_url NEOMODEL_NEO4J_BOLT_URL = 'neo4j+s://xxxxxxx.databases.neo4j.io' NEOMODEL_SIGNALS = True NEOMODEL_FORCE_TIMEZONE = False NEOMODEL_ENCRYPTED_CONNECTION = False NEOMODEL_MAX_CONNECTION_POOL_SIZE = 50 user = 'neo4j' psw = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' uri = 'neo4j+ssc://xxxxxxxx.databases.neo4j.io' DATABASE_URL = 'neo4j+ssc://{}:{}@{}'.format(user, psw, uri) config.DATABASE_URL = 'neo4j+ssc://{}:{}@{}'.format(user, psw, uri) DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} And I get this error when I run python manage.py migrate: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "S_v1\venv\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "S_v1\venv\lib\site-packages\django\core\management\__init__.py", line 382, in execute settings.INSTALLED_APPS File "S_v1\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "S_v1\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "S_v1\venv\lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\P\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "S_v1\mysite_2\mysite\settings.py", line 102, in <module> DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)} File "S_v1\venv\lib\site-packages\dj_database_url\__init__.py", line 72, in config return parse( File "S_v1\venv\lib\site-packages\dj_database_url\__init__.py", line 126, in … -
Why are my Django project JavaScript files not loading, while the CSS files load successfully when they are both placed within the same static folder?
I am having issues to make my project load the Js files and functionalities. I am using this template from the internet. All of the static files (images, CSS and Js) are located inside the "static" folder but only Js is not loading. For example, the swiper and the data-aos are not working. #Base template {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Pezorium</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href="{% static 'img/favicon_fish_white.png' %}" rel="shortcut icon" type="image/png"> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500&family=Inter:wght@400;500&family=Playfair+Display:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/bootstrap-icons/bootstrap-icons.css' %}" rel="stylesheet"> <link href="{% static 'vendor/swiper/swiper-bundle.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/glightbox/css/glightbox.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/aos/aos.css' %}" rel="stylesheet"> <!-- Template Main CSS Files --> <link href="{% static 'css/variables.css' %}" rel="stylesheet"> <link href="{% static 'css/main.css' %}" rel="stylesheet"> <!-- ======================================================= * Template Name: ZenBlog * Updated: Jan 29 2024 with Bootstrap v5.3.2 * Template URL: https://bootstrapmade.com/zenblog-bootstrap-blog-template/ * Author: BootstrapMade.com * License: https:///bootstrapmade.com/license/ ======================================================== --> </head> <body> <header id="header" class="header d-flex align-items-center fixed-top"> <div class="container-fluid container-xl d-flex align-items-center justify-content-between"> <a … -
Django - Form for Editing Objects with a One-To-Many Relationship
I have a model which contains a variable length list of objects. I want to be able to edit this model in a form, and in the same form edit each of the associated objects in the list. I have looked at formsets which may be a way to handle the form for the multiple objects in the list, but from django documentation and searching online it is not obvious how I would then integrate this into the form of the parent object. What would be the best practice approach to this in Django? -
blank space on top and left of the page while developing frontend
I am building an application in Django and for writing templates I am using HTML/CSS, now there is some weird white space I am encountering on the top and left side of the page which does not go, no matter what I try as shown below now here are my css files base.css .navbar { position: fixed; top: 0; left: 0; width: 100%; height: 60px; display: flex; align-items: center; justify-content: space-between; background-color: #333; color: white; padding: 10px 20px; z-index: -1; } .navbar-brand img { max-height: 40px; } .navbar-menu ul { list-style-type: none; margin: 0; padding: 0; display: flex; } .navbar-menu li { margin: 0 10px; } .navbar-menu li a { color: white; text-decoration: none; } .navbar-user img { max-height: 30px; } and home.css .home-video { position: relative; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; } #bg-video { width: 100vw; height: 100vh; object-fit: cover; } .home-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; } .home-content h1 { font-size: 3rem; margin-bottom: 20px; color: white; } .home-content p { font-size: 1.2rem; margin-bottom: 30px; color: white; } .btn { display: inline-block; padding: 10px 20px; background-color: #333; color: white; text-decoration: none; border-radius: 5px; transition: background-color 0.3s ease; } .btn:hover …