Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display information using django tags
I am writing a site on Django, the purpose of this site is to create a test to assess students' knowledge I need help with outputting options for answers to a question I keep the questions in a list and the answer options in a nested list for example: questions = [ "question1","question2","question3"] answers = [[ "answer1","answer2",answer3 ],["answer1","answer2",answer3,answer4 ] , ["answer1","answer2",answer3 ]]` and I need this data to be displayed in the following format: question1 answer1 answer2 answer3 question2 answer1 answer2 answer3 answer4 question3 answer1 answer2 answer3 here is my code, it does not work very correctly, I know, I have not yet figured out how to implement it in Django tags {% for question in questions %} {{question}} {% for answer in answers %} {% for current in answer %} {{ current }} {% endfor %} {% endfor %} {% endfor %} -
Django: Create form from items in model, where each item in the model has multiple associated questions
I want to ask users multiple questions for each of a list of items in a Django model. As an illustrative example: Suppose I'm collecting data on people's opinions of the Harry Potter films. I want to know if someone has a) watched one of the films, and b) what rating (out of 10) they give said film. Assume that my Django app contains 3 models: Films - to populate the list of films; Users - details on the person who has responded; Reponses - responses for each user. This contains three columns: UserID, FilmID, Rating. It is only populated when a user has given a score for a film (i.e., no blank ratings) The table below shows what kind of answer I'd want to receive: a check of whether they watched the film, and their rating out of 10. Film Watched? Rating HP-1 Y 8 HP-2 Y 9 HP-3 N - HP-4 N - HP-5 N - HP-6 Y 7 HP-7 N - HP-8 N - The HTML of the form would have a similar layout: film name, check box for if it has been watched, and the rating field (dropdown or integer field). This would then load the … -
Can my heroku app store images even after restarting dyno
I have 2 services, backend api on django and frontend on react. My goal is to make django admin page create new food models with pasting new image. On local host everything works fine,images are saving on media/food_images and even after restarting local host they stay there. But when I host them on heroku, make few food models and then restart dyno images dissapear. I checked that when I make new food models in "heroku run bash" there is no media folder. Is there a way to save them for ever? -
How to use count() to get items between specific dates
With this code I am able to get all orders items that is related to Article but here is the problem, I want to get the number of orders that are between two dates that are between the assigned timestamp.How can I do it? class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='ordersauthor') article = models.ForeignKey(Article, null=True, blank=True, on_delete=models.CASCADE,related_name='ordersarticle') timestamp = models.DateTimeField(auto_now_add=True) total_price = models.FloatField(default='0', validators=[MaxValueValidator(99999999999999999999)]) class ArticleSerializer(serializers.ModelSerializer): orders = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = '__all__' def get_orders(self, language): return language.ordersarticle.count() Initial Output: { "id": "2f95f593-6b95-45aa-97c4-e4157eed5189", "timestamp": "2024-03-04T16:55:42.572529Z", "orders": 4, // All orders }, Expected Output: { "id": "2f95f593-6b95-45aa-97c4-e4157eed5189", "timestamp": "2024-03-04T16:55:42.572529Z", "orders": 1, // Orders between 4th and 7th of march (Example) }, -
Retrieve selected Select Option value
I tried to retrieve the selected unit_selector data for the key, value in for loop in the value_row class. but it didn't work. It just didn't display anything. {% if forloop.first %} <tr class="title_row"> {% for k,v,i,z,b in sorted_title_list %} {% if k == selected_item %} {% if b|length == 1 %} {% else %} <th><label for="**unit_selector**"> <select class="master_select" id="**unit_selector**" name="unit_selector"> {% for key, value in b.items %} <option value="{{ value }}" id="{{ key }}">{{ value }}</option> {% endfor %} </select> </label></th> {% endif %} {% endif %} {% endfor %} </tr> {% endif %} <tr class="**value_row **{% if epoch_form.errors %}error{% endif %}"> {% for k,v,i,z,b in sorted_title_list %} {% if k == selected_item %} {% if b|length == 1 %} {% else %} {% for key, value in b.items %} {% if unit_selector.key == key %} <td class="_unit" id="{{ key }}">{{ value }}</td> {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </tr> -
Django backend with celery workers - memory threshold
I have a system with some periodic tasks. Each periodic task reads in files and creates objects out of them in the RAM. To prevent data loss, the cached file content is immediately stored from the peridoic task into the database after creating the object out of it. Then the file is deleted from the source. The object is queued into a RabbitMQ and the Celery workers take them for further processing and concurrency. Before caching the next file, the memory usage of the system is fetched with psutil. If it exceeds a threshld, the periodic task stops to read in files and continues with it, when executed the next time. My question is If this is generally a feasible approach if no data must be lost (the files are either stored in the database or still in the source folder) If it is a good approach to keep the synchronisation effort low (files are deleted after reading, the worker operates on objects and does not delete files and there is no sync needed with the periodic task) Which memory threshold is "safe" and fast enough. The file size can be up to 40 MB. -
Signup & Login not working in production in DigitalOcean using DjangoRestFramework and getting server error 500
-I followed the DigitalOcean Documentation to upload my Django app to digitalOcean: https://docs.digitalocean.com/developer-center/deploy-a-django-app-on-app-platform/ And I served my static files and media files using DigitalOcean space and all is good and I can make all of my requests in production but Login & Sign up is only working in my local machine but not in DigitalOcean Server I'm getting server error 500 this is my configuration : settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) # set debug to false by default DEBUG = os.getenv("DEBUG", "False") == "True" ALLOWED_HOSTS = os.getenv( "DJANGO_ALLOWED_HOSTS", "www.aklalatshop.com,https://akalat-shopcsphu.ondigitalocean.app").split(",") # Application definition INSTALLED_APPS = [ # 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'egystoreapp', # For generating / getting access token 'oauth2_provider', 'social_django', ######################################## 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', # for social login 'rest_framework_social_oauth2', # for digitalOcean space 'storages', 'bootstrap4', 'rest_framework', 'rest_framework.authtoken', ] SITE_ID = 1 MIDDLEWARE = [ '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', 'whitenoise.middleware.WhiteNoiseMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'egystores.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', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'egystores.wsgi.application' DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", … -
Best way to update multiple templates based on form submission?
I'm working on a project that does several calculations based on user input, and I am now trying to create a new form in my variables_input template where the user can retrieve the values used in prior runs, and this works on the variables_input template resulting with the values being displayed on the page. However when the user goes to another page the values displayed are the most recently run calculations. How do I make it so when the user chooses a past run that they don't have to run the calculations but just get the values from the appropriate models to be displayed on the appropriate page? I was wondering if signals could achieve the desired result or if a simpler solution is possible. Below is an example of my project's code. variables_input.html {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" , value="Submit" name="prior_run"> </form> <form action="" method="post"> <h2>Variables Table One</h2> {% csrf_token %} <!-- Table Columns --> <table> <table class="vartable" style="text-align: center;"> <colgroup> <col class="grey"> </colgroup> <thead> <tr> <th>Variable 1</th> <th>Variable 2</th> <th>Variable 3</th> <th>Variable 4</th> <th>Run Name</th> <th></th> </tr> </thead> <tbody> <tr> <div> <td><input type="text" value="{{inputs_list.0}}" name="var_one"></td> <td><input type="text" value="{{inputs_list.1}}" … -
encountering so many errors during web application deployment in firebase
I have successfully deployed my django web application into firebase. But when I did run the hosturl the website I deployed was only able to display html content and images but couldn't display the content as I registered it should in css,js, bootsrap files.it completely could not access these files but it could access the image files which present in the same directory which is static which is within public directory.which is default directory created by firebase during firebase init process.Could you help me in solving this error.or atleast let me know what error could it be. i deployed web application in firebase to host it.for this i put my html file in public directory which basically created by firebase itself during firebase initialization.and i put static files like js,img,css,bootstrap in static directoru which is within the public directory.and the error after the deployement when i did run the hosturl it did not display the website properly means it did nto display as i registered ti should be in js,css,bootstrap files.becoz it could not access that files whereas ti could access the image files which are in same directory where js,css,bootstrap files does exist. -
AttributeError at /login/ 'AnonymousUser' object has no attribute '_meta'
im trying to create my own costume view for the login page and im getting the following error. this is my views: def my_view(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) login(request, user) return reverse_lazy('HomeView') this is the urls: urlpatterns = [ path('', HomeView.as_view(), name='HomeView'), path('show_todo_list/<int:pk>', ShowToDoView.as_view(), name='Show_To_Do_list'), path('create_task/', CreateTaskView.as_view(), name='Create_Task'), path('change_task/<int:pk>', ChangeTaskView.as_view(), name= 'Change_Task'), path('delete_task/<int:pk>', DeleteTaskView.as_view(), name= 'Delete_Task'), path('login/', my_view, name='login') ] and the error is in line 34: login(request, user) AttributeError: 'AnonymousUser' object has no attribute '_meta' -
MySQLdb.OperationalError: and django.db.utils.OperationalError 1054, "Unknown column" after field rename in Django and MySql
I have django app that is connected to MySql database. I have renamed the field in models.py and succesfuly ran the migration. (the name alteration is written in migrations file) I have also manually altered the field in the MySql, so it's called the same as in models.py (let's say it's called 'newName'); After trying to run new migrations i get MySQLdb.OperationalError: and django.db.utils.OperationalError1054, "Unknown column 'oldName' in 'mysql_tableName'" What should I do? Why does django db connection have oldName of the field? inspectdb shows the new field name in the output; when checking mysql, there is new name of the field, running the sql command in db (SELECT oldName FROM mysql_tableName) works fine. -
Optimizing Image Filtering and Color Selection in Django Product Display
I created three models In Models.py: class Color(models.Model): name=models.CharField(max_length=20) code=ColorField(default='#FF0000') def __str__(self): return self.name class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL ,null=True) color = models.ForeignKey(Color, on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" So In my admin pannel Under Product Model it is creating two subparts one is General and other is Product Images--->Product model view and the product images will look like this--->Product Images In the General section I am uploading the main product image <div class="left-column"> {% for p in products %} {% for c in colors %} {% for x in p_image %} <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#1 <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#2 <img data-image="{{c.id}}" class="active" src="{{p.image.url}}" alt=""> #3 {% endfor %} {% endfor %} {% endfor %} </div> And displaying the main image in the frontend by #3 html code and I also want to display other images.My product detail page will … -
why Django upload a file to server failed
if request.method == 'POST': k = request.FILES obj = request.FILES['upload'] t = int(time.time()) jobid = 'jobid'+str(t) job_name = jobid + '_' + obj.name print(job_name) fr = open('prediction/PanPep/upload/' + job_name, 'wb+') i used request.FILES to get a uploaded file and create this file on my server. It was fine when I uploaded the first file. But then i get an error when you i to create the file. this is error: FileNotFoundError: [Errno 2] No such file or directory: 'prediction/PanPep/upload/jobid1709638360_Example_zero-shot.csv' [05/Mar/2024 19:32:40] "POST /panpep/ HTTP/1.1" 500 67598 It seems to be due to some kind of conflict,how to explian this phenomenon and how i fix it. Thanks in advance! -
Page not found (404) Request Method: GET Request URL: http://18.222.182.68/index.html Using the URLconf defined
My main page loads fine, but then when i click a button that's supposed to take me to index.html i get the error posted below. When running this locally it works fine, but when depolying onto AWS (EC2, using nginx and gunicorn) its not working and giving me the error below. im new to using django and AWS, any feedback is appreciated. error: Request Method: GET Request URL: http://18.222.182.68/index.html Using the URLconf defined in LectureLingo.urls, Django tried these URL patterns, in this order: [name='index'] admin/ The current path, index.html, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. views.py code def index_view(request): return render(request, 'index.html') urls.py code from django.urls import path from . import views urlpatterns = [ path('', views.index_view, name='home'), path('index/', views.index_view, name='index'), ] Main urls.py code from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('', include('transcript.urls')), path('admin/', admin.site.urls), ] index.html code {% load static %}<!DOCTYPE html> <html> <head> <title>Chat</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" href="{% static 'indexstyles.css' %}"> </head> <body> <p id="status">Connection status will go here</p> <div class="custom-tooltip" style="display:none;"></div> … -
Facing error on loading Ml Model through PipelineModel.load(model_location) in Django app
Hello I am using django application which has both asgi and wsgi modes. Now when I load the model in a standalone script it loads without any error but when I load it through an api call in django to perform task it gives an error: File "/mnt/d/InnovativeSolutions/DataAnalytics/DataAnalyticsDataTransformation/env2/lib/python3.10/site-packages/pyspark/ml/param/__init__.py", line 276, in <listcomp> src_name_attrs = [(x, getattr(cls, x)) for x in dir(cls)] AttributeError: __provides__ Code: from pyspark.ml import PipelineModel pipeline_model: PipelineModel = await PipelineModel.load(model_location) I have tried making the root method that is loading the ml model into an asynchronous type but still facing the same error. The standalone script loads the model without any error. -
Optimizing Image Filtering and Color Selection in Django Product Display
I created three models In Models.py: class Color(models.Model): name=models.CharField(max_length=20) code=ColorField(default='#FF0000') def __str__(self): return self.name class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL ,null=True) color = models.ForeignKey(Color, on_delete=models.CASCADE) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" So In my admin pannel Under Product Model it is creating two subparts one is General and other is Product Images--->Product model view and the product images will look like this--->Product Images In the General section I am uploading the main product image <div class="left-column"> {% for p in products %} {% for c in colors %} {% for x in p_image %} <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#1 <img data-image="{{c.id}}" src="{{x.image.url}}" alt="">#2 <img data-image="{{c.id}}" class="active" src="{{p.image.url}}" alt=""> #3 {% endfor %} {% endfor %} {% endfor %} </div> And displaying the main image in the frontend by #3 html code and I also want to display other images.My product detail page will … -
Sign up doesnt work when i include the firstname and last name in django
I created my signUp template at first with email, username, and password fields and a user was able to signUp successfully, But when i added the first_name, Last_Name and Phone fields I started getting a MultiValueDictKeyError evrytime a user tries to signup... I'm requesting for help on this😭😭😭😭 def signup(request): if request.method == "POST": first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] phone = request.POST['phone'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if User.objects.filter(username = username).exists(): messages.error(request,"Username already exists.") return render(request, 'registration\signup.html') elif User.objects.filter(email = email).exists(): messages.error(request,"email already exists.") return render(request, 'registration\signup.html') else: NewUser = User.objects.create_user(first_name, last_name,username, email, password,phone) NewUser.save() messages.success(request, "Your account has been successfully created you will be redirected to the login page") return redirect('home') else: messages.error(request,"Passwords do not match.") return render(request, 'registration\signup.html') return render(request, 'registration\signup.html') this is the form <div class="row "> <div class=" form_container col-5 my-1 " style=" height: 500px; border: 2px solid rgb(10, 43, 151); border-radius: 5px;margin-left: 30%;"> <form class="overlay" action="{% url 'signup' %}" method="post" style="background-color:trasparent;border-radius: 5px;margin-left: 0%;"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <label style="color: aliceblue;" for="fisrt_nam">First Name</label> <input type="text" id="fisrt_nam" class="form-control" name="fisrt_name" placeholder="fisrt name" required> </div> </div> <br> <div class="col-md-6"> <div class="form-group"> <label … -
Django 5 and Py 3.11.1 support for field encryption [closed]
A Customer want to have a field encryption for his Django Backend. Backend is running on Django 5 and Python 3.11.1. E2E Encryption from frontend side is currently not possible. I know that field encryption make his application not really more safe but I guess thats just requirements for marketing and the good feeling for the clients. Of cource we do everything possible to protect the System around from common attacks. My Problem is now that I can't find a Library that officially suports field encryption with Django 5 and Python 3.11.1. We run PSQL so a lib with pg_crypto support would be nice. I dont really like the idea to use an old library for such an important feature. I'm afraid to destroy my data when Security and Bug Fixes are not longer suported for the current version I'm working on. I searched several libraries and didn't found any hint for django 5 or python 3.11.1 support. Even the core library cryptography says nothing about 3.11.1 support. -
How to host my reactjs and django application on go daddy
I have a web application which uses reactjs for the frontend and django for the backend. I want to now host this on go daddy. I have a domain purchased as well as a hosting plan. I am just very confused on where to upload all my files. Any help would be appreciated -
How to use ManyToManyField for self class
I have one Model inside my models.py named Account In this case I wanna create a field in which I can choose my own Model Objects. for example if I had 3 Accounts {Jack, Harry, Helena} I want to choose the accounts I want between them. Actually I just want to create a Following System. Jack can follow Harry and Helena & also Helena can follow Jack or Harry How can I do that guys? Account class inside models.py class Account(models.Model): username = models.CharField(max_length=100) following = models.ManyToManyField(**Account**, blank=True) -
Private/offline LLM Chatbot on trained data
I have created a Django project with one model. And from admin portal, I will add the question and response which inserts data into postgres DB. Now, I'm trying to create an LLM chatbot for questioning and answering purpose on Postgres data and The user should be able to ask questions and chatbot must answer based on DB data. And, I am want to do with with any private/offline LLM model to secure it. I see, this can be achieved with Llama, Hugging face. But, not able to find any proper document/link to implement this. I am new to this. Can someone help to share links or any suggestions on this ? -
Django - Authentication using only a password
I need to implement authentication using only a password. I know that for security reasons this is not recommended, but I need this approach because it logs in using only RFID codes. I could treat this code as a regular field (not a password) and just retrieve the user with this code, but I want to hash this value so I iterate through all users using check_password. [models.py] class CustomUserManager(BaseUserManager): def create_user(self, password=None, **extra_fields): user = self.model(**extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(**extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return self.username @property def full_name(self): return f'{self.first_name} {self.last_name}' [views.py] def login_view(request): if request.user.is_authenticated: return redirect(reverse('home')) if request.method == 'POST': password = request.POST.get('rfid_code') user = authenticate(request, password=password) if user is not None: login(request, user) return redirect(settings.LOGIN_REDIRECT_URL) return render(request, 'account/login.html') [backend.py] class CustomAuthenticationBackend(BaseBackend): def authenticate(self, request, password=None): try: User = get_user_model() for user in … -
How can i run the existing Django project in my mac
I am trying to run the Django project in my machine and i have cloned it. Now i directly run the the Project by python3 manage.py runserverand after that i got the error like this 192:vehiclerent vishal$ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/threading.py", line 1052, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/threading.py", line 989, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1381, in _gcd_import File "<frozen importlib._bootstrap>", line 1354, in _find_and_load File "<frozen importlib._bootstrap>", line 1318, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mathfilters' Can anyone help how can i resolve this and explain what's happening. -
Issue with Registration: User Data Not Saving to Database (Django)
I've developed registration functionality for my web application using a combination of form elements, a view, a registration template, and JavaScript modals. However, despite completing the registration process, the user data is not being saved to the database as expected. Details: Form: I have implemented a form for user registration. View: A corresponding view function handles the registration process. Template: I've created a registration template for rendering the registration form. JavaScript Modals: Modal dialogs are used for user interaction during the registration process. Problem Statement: When I submit the registration form, the user data does not get stored in the database. I've verified that the form submission is successful, but somehow the data isn't persisting. Expectation: Upon successful submission of the registration form, the user data should be saved to the database for future reference and authentication purposes. Request for Assistance: I'm seeking guidance on what could be causing this issue and how to troubleshoot it effectively. Any insights, suggestions, or potential solutions would be greatly appreciated. Thank you! My code: Base code, containing JavaScript modals: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" … -
Custom system checks are getting ignored
Recently, I implemented a custom system check in our project. This check performs assertions based on our custom implementation of Django Rest Framework's model serializers. For debugging purposes on Visual Studio Code, I am using the debugpy package in conjunction with a Docker Compose setup. I followed this article to set it up. After configuring the debugger, I noticed that my custom system checks were not functioning properly. Upon further troubleshooting, I realized that it was due to a configuration I made in the manage.py file as mentioned in the article. In the article, they recommend adding the following code block to the manage.py file: # start new section from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 3000)) print('Attached!') # end new section However, when this code block is present, my custom system checks are completely ignored. If I comment out or remove this code and save the file, the system checks are triggered successfully. I'm unsure why this issue is occurring. Has anyone else encountered a similar problem where custom system checks were being ignored? Thank you in advance for your assistance.