Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Invalid filter: 'length_is' Error in Django Template – How to Fix?
I’m encountering a TemplateSyntaxError in my Django project when rendering a template. The error message I’m seeing is: TemplateSyntaxError at /admin/dashboard/program/add/ Invalid filter: 'length_is' Django Version: 5.1 Python Version: 3.12.4 Error Location: This error appears in a Django template at line 22 of the fieldset.html file. {% for line in fieldset %} {% for field in line %} {{ field.field.label|capfirst }} {% if field.field.field.required %} * {% endif %} What I Tried: Checked for Custom Filters: I reviewed my project and its installed packages to verify if there is a custom filter named length_is. I found that no such custom filter is defined in my project. Verified Django Installation: I ensured that Django is correctly installed and up-to-date with version 5.1. Reviewed Template Code: I carefully examined the template code that causes the error. I found that line.fields|length_is:'1' is used, but the length_is filter is not a standard Django filter. Searched for Package Bugs: I searched through documentation and bug reports related to django-jazzmin to see if there is any mention of the length_is filter issue, but I could not find relevant information. What I Expected: I expected to find either: Documentation or a reference indicating that length_is is a … -
JS / Jquery - Dynamically set text value to a Django form choicefield
I have this choicefield in a django form : forms.py sales_documents_description_1 = forms.ChoiceField(required=False, choices=list(models_products.objects.values_list( 'id_product','product_denomination')), widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) In my template, how do I set this choicefield value by specifiying the text argument (NOT THE VALUE) I tried with this : Template.html $('#sales_documents_description_1').filter(function() {return $(this).text() == 'Neumann U87';}).prop('selected', true); But it's not working. Any JS or JQuery solution will be ok for me. Thanks -
Filtrer les données d'un select à partir d'un autre select
Bonjour. Je suis entrain de développer une petite application de gestion scolaire en Django. Sur mon formulaire j'ai 3 drop-down : un pour afficher la liste des filières, un autre pour afficher la liste de classe selon la filière sélectionnée et un autre pour afficher la liste des élèves inscrits dans la classe sélectionnée précédemment dans la liste des classes affichées selon la filière choisie. Aidez-moi avec le code pour résoudre ce problème. Je travaille en Django 5. J'ai besoin d'avoir des filtres sur mes modèles Classe et Eleve pour y arriver mais je ne sais pas comment procéder. -
TemplateSyntaxError after Adding Django Admin Theme using Jazzmin Module
I've added a Django admin panel theme to my project using the django-jazzmin module. It works fine initially, but when I try to access certain options in the admin panel (like "Users" or "Profile"), I encounter the following error: TemplateSyntaxError at /admin/booking/bookedseat/53/change/ Invalid filter: 'length_is' and this is my html code <div class="form-group{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> From what I've read online, it seems like the theme might be deprecated or not fully compatible with Django 5, but I'm not entirely sure. I'm currently stuck and not sure how to resolve this issue. Has anyone else faced this problem? Any advice on how to fix this template error or suggestions for alternative themes that work well with Django 5? Details: Django version: 4.2 Jazzmin version: django-jazzmin-3.0.0 Thanks in advance for any help! Questions: Has anyone encountered this issue with Jazzmin on Django 5? Is there a known fix or workaround to resolve this length_is filter error while still using Jazzmin? Would downgrading Django or making adjustments to the Jazzmin templates be a viable solution? -
GitHub Actions not picking-up errors on Django doctests
I just realized that failure of my doctests was not raising error during testing run through GitHub Actions. How to ensure that failing doctests would trigger failure of the GitHub Actions testing? Example of a doctest as I'm defining them so far: from django.test import SimpleTestCase import doctest class DocStrings_Tests(SimpleTestCase): def test_docstrings(self): from cubes import color_coding doctest.testmod(color_coding) and here is the simplified workflow I'm using for testing: name: Project testing on: [pull_request, push] # activates the workflow when there is a push or pull request jobs: run_project_testing: runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: tests: ["cubes", "users", "games"] steps: - name: Run Tests - ${{ matrix.tests }} run: | pip install coverage coverage run -p manage.py test ${{ matrix.tests }} -
django RelatedManager return None in template
I am trying to access related data in Templates But I only get None. models from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField() price = models.PositiveBigIntegerField() discount = models.PositiveBigIntegerField(default=0) inventory = models.PositiveBigIntegerField(default=1) last_update = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.title class Image(models.Model): image = models.ImageField() product = models.ForeignKey(to=Product,on_delete=models.CASCADE) class Cart(models.Model): STATUS = [ (0,"pending payment"), (1,"paid") ] status = models.SmallIntegerField(choices=STATUS,default=0) user = models.ForeignKey(to=User,on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.user} - {self.status}" @receiver(post_save,sender=Cart) def cart_post_save(sender, instance, created, *args, **kwargs): if created and instance.status == 1 : Cart.objects.create(user=instance.user) class Order(models.Model): product = models.ForeignKey(to=Product,on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) cart = models.ForeignKey(to=Cart,on_delete=models.CASCADE) def __str__(self) -> str: return f"{self.product}" views from django.views import generic from . import models from django.http import JsonResponse,HttpResponseBadRequest,HttpResponse class ProductsList(generic.ListView): """return list of all products and template name is prudoct_list.html""" model = models.Product paginate_by = 30 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class ProductsDetail(generic.DetailView): """return a product and template name is prudoct_detail.html""" model = models.Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>online-shop</title> … -
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte [Djanago Rest Framework]
Issue: When uploading data with an image, the following issue occurs if some PrimaryKeyRelatedField is missing or the field ID is not valid. If I don't upload any image file, then expected output field validation issues arise. Encountered Issue: If I send some missing or invalid data with image files, the following issue occurs. However, the expected result was a validation issue. Validation Issue [expected output]: The API shows the following output if I don't send any image file, which is the expected output. { "status": false, "errors": { "service_cost_details": [ "This field is required." ], "photo": [ "No file was submitted." ], "citizenship_front": [ "No file was submitted." ], "citizenship_back": [ "No file was submitted." ], "province": [ "Invalid pk \"75242546\" - object does not exist." ] }, "results": { "house_number": "420", "old_membership_number": "", "first_name": "test", "middle_name": "test", "last_name": "456", "email": "user@example.com", "phone_number": "9895655644", "address": "madhyabindu", "date_of_birth": "2024-08-15", "gender": "Male", "pan_number": "420", "family_member_count": "4", "citizenship_number": "56551", "citizenship_issue_district": "1", "province": "75242546", "district": "2", "municipality": "3", "ward": "4", "tol": null } } My model Looks like: class ConsumerDetails(CreatorModifierInfo): gender_select = (("Male", "Male"), ("Female", "Female"), ("Other", "Other")) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True, db_index=True) office = models.ForeignKey(Office, null=True, blank=True, on_delete=models.SET_NULL) service_cost_details = models.ForeignKey(ServiceCostDetails, … -
Running another method in a View after a form is saved using CBVs - DJANGO
I am trying to run another method after a form is saved: The method inc_rec gets the id field created from the class based view once saved Once form is saved: I want to retrieve all records in the table Checklist Iterate through each of the rows and add the records to the All_Inspection table and updating the company id. I am a bit stuck - as I have tried using signals, and I have tried to override, but somewhere there is a gap. Help appreciated - Thanks in advance. class ParishCreateView(LoginRequiredMixin, CreateView): model = Company fields = ['str_Company_Name', 'str_City','str_post_code'] #success_url = '/' def form_valid(self, form): print('form_valid') form.instance.author = self.request.user return super().form_valid(form) def inc_rec(self): Checklist = Checklist.objects.all() id = self.request.id for rec in Checklist: new_rec=All_Inspection(str_status=rec.str_status, str_check=rec.str_check, str_comment='',company_id=id) new_rec.save() I am expecting new records to be added into ALL_Inspection table once the form is saved with the new created item. -
Django All-auth return account inactive at the first social login
I have the local account that status is_active = False. Now I would like to set the account activation status True automatically if users login by their social account. At my code, I have the Django Allauth hook to set the user is_active to True class CustomAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): email = sociallogin.email_addresses[0] user = User.objects.get(email=email) user.is_active = True user.save() However, at the first time login, it's always tells me that the account is not active. When login at the second time, users can login as expected, I'm still not figure out why is this happening. please help me with this, thank you. -
Is there a way to connect users from different projects?
My admin dashboard users are in mongodb in authentication server(expressjs ts) but my apps users are in postgresql in another server(Django). I have made once service that is used to create events. but the problem is I want to know who created the event. as the event can be created by both admin users and app users. I am currently using jwt with same secret in both servers and using bearer token to authenticate the user. So far it's working as I am storing the id and name of users in event model. here the id of admin will be from mongodb and id of app user will be from postgresql. Is there a correct way to do this? -
Trigger Function Not Inserting All Records in data_sync_datahistory Table with application_name = 'dibpos_offline'
I'm working on a PostgreSQL trigger function to log changes to a data_sync_datahistory table whenever there's an INSERT or UPDATE operation on other tables. The trigger is set up to only log these changes when the application_name is set to 'dibpos_offline'. However, I'm encountering an issue where some records are not being inserted into the data_sync_datahistory table when multiple records are inserted into the database. Here is my trigger function: IF current_setting('application_name') = 'dibpos_offline' THEN IF TG_OP = 'INSERT' THEN INSERT INTO data_sync_datahistory (created, modified, data, source, table_name) VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ROW_TO_JSON(NEW), 'local', TG_TABLE_NAME); ELSIF TG_OP = 'UPDATE' THEN INSERT INTO data_sync_datahistory (created, modified, data, source, table_name) VALUES (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ROW_TO_JSON(NEW), 'local', TG_TABLE_NAME); END IF; END IF; RETURN NEW; And here is the relevant part of my database configuration: DATABASES = { 'default': { 'NAME': os.environ.get('DB_NAME', "postgres") if os.environ.get("DB_HOST", None) else os.path.join(Path.home(), 'dibpos.sqlite3'), 'USER': os.environ.get('DB_USER', "postgres"), 'PASSWORD': os.environ.get('DB_PASSWORD', '1234'), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': os.environ.get('DB_PORT', 5432), 'CONN_MAX_AGE': None, 'CONN_HEALTH_CHECK': True, 'OPTIONS': { 'options': '-c application_name=dibpos_offline' }, } } Problem: When multiple records are inserted into the database, some of them are not being logged into the data_sync_datahistory table. The trigger function seems to be missing some records. Questions: Could the issue … -
Define commonly used form fields in Django
I have an app where there are some search forms on different pages. One commonly used form field would be 'show x items', where x can be 10, 20 or 50. I would also like a field 'Sort by' with some standard values. I have used Django model mixins earlier, e.g. CreateTimestampMixin, which standardizes the column name 'create_ts' in my models, and I want to have something similar in my forms now. Note: These are just forms, not model forms. Is there a way that I can do it? Or must I only define a new field type that derives from forms.ChoiceField, plugin my choice values, and then in each form define this field? -
Nothing happens when you try to start the django server. Writes only to the Python terminal
Nothing happens when you try to start the django server. Writes only to the Python terminal. I work in the VS code editor I was checking Check the path to the interpreter. I checked the Python version. I run it in the folder where it is located manage.py -
Django - can't use different id an value with choicefield's list while using jQuery Editable Select
In Django I'm using a ChoiceField: forms.py class forms_sales_documents(forms.ModelForm): sales_documents_description_1 = forms.ChoiceField(required=False, choices=list(models_products.objects.values_list( 'id_product','product_denomination')), widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) I'm using JQuery-Editable-select https://github.com/indrimuska/jquery-editable-select to create searchable selecboxes but when I do, it becomes impossible to dissociate the ChoiceField value from the label. They have to be the same like models_products.objects.values_list( 'id_product','id_product')) you can"t do something like models_products.objects.values_list( 'id_product','product_denomination')) otherwise the form won't save and raise the error : Select a valid choice. That choice is not one of the available choices Anybody to help me on this ? -
DigitalOcean IP is sending me to a random website
I am setting up a Django website on DigitalOcean. I've been following along a tutorial and in my settings folder I set my ALLOWED_HOSTS equal to the ipv4 that DigitalOcean provided when I set up the droplet for the project. However when I run python3 manage.py runserver using the provided ip address it sends me over to https://unforgettableweddingaustralia.com/. I'm thinking that DigitalOcean provided me with an IP address already in use but I'm not sure. Any advice or ideas would be greatly appreciated. -
Error 500 on the Heroku server, when locally everything is fine
I made an django app from the "Python Crush Course" book and when I try to login or register in my django app on heroku server, I have an error 500 on webpage and error 200 on logs. However, when I register or login locally I don't have any issues. Here are the heroku logs: 2024-08-02T22:17:13.267743+00:00 heroku\[web.1\]: State changed from starting to up 2024-08-03T22:34:20.389130+00:00 heroku\[router\]: at=info method=GET path="/" host=fierce-brook-34882-87d6631e0056.herokuapp.com request_id=34b832f3-b190-4bc2-88ac-576c6dd59905 fwd="80.107.58.61" dyno=web.1 connect=0ms service=137ms status=200 bytes=2493 protocol=https 2024-08-03T22:34:20.389210+00:00 app\[web.1\]: - - \[03/Aug/2024:22:34:20 +0000\] "GET / HTTP/1.1" 200 2197 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" 2024-08-03T22:34:20.729350+00:00 app\[web.1\]: 10.1.62.231 - - \[03/Aug/2024:22:34:20 +0000\] "GET /favicon.ico HTTP/1.1" 404 1862 "https://fierce-brook-34882-87d6631e0056.herokuapp.com/" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" 2024-08-03T22:34:20.729672+00:00 heroku\[router\]: at=info method=GET path="/favicon.ico" host=fierce-brook-34882-87d6631e0056.herokuapp.com request_id=ba080178-f0ef-4d0c-8745-0556273710f1 fwd="80.107.58.61" dyno=web.1 connect=0ms service=28ms status=404 bytes=2165 protocol=https 2024-08-03T22:34:26.884713+00:00 app\[web.1\]: 10.1.94.152 - - \[03/Aug/2024:22:34:26 +0000\] "GET /users/login/ HTTP/1.1" 200 2715 "https://fierce-brook-34882-87d6631e0056.herokuapp.com/" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" Here are the localhosts logs: [arch@archlinux dj_proj]$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). August 14, 2024 - 19:36:06 Django version 5.1, using settings 'learning_log.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [14/Aug/2024 19:36:09] "GET / HTTP/1.1" 200 2197 [14/Aug/2024 19:36:28] … -
Django user_auth how to foreign key one to many
What I'm looking for is that a many users can be part of a tenant, so my idea in the beginning was to foreign key from user to tenant but I can't found how to do this. This is what I have at the moment: models.py class Tenants(models.Model): empresa = models.CharField(max_length=60, null=False, blank=False) sub_dominio = models.CharField(max_length=60, null=True, blank=True) usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=20, null=False, blank=False) class Meta: verbose_name_plural = "Tenants" def __str__(self): return self.empresa But with this solution I can only have a User per Tenant, how can I do Many users per tenant? -
when i use django model's variable for api keys to get data of coinbase market it doesn't work
i have created django models to save the api keys this is the models code class Coinbaseapi(models.Model): symbol = models.CharField(max_length=10, null=True, blank=True) API = models.CharField(max_length=100, null=True, blank=True) SECRET = models.CharField(max_length=250, null=True, blank=True) and using this serializer class Coinbaseserializer(serializers.ModelSerializer): class Meta: model = Coinbaseapi fields = "__all__" I tried getting the market data in a function with this code coinbase = Coinbaseapi.objects.all().first() cbSerializer = Coinbaseserializer(coinbase) CoinbaseData = cbSerializer.data current_price = coinbase.fetch_ticker(CoinbaseData['symbol'])['last'] it gives this error print(coinbase.fetch_ticker(CoinbaseData['symbol'])['last']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ n = string[0] if isinstance(string[0], int) else ord(string[0]) ~~~~~~^^^ IndexError: index out of range while i used it buy using local variable and tested in another 1 simple python file and it was working fine. coinbase = ccxt.coinbase({ 'apiKey': API, 'secret': SECRET, "enableRateLimit": True, 'options': { 'defaultType': 'future', } }) cp = coinbase.fetch_ticker('MATIC/USDT')['last'] print(cp) I checked on the internet to save it in this format given below -----BEGIN EC PRIVATE KEY----- xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -----END EC PRIVATE KEY----- instead of using this default format below but didn't worked either -----BEGIN EC PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n-----END EC PRIVATE KEY-----\n -
Django - ChoiceField to save ID instead of value, and retrieve value from ID on form load
In Django I'm using a ChoiceField named sales_documents_description_1. forms.py #creation of the list def get_product_denomination_list(): list_product_denomination = list((item.product_denomination , item.product_denomination) for item in models_products.objects.all()) return sorted(list_product_denomination) class forms_sales_documents(forms.ModelForm): [...] sales_documents_description_1 = forms.ChoiceField(required=False,choices=get_product_denomination_list, widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) models.py class models_products(models.Model): id_product = models.CharField(primary_key=True, max_length=50) product_reference = models.CharField(max_length=20) product_denomination = models.CharField(max_length=200) product_prix_achat = models.CharField(max_length=50) I'm trying to show product_denomination in the dropdown menu but store the related id_product in the DB. On form load I would like the selectbox to retrieve the related product_denomination from the id_product initially stored. I tried this : Need to get id instead of selected value in modelchoicefield django and How to store id in database but to show name in modelchoicefield in Django? with no succes. Thanks for help -
How to Safely Add Users to Backend with Google Sign-In?
I’m working on a Flutter app with my own custom backend built in Django. Currently, I have a registration form that accepts an email and password to create a new user in the database. Now, I’m integrating Google Sign-In and wondering how to handle new user registration. After a successful Google sign-in, I receive details like the email, idToken, accessToken, and user ID. I was thinking of sending a request to my backend with the email and using the accessToken as the password to create the user. But is this a safe approach? Should I handle this differently to ensure the security of the authentication process? What’s the best way to securely add a new user to my backend using the data received from Google Sign-In? I’m not using Firebase, just my own Django backend. Any guidance or best practices on how to implement this securely would be greatly appreciated. Thanks! -
Tailwind color class not working in HTMX post result in a Django app
I want to send a form to a Django view via HTMX. After the request, a new span should be inserted in a div with the ID #result. This span has the Tailwind class text-green-500. This works so far (the span is inserted into the div). However, the color of the span does not change to the nice green tone that I expected. This is the Django view: @login_required def create_daytistic(request: HttpRequest) -> HttpResponse: return HttpResponse('<span class="text-green-500">Daytistic erfolgreich erstellt</span>') And this is the Django template: {% extends 'base.html' %} {% block content %} <div class="bg-gray-100"> <div class="min-h-screen flex"> <!-- Sidebar --> {% include 'components/common/sidebar.html' %} <!-- Main content --> <main class="flex-1 p-8" x-data> <div class="flex flex-row"> <div class="bg-white p-6 rounded-lg shadow-lg w-1/2" x-data="{loading: false}" > <h1 class="text-2xl font-bold mb-4">Daytistic erstellen</h1> <p><b>Hinweis</b>: Die Daytistic darf maximal 4 Wochen alt sein.</p> <form hx-post="{% url 'daytistics_create' %}" hx-trigger="submit" hx-target="#result" hx-swap="innerHTML" hx-indicator="#spinner" @submit.prevent="loading = true" @htmx:afterRequest="loading = false" > {% csrf_token %} <label for="date" class="mt-4">Datum: </label> <input x-mask="99.99.9999" placeholder="DD.MM.YYYY" name="date" class="mt-4 bg-white-light text-gray-500 border-1 rounded-md p-2 mb-4 focus:bg-white-light focus:outline-none focus:ring-1 focus:ring-blue-500 transition ease-in-out duration-150 h-11" /> <div id="submit-button-container" class="inline"> <button type="submit" id="submit-button" class="h-11 w-48 bg-gradient-to-r from-lime-500 to-green-500 text-white font-bold py-2 px-4 rounded-md hover:bg-lime-800 hover:to-green-800 … -
Getting error while accessing my site on python anywhere
Getting this error : Something went wrong :-( Something went wrong while trying to load this site; please try again later. Debugging tips If this is your site, and you just reloaded it, then the problem might simply be that it hasn't loaded up yet. Try refreshing this page and see if this message disappears. If you keep getting this message, you should check your site's server and error logs for any messages. Error code: 504-backend. I have created Blog API using drf and frontend app in django templates in same project. the response time for signup taking to much time to load and gives above error. But when i am using same api for local server on my machine it is working why is it happening also there is this message You are in the tarpit. 100% used – 126.38s of 100s. Resets in 2 hours, 35 minutes is it happening because i am in tarpit? i asked chatgpt my error log it gave this The error log indicates that the signup_view is trying to parse a JSON response from an API, but the response body is empty or not valid JSON. Even though my api response from postman … -
How to generate the confirm password reset view with Django?
I have a Django Rest Framework api app. And I try to generate some functionaly for forgot password. At the moment there is an api call availeble for reset password. And a user gets an email with a reset email link. But the problem I am facing is that if the user triggers the reset email link that this results in an error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/reset-password/MjE/cbr2cj-0d6c660c151de4e79594212801241fed/ So this is the views.py file with the function PasswordResetConfirmView class PasswordResetConfirmView(generics.GenericAPIView): serializer_class = PasswordResetConfirmSerializer print("password rest") def post(self, request, uidb64, token, *args, **kwargs): try: uid = urlsafe_base64_decode(uidb64).decode() user = Account.objects.get(pk=uid) print(user) except (TypeError, ValueError, OverflowError, Account.DoesNotExist): user = None if user and default_token_generator.check_token(user, token): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user=user) return Response({"message": "Password reset successful."}, status=status.HTTP_200_OK) else: return Response({"error": "Invalid token or user."}, status=status.HTTP_400_BAD_REQUEST) And model account looks: class MyAccountManager(BaseUserManager): @allowed_users(allowed_roles=['account_permission']) def create_user(self, email, password=None, **extra_field): if not email: raise ValueError("Gebruiker moet een email adres hebben.") if not password: raise ValueError("Gebruiker moet een password hebben.") user = self.model(email=email, **extra_field) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True … -
Django mod-wsgi return empty response
I am trying to deploy a project on windows server with Apache24 on a Windows server. I am fairly new to this but I have spent more than a week trying to figure out what I need to do and what configurations I need to put in. The server is configured to work on HTTPS with a certificate. You can assume that any request coming on 80 or 8080 port is redirected to 443 that all works fine. <VirtualHost *:443> DocumentRoot "${DOCROOT}" ServerName domain SSLEngine on SSLCertificateFile "${SRVROOT}/conf/${SSLCRT}" SSLCertificateKeyFile "${SRVROOT}/conf/${SSLPEM}" SSLCertificateChainFile "${SRVROOT}/conf/${SSLINTCRT}" #SSLCACertificateFile "${SRVROOT}/conf/${SSLROOTCRT}" <Directory "${DOCROOT}/TIPS"> Require all granted </Directory> <FilesMatch "\.(cgi|shtml|phtml|php|py)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory "${SRVROOT}/cgi-bin"> SSLOptions +StdEnvVars </Directory> WSGIScriptAlias / "path/to/wsgi.py" # WSGIScriptAlias / "path/to/test.wsgi" # Alias for static files Alias /static "path/to/static" Alias /media "path/to/media" <Directory "path/to/static"> Require all granted </Directory> <Directory "path/to/media"> Require all granted </Directory> ErrorLog ${SRVROOT}/logs/error-TIPS.log CustomLog ${SRVROOT}/logs/access-TIPS.log combined BrowserMatch "MSIE [2-5]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 In the httpd.conf file there are the following relevant configurations aside from some others: RequestHeader unset Proxy early TypesConfig conf/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz LoadFile "C:/Program Files/Python310/python310.dll" LoadModule wsgi_module "path/to/venv/lib/site- packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "path/to/venv" WSGIPythonPath "path/to/TIPS" The weird thing is that if i request anything from … -
Creating new tenant for django-tenants enabled web application, but could not be able to connect
I have created a multi tenants based web application by using django-tenants package. Earlier i have created two tenants on it and they are working fine. Now i am creating one more tenant by using following method:- from customers.models import Client, Domain lspsk = Client(schema_name='lspsk1', name=' lspsk1', paid_until='2025-09-01', on_trial=True) lspsk.save() domain = Domain() domain.domain = 'lspsk.maumodern.co.in' domain.tenant = lspsk domain.is_primary = False domain.save() I also created DNS entry for the tenant. But when i am connecting to the server i am getting internal server error 500 in browser. When i checked the log file there is one entry like:- 47.9.78.243 - - [14/Aug/2024:10:43:04 +0000] "GET / HTTP/1.1" 500 3058 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" 47.9.78.243 - - [14/Aug/2024:10:43:04 +0000] "GET /favicon.ico HTTP/1.1" 404 3103 "https://lspsk.maumodern.co.in/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36" Kindly guide me where i am doing wrong what logs should i look to further investigate the issue. Thanks & Regards Neha Singh