Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn not starting even after succesfully configuring all files
I am working on a particular Django project (Don't know if this makes a difference but the service provider is Hostinger).. The deployment of the same is to be done on a vps server with ubuntu in it. Using gunicorn and nginx is what I have planned , but I keep on running into 502 bad gateway error On poking around found that gunicorn is not starting The following is the error received when I ran sudo systemctl status gunicorn Error : × gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2024-01-02 07:53:47 UTC; 4 days ago TriggeredBy: ● gunicorn.socket Main PID: 6153 (code=exited, status=203/EXEC) CPU: 1ms Jan 02 07:53:47 srv457341 systemd[1]: Started gunicorn daemon. Jan 02 07:53:47 srv457341 systemd[6153]: gunicorn.service: Failed to execute /root/Assistanza/Assistanza/env/bin/gunicorn: No such file or directory Jan 02 07:53:47 srv457341 systemd[6153]: gunicorn.service: Failed at step EXEC spawning /root/Assistanza/Assistanza/env/bin/gunicorn: No such file or directory Jan 02 07:53:47 srv457341 systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Jan 02 07:53:47 srv457341 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 02 07:53:47 srv457341 systemd[1]: gunicorn.service: Start request repeated too quickly. Jan 02 07:53:47 srv457341 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 02 … -
django allauth adding uuid field
I'm trying to add a field for user uuid for sigup but after adding AUTH_USER_MODEL = "aihuser.UidUser" I'm getting errors on makemigrations even I deleted all migrations and drop the database and I created new database : root@5ce3411a2490:/wg_aihalbum_01# python manage.py makemigrations Wagtail version is : 4.1.9 DEV environment hook : register_rich_text_handlers Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/wagtail_modeltranslation/management/commands/makemigrations_translation.py", line 29, in handle super(Command, self).handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 195, in handle autodetector = MigrationAutodetector( File "/usr/local/lib/python3.8/site-packages/wagtail_modeltranslation/management/commands/makemigrations_translation.py", line 12, in wrapper from_state_page = from_state.apps.get_model('wagtailcore', 'page') File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.8/site-packages/django/db/migrations/state.py", line 566, in apps return StateApps(self.real_apps, self.models) File "/usr/local/lib/python3.8/site-packages/django/db/migrations/state.py", line 637, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field account.EmailAddress.user was declared with a lazy reference to 'aihuser.uiduser', but app 'aihuser' isn't installed. The field admin.LogEntry.user was declared with a lazy reference to 'aihuser.uiduser', but app 'aihuser' isn't installed. The field … -
How can I setup my container Django app in Azure so it doesn't crash?
Sometimes, my Python Django app in Azure crashes. The error I get is this: upstream connect error or disconnect/reset before headers. retried, and the latest reset reason: remote connection failure, transport failure reason: delayed connect error: 111 I haven't been able to figure out what's causing it. Any help is appreciated. Thanks. -
how can disable send email automatically in reset password (PasswordResetView) django
this is my views.py class CustomPasswordResetView(PasswordResetView): template_name = 'users/password_reset_form.html' success_url = reverse_lazy('password_reset') def form_valid(self, form): email = form.cleaned_data['email'] # Check if the user with the provided email exists and is active try: user = User.objects.get(email=email, is_active=True) except User.DoesNotExist: messages.success(self.request, 'ok.') return super().form_valid(form) # Return the default behavior if user doesn't exist or is inactive # Generate uidb64 and token uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) token = default_token_generator.make_token(user) print(email, uidb64, token) messages.success(self.request, 'ok.') return super().form_valid(form) and this is my urls.py urlpatterns = [ path('password_reset/', CustomPasswordResetView.as_view(), name='password_reset'), path('reset/<uidb64>/<token>/', CustomPasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', CustomPasswordResetCompleteView.as_view(), name='password_reset_complete'), ] and this is my settin.py : EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = '*****' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '*****' AUTH_USER_MODEL = 'users.User' ACCOUNT_EMAIL_CONFIRMATION_MODEL = 'users_custom.CustomEmailConfirmation' when i enter email adress for reset password in users/password_reset_form.html , djnafo automatically send email and i can see it in console like : You're receiving this email because you requested a password reset for your user account at http://127.0.0.1:8000. Please go to the following page and choose a new password: http://http://127.0.0.1:8000/users/reset/MQ/c0exppa87e20490eb2e3c11513cad273efc4cc/ Your username, in case you’ve forgotten: a@a.com Thanks for using our site! The http://127.0.0.1:8000 team how can i disable this ? -
The difference between __call__ and other methods in Django middleware
Why do we use Django middleware predominantly for? I’m relatively new to Django, so I’m trying to understand the difference between __call__ and process_view() or process_request() methods. As I see, we use __call__ before the request was filtered through every middleware in Django and to determine what method to use either process_view() or process_request()? -
Comment form is not valid?
I'm working on a Django project, I'm implementing comments. For some reason I cannot post comments, it's showing like my form is not valid. Please see code and see where I made mistake. I created that you can only post comment if you are registered and logged in user. If you are not logged it you will not see the field to post comment. When I log in and when I want to post comment, I'm able to write and post comment, but when I click button post comment I get message You need to be logged in to add a comment.. I'm not sure why this is happening, any ideas? views.py def lesson_detail(request, year, month, day, lesson): lesson = get_object_or_404(Lesson, status=Lesson.Status.PUBLISHED, slug=lesson, publish__year=year, publish__month=month, publish__day=day) #comments comments = lesson.comments.all().filter(hide_comment=False) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment=comment_form.save(commit=False) new_comment.lesson = lesson new_comment.author = request.user new_comment.save() return redirect(lesson.get_absolute_url()) #redirect here else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author':request.user}) else: comment_form = CommentForm() # List of similar posts lesson_tags_ids = lesson.tags.values_list('id', flat=True) similar_lessons = Lesson.published.filter(tags__in=lesson_tags_ids).exclude(id=lesson.id) similar_lessons = similar_lessons.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] lesson_detail_url = reverse('lang_learning_app:lesson_detail', args=[lesson.publish.year, lesson.publish.month, lesson.publish.day, lesson.slug]) … -
Bootstrap modals not displaying content on button click (Django Framework)
I'm encountering an issue with Bootstrap modals in my HTML code where they are not displaying any content when I click the buttons triggering them. Despite seemingly correct IDs and attributes, the modals remain empty on clicking the buttons. Here's the relevant portion of my HTML code: <tbody> {%for coder in coders %} <tr> <td>{{coder.coder_number}}</td> <td>{{coder.first_name}}</td> <td>{{coder.last_name}}</td> <td>{{coder.lc_id}}</td> <td>{{coder.rating}}</td> <td> <button type="button" class="btn btn-success me-1" href="{% url 'view_coder' coder.id %}" data-bs-toggle="modal" data-bs-target="#myModal{{coder.id}}"> <i class="fa-solid fa-circle-info"></i> </button> <!-- modal --> <div class="modal" id="#myModal{{coder.id}}" tabindex="-1" aria-labelledby="myModalLabel1" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> coder: {{coder.first_name}} {{coder.last_name}} </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true"></span> </button> </div> <div class="modal-body"> <ul class="list-unstyled"> <li>S.No. <strong>{{coder.coder_number}}</strong></li> <li>Name: <strong>{{coder.first_name}} {{coder.last_name}}</strong></li> <li>Leetcode Id: <strong>{{coder.lc_id}}</strong></li> <li>Rating <strong>{{coder.rating}}</strong></li> <!-- <li>S.No. <strong>{{coder.coder_number}}</strong></li> --> </ul> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> </td> </tr> {% endfor %} </tbody> ` [enter image description here](https://i.stack.imgur.com/KNsal.png) i want this type of result stuck on this since 6hrs enter image description here -
How do I determine why a Bootstrap 5 Modal button is not working?
I have a Django based web site that uses bootstrap 5. I have a table of data and a notes column with a lot of text. I am trying to use the Bootstrap Modal popup feature to display the notes to keep the table smaller. The long notes text makes the table hard to read. When I say long notes, I mean about 15-25 words. When I click the button "Read the notes", the modal does not appear. My html: {% for f in flights %} {% for flight in f.flight_data %} <!-- Modal --> <div class="modal fade" id="{{ flight.flight_id }}" tabindex="-1" role="dialog" aria-labelledby="{{ flight.flight_id }}Label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="{{ flight.flight_id }}Label">Notes for the flight of the {{ flight.name }}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ flight.notes|safe }} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <!--<button type="button" class="btn btn-primary">Save changes</button>--> </div> </div> </div> </div> {% endfor %} {% endfor %} {% for f in flights %} <div class="row mt-4"> <div class="col-12"> <div class="card mb-4"> <div class="card-header pb-0"> <p class="mb-1 pt-2 text-bold">{{ f.date }}</p> <h5 class="font-weight-bolder">{{ f.teacher_name }}</h5> </div> <div class="card-body px-0 pt-0 pb-2"> <div class="table-responsive p-0"> … -
expo error "possible undandled promise rejection"
I am making an app using react-native with expo and django rest-framework, this error appears when I want to fetch the data from my database, I leave below how I take the data from my localhost to see if someone can solve it, try using the android studio emulator and a personal device and the same error occurs. EXPO ERROR import React, { useState, useEffect } from "react"; import { View } from "react-native"; import DataList from "../components/data-list"; const ListScreen = ({ navigation }) => { const [data, setData] = useState([]) useEffect(() => { fetchData() }, []) const fetchData = async() => { const response = await fetch('http://127.0.0.1:8000/api/prices/') const data = await response.json() setData(data) } return( <View> <DataList data={data}/> </View> ); } export default ListScreen It works correctly for another person with this same code, but it doesn't work for me in particular. :( -
Django: How to get a muttable object from get_object_or_404 in django?
I'm using Django==4.2 and after using get_object_or_404 function in my view I get an immutable object. result = get_object_or_404(MyModel, id=id) And I need to pass this "result" to my form (in post method): request.POST["result"] = result However, on post I'm getting this error: This QueryDict instance is immutable I've tried to do something like result = result.copy() to make it mutable but it didn't work. So, what should I do to make the "result" mutable, so I can pass it to the form? Thanks! -
How can I pass this javascript game score into a Django Model?
right now i need to make a website that has his own games. Currently everything is working fine, but I need to know how I can store the high score then to a django model. My Idea is a hidden POST form, which gets triggered automatically(currently even manual would be enough), and then it just submits the integer stored in a JavaScript variable via the POST form to the model. I will provide you with my current Code snippets, so you will know how far I am and how I am approaching. views.py def loadGame(request, slug): game = Game.objects.get(slug=slug) if request.method == 'POST': pass return render(request, 'main/game-detail.html', { 'game': game }) my hidden form in the template <form action="/games/{{ game.slug }}" method="post"> {% csrf_token %} <button type="submit" hidden>Upload your highscore to the Leaderboard?</button> </form> models.py model for the leaderboard class Ranking(models.Model): player = models.ForeignKey(User, on_delete=models.CASCADE) game_overall_score = models.IntegerField(null=True) var score = 0; ... if (pipes[i].hits(bird)) { score = 0; pipes = []; return; } ... if (frameCount % 5 == 0) { score++; } I actually don't even know where to start. I looked up multiple approaches with jQuery or AJAX, but no one had the same situation like me, … -
Error: matching query does not exist (Django/Python/JS-RatingApp)
As a beginner, I'm working on a Django rating application. The uploaded pdf files get displayed on a rating site, where one can give two star-ratings. When there was only one rating option, everything worked fine. Now that I added the second one and changed some js code, none of them works anymore. pls help:) my models: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Rating(models.Model): file = models.FileField(upload_to='images/', null=True) relevanz = models.IntegerField(default=0, validators=[ MaxValueValidator(6), MinValueValidator(0), ] ) richtigkeit = models.IntegerField(default=0, validators=[ MaxValueValidator(6), MinValueValidator(0), ] ) def __str__(self): return str(self.pk) my views: from django.shortcuts import render from .models import Rating from django.http import JsonResponse # Create your views here. # def main_view(request): # obj = Rating.objects.filter(score=0).order_by("?").first() # context ={ # 'object': obj # } # return render(request, 'ratings/main.html', context) def main_view(request): objs = Rating.objects.all() return render(request, 'ratings/main.html', {'objs':objs}) def rate_relevanz(request): if request.method == 'POST': el_id = request.POST.get('el_id') val = request.POST.get('val') print(val) obj = Rating.objects.get(id=el_id) obj.relevanz = val obj.save() return JsonResponse({'success':'true', 'relevanz': val}, safe=False) return JsonResponse({'success':'false'}) def rate_richtigkeit(request): if request.method == 'POST': el_id = request.POST.get('el_id') val = request.POST.get('val') print(val) obj = Rating.objects.get(id=el_id) obj.richtigkeit = val obj.save() return JsonResponse({'success':'true', 'richtigkeit': val}, safe=False) return JsonResponse({'success':'false'}) html: {% extends "base_rate.html" %} {% … -
How to optimize objects.all() database query?
If I will use videos = Videos.objects.all() and then paginator = Paginator(videos, 9) an I have 1 000 000 records, then Videos.objects.all() will make a query SELECT * FROM...? Is it a proper way? Or I have to use LIMIT parameter query to paginate properly? -
how to solve this pythonanywhere error , i tried many time
2024-01-06 15:41:00,849: Error running WSGI application 2024-01-06 15:41:00,854: ModuleNotFoundError: No module named 'officialthiruth.settings' 2024-01-06 15:41:00,854: File "/var/www/fathu856_pythonanywhere_com_wsgi.py", line 10, in 2024-01-06 15:41:00,855: application = get_wsgi_application() 2024-01-06 15:41:00,855: 2024-01-06 15:41:00,855: File "/home/fathu856/.virtualenvs/mysite-virtualenv/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2024-01-06 15:41:00,855: django.setup(set_prefix=False) 2024-01-06 15:41:00,855: 2024-01-06 15:41:00,856: File "/home/fathu856/.virtualenvs/mysite-virtualenv/lib/python3.10/site-packages/django/init.py", line 19, in setup 2024-01-06 15:41:00,856: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2024-01-06 15:41:00,856: 2024-01-06 15:41:00,856: File "/home/fathu856/.virtualenvs/mysite-virtualenv/lib/python3.10/site-packages/django/conf/init.py", line 89, in getattr 2024-01-06 15:41:00,856: self._setup(name) 2024-01-06 15:41:00,856: 2024-01-06 15:41:00,856: File "/home/fathu856/.virtualenvs/mysite-virtualenv/lib/python3.10/site-packages/django/conf/init.py", line 76, in _setup 2024-01-06 15:41:00,856: self._wrapped = Settings(settings_module) 2024-01-06 15:41:00,857: 2024-01-06 15:41:00,857: File "/home/fathu856/.virtualenvs/mysite-virtualenv/lib/python3.10/site-packages/django/conf/init.py", line 190, in init 2024-01-06 15:41:00,857: mod = importlib.import_module(self.SETTINGS_MODULE) 2024-01-06 15:41:00,857: *************************************************** 2024-01-06 15:41:00,857: If you're seeing an import error and don't know why, 2024-01-06 15:41:00,857: we have a dedicated help page to help you debug: 2024-01-06 15:41:00,858: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2024-01-06 15:41:00,858: *************************************************** desplaying like this -
Error with postgres when using the `docker compose up` command (Django, Ubuntu 22.04)
Error: django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "172.18.0.3", user "postgres", database "postgres", no encryption My settings: settings/prod.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } docker-compose.yml: services: db: image: postgres:14.5 restart: always volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "python", "/code/educa/manage.py", "runserver", "0.0.0.0:8000"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=educa.settings.prod - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db Dockerfile: FROM python:3.10.6 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code RUN pip install --upgrade pip COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ I've already tried going to bash to change pg_hba, but it says nano not found, vim not found, and so on. root@428882cf46ed:/var/lib/postgresql/data# nano pg_hba.conf bash: nano: command not found root@428882cf46ed:/var/lib/postgresql/data# sudo nano pg_hba.conf bash: sudo: command not found I also changed pg_hba.conf via the terminal by entering the following lines in this file: host all all 172.18.0.3/32 trust But that didn't solve the problem -
problem with passing dynamic path parameter to a component funtion
views: *i use this function as a render partial urls: url: http://127.0.0.1:8000/products/cat/lundury/ i should be able to get the cat parameter wich is a path parameter with pasing it to the function. but i get this eror : TypeError at /products/cat/lundury/ Product_tags_component() missing 1 required positional argument: 'cat' i will be really thankful if any one help me. -
Python, Django: 'Videos' object is not iterable, for video in chunk
How to fix that error? In template C:\Users\webst\webstudioamerica\webstudio\templates\index.html, error at line 441 Python: 'Videos' object is not iterable This code is not working: 439 {% for chunk in videos|slice:":3" %} 440 <div class="row"> 441 {% for video in chunk %} 442 <div class="col-xs-12 col-lg-4"> 443 <div class="video-container"> 444 <iframe class="video" src="{{ video.video_id }}" allowfullscreen></iframe> 445 </div> 446 </div> 447 {% endfor %} 448 </div> 449 {% endfor %} This one is working: {% for video in videos %} <li>{{ video.video_id }}</li> {% endfor %} views.py is the same: from django.shortcuts import render from .models import Videos def index(request): videos = Videos.objects.all() return render(request, 'index.html', {'videos': videos}) -
# Cloudinary not displaying static files when displayed to heroku, despite Cloudinary collecting from IDE. Issue between Cloudinary and Heroku?
Cloudinary not displaying static files when displayed to heroku. Issue between Cloudinary and Heroku? see deployed URL https://coach-matrix-d2cd1e717f81.herokuapp.com/ask_question/ This was previously an issue documented here, but much of the debugging steps seem irrelevant now I have reached the working theory that Cloudinary is installed correctly on my Django IDE, and the issue in fact lies between Cloudinary and Heroku settings. Key points at a glance. on Heroku, I am expecting to see the django-quill WYSIWYG editor displaying just like in the localhost, however I get no box and instead these error messages in console. what makes this particularly challenging is that there are no obvious errors on localhost. Numerous editors have been installed - Summernote, CKEditor, working perfectly on localhost and having deployment issue. Cloudinary does seem to be implemented successfully in settings.py and env.py - confirmed as working by many peers. [omitted here for readability] python3 manage.py collectstatic command appears to work with no issues, returns a statement Looking at the error message, it mentions an issue with MIME production version seem to be looking for the files locally (on Heroku) instead of on Cloudinary. Refused to apply style from 'https://coach-matrix-d2cd1e717f81.herokuapp.com/static/django_quill/django_quill.css' because its MIME type ('text/html') is not a … -
Shoe the image URL on Update page of the Crud
this is a template page of a Edit Page of crud, when we render this edit page all fields which are already uploaded will be shown except the image, how can we see the already uploaded image in image field, hope you guys got that. <body> <div class="row"> <div class="col-sm-4"> <h1 class="text-center alert alert-info">Modify Order Details</h1> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="category">Select a Category :- </label> <select name="category" id="category"> <option value="None"selected >None</option> <option value="Tshirt" {% if products.category == 'Tshirt' %} selected {% endif %}>Tshirt</option> <option value="Jeans" {% if products.category == 'Jeans' %} selected {% endif %}>Jeans</option> <option value="Jacket" {% if products.category == 'Jacket' %} selected {% endif %}>Jacket</option> <option value="Shoes" {% if products.category == 'Shoes' %} selected {% endif %} >Shoes</option> <option value="Watch" {% if products.category == 'Watch' %} selected {% endif %} >Watch</option> </select> <br><br> <label for="product_name">Select a Product: </label> <select name="product_name" id="product_name" value="{{products.product_name}}" > <option value="{{products.product_name}}" selected readonly >{{products.product_name}}</option> </select><br><br><br> <label for="product_price">Product Price:</label> <input type="text" id="product_price" class="form-control" name="product_price" value="{{products.product_price}}" pattern="^[^ ].+[^ ]$" title="Please Remove Extra Spaces" required><br> <label for="supplier_images">Image:</label> <input type="file" name="image"></a> <br><br> <!-- <span>Current image:</span> <img src="{{products.image.url}}" alt="" width="40"> --> <br><br> <input type="submit" value="Update" class="btn btn-success"> </form> </div> </div><br><br> <h3><a href="{% url 'supplier_dashboard' %}">Back</a></h3> -
Django Custom Authentication authenticating users incorrectly
So I am trying to build a website using Django where there are two separate user bases, one is user and the other is agent. Now I imported User from from django.contrib.auth.models import User and have a separate model for Agent. Now the problem is, when I enter user credentials into agent sign in page, it is logging me in as an agent even though it is a user instance and returning error 'User' object has no attribute 'slug' because there is no slug in user model. Same is happening when I use agent credentials in the user sign in page. It is logging me in as a user even though there is a separate authentication backend for agents. Incorrect credentials are being shown when incorrect credentials are provided but somehow agent credentials in user sign in are not incorrect credentials and vice versa. How can I fix this? My models.py: from django.contrib.auth.models import User class Agent(models.Model): username = models.CharField(max_length=100) name = models.CharField(max_length=100) email = models.CharField(max_length=100) password = models.CharField(max_length=200) last_login = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) slug = AutoSlugField(populate_from='name') USERNAME_FIELD = 'username' def set_password(self, raw_password): self.password = make_password(raw_password) self.save() def __str__(self): return f'{self.name}' My forms.py: class UserRegisterForm(UserCreationForm): email = forms.EmailField() class … -
Using Crispy Forms with django, error template does not exist at uni_form/uni_form.html
I have ran python3.9 -m pip install django-crispy-forms Then added the following to settings.py: INSTALLED_APPS = [ # default apps excluded 'crispy_forms', 'core.apps.CoreConfig', ] CRISPY_TEMPLATE_PACK = 'uni_form' Then am attempting to use the crispy filter in a template: {% load crispy_forms_tags %} <html> <head> </head> <body> <form action=""> {{form|crispy}} </form> </body> </html> and am getting a TemplateDoesNotExist at /uni_form/uni_form.html error. I am not really what is going on? I see that if you wanted to use the bootstrap version you have to download another package such as django-crispy-forms-bootstrap4 but I am just trying to use the default version, so I think I installed the only necessary package. I've definitely used cripsy forms in a django project before so am not sure what I am forgetting. Thanks for any help with this. -
Best practice for writing views in Django (how to comment params, transferring request out of view and what about messages)
service.py def add_goods_to_cart(goods_id, user, addend): goods = Goods.objects.filter(pk=goods_id).first() if goods: the_goods_already_in_cart = Cart.objects.filter(user=user, goods=goods, order=None).first() if the_goods_already_in_cart: the_goods_already_in_cart.quantity = (the_goods_already_in_cart.quantity + addend) if the_goods_already_in_cart.quantity == 0: the_goods_already_in_cart.delete() else: the_goods_already_in_cart.save() else: Cart.objects.create(user=user, goods=goods, quantity=1) status = 200 else: status = 400 return status views.py class AddToCart(LoginRequiredMixin, View): def post(self, request): goods_id = request.POST.get('goods_id') addend = int(request.POST.get('addend')) assert (addend == 1 or addend == -1) status = add_goods_to_cart(goods_id, request.user, addend) if status == 200: act = "added to cart" if addend > 0 else "removed from cart" messages.add_message(request, messages.INFO, 'Goods "{}" {}.'.format(goods.name, act)) return redirect(request.META['HTTP_REFERER']) else: return HttpResponse("Wrong goods id", status=status) What troubles me: Can I transmit request from views.py to service.py? A view is something that operates on request. In my logic, it is reasonable not to transmit request out of view. Receive data from request, transmit the data to the service. What will create the message? In my logic, it is the responsibility of the view. But the view doesn't know anything about the name of the goods. Look here: this code will not work just because there is no name of the goods for the message. Well, anyway, the architecture of this code stinks. Maybe I should return from … -
RandomizedSearchCV independently on models in an ensemble
Suppose I construct an ensemble of two estimators, where each estimator runs its own parameter search: Imports and regression dataset: from sklearn.ensemble import VotingRegressor, StackingRegressor, RandomForestRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.datasets import make_regression from sklearn.model_selection import RandomizedSearchCV X, y = make_regression() Define two self-tuning estimators, and ensemble them: rf_param_dist = dict(n_estimators=[1, 2, 3, 4, 5]) rf_searcher = RandomizedSearchCV(RandomForestRegressor(), rf_param_dist, n_iter=5, cv=3) dt_param_dist = dict(max_depth=[4, 5, 6, 7, 8]) dt_searcher = RandomizedSearchCV(DecisionTreeRegressor(), dt_param_dist, n_iter=5, cv=3) ensemble = StackingRegressor( [ ('rf', rf_searcher), ('dt', dt_searcher) ] ).fit(X, y) My questions are about how sklearn handles the fitting of ensemble. Q1) We have two unfitted estimators in parallel, and both need to be fitted before ensemble.predict(...) would work. But we can't fit any of the estimators without first getting a prediction from the ensemble. How does sklearn handle this circular dependency? Q2) Since we have two estimators running independent tuning, does each estimator make the false assumption that the parameters of the other estimator are fixed? So we end up with a poorly-defined optimisation problem. For reference, I think the correct way to jointly optimise the models of an ensemble would be to define a single CV that searches over all parameters jointly, … -
Django cache function taking too much time
I need help with the django caching I am using django cache function to cache the currency conversion of a currency for 24 hours, I am using redis for caching and redis is a container at same place as django container in a docker compose file. this is the function `def getExchangeRate(currencyCode: str) -> float: # Define a cache key based on the currency code cache_key = f'exchange_rate_{currencyCode}' # Check the cache first for the exchange rate exchangeRate = cache.get(cache_key) if exchangeRate is None: try: # Fetch the exchange rate from the database exchangeRate = float(ExchangeRate.objects.get(currency__code=currencyCode).rate) # Cache the fetched value with an appropriate TTL (e.g., 24 hours) cache.set(cache_key, exchangeRate, 86400) # 86400 seconds = 24 hours except (ExchangeRate.DoesNotExist, ValueError): # Handle the case where the currency code is not found in the database # or the rate cannot be converted to a float exchangeRate = None cache.close() return exchangeRate` the get function is taking too much time about 1700 ms which is I think way too much The image attached is from atatus monitering which shows the get query is taking alot of time in a transection I needed a currency conversion in my app which use a conversion … -
Error when trying to import shuffle in scikit-learn
I am trying to simply from sklearn.utils import shuffle but I am getting this error: File "D:\research\pape\papertwo\Directional_Partial_Charging\hppo\hppo_noshare.py", line 6, in <module> from sklearn.utils import shuffle File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\sklearn\__init__.py", line 83, in <module> from .base import clone File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\sklearn\base.py", line 19, in <module> from .utils import _IS_32BIT File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\sklearn\utils\__init__.py", line 15, in <module> from scipy.sparse import issparse File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\__init__.py", line 283, in <module> from . import csgraph File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\csgraph\__init__.py", line 185, in <module> from ._laplacian import laplacian File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\csgraph\_laplacian.py", line 7, in <module> from scipy.sparse.linalg import LinearOperator File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\linalg\__init__.py", line 130, in <module> from . import isolve, dsolve, interface, eigen, matfuncs File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 4, in <module> from .iterative import * File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 8, in <module> from . import _iterative ImportError: cannot import name '_iterative' from partially initialized module 'scipy.sparse.linalg.isolve' How should I solve this problem?