Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key
I'm trying to make the patient give a review and a rate but this error pop up when I run migrate the error is django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key: accountss_comments.doctore_id contains a value '1' that does not have a corresponding value in accountss_doctor.user_id. this my models class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50, verbose_name="الاسم ") class Comments(models.Model): created_by = models.ForeignKey( Patient, on_delete=models.CASCADE) doctore = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='comments') # co_email = models.ForeignKey( # User, on_delete=models.CASCADE, related_name='comment') co_body = models.TextField(max_length=400, verbose_name='التعليق') rate = models.IntegerField(default=0) created_dt = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) please if there is any solution write below and explain it because I'm still new to Django I tried so hard to fix but with no result -
Adding extra content in django admin jazzmin index page
I want to add user's count and total post count in my built in django admin (html css cards). Iam using jazzmin for styling my dashboard. I prefer to use context processors to fetch counts. I can't override current admin index page my Django version is 4.1 This is my curent admin panel i want to add the count cards abouve app list -
Django queryset checking existence having unexpected behavior
I have a model like this class Student(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) archived = models.BooleanField(default=False) class Meta: constraints = [ UniqueConstraint( fields=["first_name", "last_name"], condition=Q(archived=False), name="unique_user" ) ] and code like below d = {"first_name": "John", "last_name": "Doe"} students = Student.objects.filter(first_name=d.get("first_name"), last_name=d.get("last_name")) for student in students: """Doing some stuff here""" pass if not students: Student.objects.create(first_name=d.get("first_name"), last_name=d.get("last_name")) I am getting an integrity error from the last line where I call objects.create duplicate key value violates unique constraint "unique_user" DETAIL: Key (first_name, last_name) In the objects.filter() I have two fields that are part of the unique constraint, and I am using the same queryset before the objects.create is called, so this error should not happen unless something going wrong with the queryset. This code is working without issues most of the time. Only once this error was raised. Any idea what is going on ? One possibility is that between the filter query and the create query the object was created and the integrity error was raised from create query. But that was not the case. I checked the db, there was nothing created. Infact there was already data which was created hours before matching these conditions. So the filter query … -
Azure Database for PostgreSQL flexible server Slow with Django
Am using Django to connect to Azure Database for PostgreSQL flexible server but it's very slow, below are the specs of the server : https://i.stack.imgur.com/DnV2y.png As you can see above, the specs are high, but the performance isn't better, in postman when I was hitting to get data it took 34.5 seconds, this is way too much to wait. In my Django code, I tried my best to optimize the queries, and on Heroku, it was super fast, however here on Azure it's extremely slow, what could be done to improve the speed of the server? For more information on Django this is the view.py of the endpoint: @method_decorator(cache_page(60 * 60 * 4), name='get') @method_decorator(vary_on_cookie, name='get') class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.filter(status=APPROVED).select_related( "owner", "grade_level", "feedback").prefetch_related( "bookmarks", "likes", "comments", "tags", "tags__following").prefetch_related("address_views") serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) def filter_queryset(self, queryset): ordering = self.request.GET.get("order_by", None) author = self.request.GET.get("author", None) search = self.request.GET.get("search", None) tag = self.request.GET.get("tag", None) # filter queryset with filter_backends 🖟 queryset = super().filter_queryset(queryset) if ordering == 'blog_views': queryset = queryset.annotate( address_views_count=Count('address_views')).order_by( '-address_views_count') if author: queryset = queryset.filter(owner__email=author).select_related( "owner", "grade_level", "feedback").prefetch_related( "bookmarks", "likes", "comments", "tags", "tags__following").prefetch_related("address_views") if tag: queryset = queryset.filter( tags__name__icontains=tag).select_related( "owner", "grade_level", … -
In Django, can I use a variable passed to a function in order to access and attribute of a model?
I'm trying to create a custom function where one of the variables passed is the name of an attribute of a model. I'm doing this to try to access the underlying value. def tabsums(entity_object, year_object, columntitle): curassetobject = BSAccountType.objects.get(name = "Current asset", company = entity_object) curassetsum = BSSum.objects.get(Q(company = entity_object) & Q(year = year_object) & Q(account_type = curassetobject)).columntitle Essentially, I want columntitle to be a string that matches the model field name so I'm trying to pass the variable as the attribute name to access the underlying value. It's not working as Django/python is looking for the attribute "columntitle" which does not exist, rather than looking to the underlying string. Is there a syntax I can use that will allow Django to utilize the underlying string value that is passed? Thank you very much. -
Pass list dict as params in axios react
I am building a react app. I am trying send list dict as params in axios. I am using Django rest framework as backend and It is showing [] or None every times I send request. App.js function App() { const [currentState, setCurrentState] = useState([{"name": "First", "id": 100}, {"name": "Second", "id": 200},]) const sendRequest = () => { axios.get("/api/", {params: {state: currentState}).then((res) => { console.log(res); }) } return ( <> <b onClick={sendRequest}>Send request</b> </> ) } I am trying to send the whole list dict to backend as params like. [{"name": "First", "id": 100}, {"name": "Second", "id": 200}] But it showing none. in backend I am accessing like views.py class Api(APIView): def get(self, request, *args, **kwargs): data = self.request.query_params.get("state") print(data) return Response({"good"}) I have also tried using paramsSerializer in axios for serialization like :- const sendRequest = () => { axios.get("/api/", { params: { state: currentState }, paramsSerializer: params => { return qs.stringify(params, {arrayFormat: "repeat"}) }, ).then((res) => { console.log(res); }) } but it is still not working. Tried also {arrayFormat: "brackets"}. Any help would be much Appreciated. Thank You -
Is Django db_index helpful in text search queries?
I've a similar model in a Django project: from django.db import models class Book(models.Model): title = models.CharField(verbose_name='Title', max_length=255, db_index=True) authors = models.CharField(verbose_name='Authors', max_length=255, db_index=True) date = models.DateField(verbose_name='Date', db_index=True) In the views I need to do a full text search query like the following: books = Book.objects.filter(Q(title__icontains=query) | Q(authors__icontains=query)) Is the db_index=True actually helping the performances of my query or not? -
Django problem updating date field when updating a record
I have a problem when I try to update a field named date_updated. My intention with the field is that every time a record is updated, the date_updated field of that record should be updated by the date the change is made. That field and one other field I have inside a Base class and then in each of the models I inherit that class to repeat the fields. class Base(models.Model): ... date_updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.date_updated = django.timezone.now() super(Base, self).save(*args, **kwargs) class Meta: abstract = True class OtherClass(Base): ... My intention is that when I update any record in the OtherClass, its date_updated field will be updated. I also tried adding the overwrite of the save method in the OtherClass, but the result is the same. The date is kept after I make the change. I am making the change with .update(**data_to_update) -
TypeError: TestViews.test_fails() missing 1 required positional argument: 'param'
I'm trying to run tests on a django app using selenium + pytest which according to the docs, the below should work import pytest from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium.webdriver import Chrome class TestViews(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.driver = Chrome() @classmethod def tearDownClass(cls): if hasattr(cls, 'driver'): cls.driver.quit() super().tearDownClass() @pytest.mark.parametrize('param', ['param1', 'param2']) def test_fails(self, param): pass However I get: Creating test database for alias 'default'... Found 1 test(s). System check identified no issues (0 silenced). Error TypeError: TestViews.test_fails() missing 1 required positional argument: 'param' Destroying test database for alias 'default'... more details more details more details more details more details more details more details more details -
Django file upload is not uploading the file?
I have created a file upload something like this: DataUpload is the view that handles template rendering and handle_uploaded_file is the function that reads the file. View.py def DataUpload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print(request.FILES['file']) handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'DataBase/upload.html', {'form': form}) def handle_uploaded_file(f): with open(os.getcwd()+f, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) url url(r'DataUpload', views.DataUpload, name='DataUpload'), forms.py from django import forms class Rand_Frag_From(forms.Form): Seq = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Tropomyosin beta chain '}),required=False) Acc = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'P02671 '}), required=True) class UploadFileForm(forms.Form): file = forms.FileField() template {% load static %} <link rel="stylesheet" href="{% static 'css/table/custom.css' %}"> <div class="main"> <div class="site-content"> <div class="mdl-grid site-max-width"> <div class="mdl-cell mdl-cell--12-col mdl-card mdl-shadow--4dp page-content"> <div class="mdl-grid"> <div class="mdl-cell mdl-cell--12-col"><div class="mdl-card__supporting-text"> <h2 class="mdl-card__title-text">Enter UNIPROT ID and/or description </h2> <form action="{%url 'DataUpload' %}" method="POST" class="form-contact"> {%csrf_token%} </div> <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> {{form.file}} </div> <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" type="submit"> Submit </button> </form> </div></div> </div> </div> </div> </div> </div> console log after submitting the form Quit the server with CONTROL-C. [22/Dec/2022 15:14:19] "POST /DataUpload HTTP/1.1" 200 1317 I'm not getting any error anywhere, but it's not uploading the file. -
Django how to store data from checkbox into a database
I want to add data from checkbox to database. I watched some videos but didn't worked out. checkbox.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Checkbox</title> </head> <body> <form action="" method="post"> {%csrf_token%} <div class="form-check"> <h5>Checkbox_report</h5> <input type="checkbox" value="Executive_summary" id="Executive_summary" name="checkbox_data"> <label for="Executive_summary"> Executive summary &nbsp</label> <input type="checkbox" value="Scope" id="Scope" name="checkbox_data"> <label for="Scope"> Scope &nbsp</label> <input type="checkbox" value="ISMS" id="ISMS" name="checkbox_data"> <label for="ISMS"> ISMS &nbsp</label> <input type="checkbox" value="Methodology" id="Methodology" name="checkbox_data"> <label for="Methodology"> Methodology &nbsp</label> <input type="checkbox" value="Recommendation" id="Recommendation" name="checkbox_data"> <label for="Recommendation"> Recommendation &nbsp</label> </div> <button type="submit">submit</button> </form> </body> </html> views.py from collections import Counter from django.shortcuts import render # Create your views here. def home(request): return render(request, 'home.html', {"text": "hello home"}) def about(request): return render(request, 'about.html', {"text": "hello about"}) def checkbox(request): if request.method == 'POST': checkbox_data = request.POST.getlist('checkbox_data') for i in checkbox_data: print(i) return render(request, 'checkbox.html') I want to add 1 when user check any of the checkbox and the one which are not checked add 0 second:: what is forms.py?what is the main difference between forms.py and manage.py -
A server error occurred. Please contact the administrator
i have a project but it says A server error occurred. Please contact the administrator. i have tried many times but not worked -
Django Server KeyError - Unable to locate my environment variable
I am making a blog using Django and am trying to make it secure by using 2 settings files (prod.py and local.py which both "import *" from a base.py original settings file). I have two environment variables which are on my local computer and have confirmed they exist: myBlog and SECRET_KEY. myBlog=prod The error I am receiving is a KeyError: (venv) C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog>python manage.py runserver Traceback (most recent call last): File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 22, in <module> main() File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\myBlog\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\core\management\__init__.py", line 386, in execute settings.INSTALLED_APPS File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "C:\Users\shark\Documents\Bootstrap Tutorial Website Files\38. Bootstrap 2020 Starter Files\DjangoBlog - Copy\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module … -
Apache2 not loading Django settings.py file properly
I am currently facing an issue where making any changes in settings.py file is not reflecting properly in my project. I have tried deleting the .conf file, adding it again, enabling it and reloading the apache2 server. But somehow it still does not work. I have an issue with CORS in Django, I made changes to correct it by allowing certain origins to make cross-origin requests: CORS_ALLOWED_ORIGINS = ['www.test.domain',...] So I tested it by running the Django server manually using python runserver 0.0.0.0:8000 and it is working fine, not getting any CORS issues But when I reload the apache2 server or even in this case, make a completely new .conf file and run it via apache2 - it still somehow does not recognize the changes and keeps giving me CORS errors. I am confused as to what is making this happen - to not reflect any newly made changes. The problem is, now I am not able to reflect these changes with a new configuration as well. So there is no way for me to keep this webserver running without getting CORS errors. NOTE: Apache has all the required accesses to my Django project - it can access settings.py without … -
How to get child model having one to one relation with default User model of Django?
I created a model having one to one relation with default User model to extend it for providing some permission for tabs in my website. Now I want to not show the tab options to the users not having permissions to access them. user permission model: from django.contrib.auth.models import User class userpermissions(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Checking whether the user has permission or not I created a function which is supposed to get the userpermission model instance of the logged in user. For which I used the following code -> def check(user): up = User.userpermissions_set.get(id=user.id) Now when user logs in the login function will call this check function and redirect to the tab that the user can access and also send the up variable containing all the permissions of the user so that the Navbar templet can hide those tabs which the user has no access to. Now the problem that I am facing is when I run the server it shows this error -> AttributeError at / type object 'User' has no attribute 'userpermissions_set' I saw on YouTube that to get the instance of child model (I don't know what to call it..) we need to use it's … -
Error with making a facial recognizer matrix. how to fix?
File "./rastreamento_de_rosto.py", line 43, in recognizer.train(x_train, np.array(y_labels)) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:362: error: (-210:Unsupported format or combination of formats) Empty training data was given. You'll need more than one sample to learn a model. in function 'cv::face::LBPH::train' I am having a problem with this code, it is supposed to be reading images and making a resumed pixel per color matrix of said images for a facial recognizer. but once i run this code, it keeps giving me the error said in the title, even though before it reaches the line of that code it reads the images before. import cv2 import os import numpy as np from PIL import Image import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(BASE_DIR, "images") face_cascade = cv2.CascadeClassifier('cascades/haarcascade_frontalface_alt2.xml') print("não e aqui em face_cascade") recognizer = cv2.face.LBPHFaceRecognizer_create() print(recognizer) current_id = 0 label_ids = {} y_labels = [] x_train = [] for root, dirs, files in os.walk(image_dir): for file in files: if file.endswith("png") or file.endswith("jpg"): path = os.path.join(root, file) label = os.path.basename(root).replace(" ", "-").lower() if not label in label_ids: label_ids[label] = current_id current_id += 1 pil_image = Image.open(path).convert("L") size = (550, 550) final_image = pil_image.resize(size, Image.ANTIALIAS) image_array = np.array(final_image, "uint8") faces = face_cascade.detectMultiScale(image_array,scaleFactor=1.5,minNeighbors=5) print(image_array) for (x,y,w,h) in faces: roi = … -
Django Queryset: Filter for subset of many to many relation
Let's assume the following model: class User(models.Model): clients = models.ManyToManyField(Client) How to query users by a list of clients, so that only those users are returned that have not other clients than those in the given list assigned. User.objects.filter(client__??=[client1, client2]) I had a look at Django's documentation of field lookups, but that did not help. Thanks in advance! -
TemplateDoesNotExist at / basicapp/index.html
`Hello friends,i tried creating basic forms with django from a direct example from Python and Django Full Stack Web Developer Bootcamp. i got the error below. TemplateDoesNotExist at / basicapp/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.3 Exception Type: TemplateDoesNotExist Exception Value: basicapp/index.html Exception Location: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: basicapp.views.index Python Executable: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\ADMIN\Desktop\Django\Django_forms\basic_forms\templates,\basicapp\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\templates\basicapp\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\ADMIN\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\templates\basicapp\index.html (Source does not exist) This is my **setting.py ** from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR,"templates,") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-bdh2@$^s84&+%qn^atqa+xjz8@7&g=(m2^!5j$f#$o=4+7jb5s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "basicapp", ] 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', ] ROOT_URLCONF = 'basic_forms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True,` … -
Django - How to use delete() in ManyToMany relationships to only delete a single relationship
I have a model Voucher that can be allocated to several users. I used a M2M relationship for it. I want, in the template, the possibility to delete the voucher allocated to the logged in user, and the logged in user only (not all relationships). The problem I have is that the current model deletes the entire model for all users, instead of the single user requesting "delete". The alternative would obvioulsy be to simply create a model Voucher on a ForeignKey, but something tells I can probably do it with a M2M in the views. Is there a way to focus my delete function specific to the user? In the example below, I tried to filter based on user.request which is not working. Looking at the data inside the model, users IDs are listed. Is it not what request.user does? models class Voucher(models.Model): user = models.ManyToManyField(User, blank=True) views def delete_voucher(request, voucher_id): voucher = Voucher.objects.filter(pk=voucher_id).filter(user=request.user) voucher.delete() return redirect('account') template <a class="button3 btn-block mybtn tx-tfm" href="{% url 'delete-voucher' voucher.id %}">Delete</a> url path('delete_voucher/<voucher_id>', views.delete_voucher, name='delete-voucher'), -
django app in cpaned doesn't upload pictures that I upload from django admistration page
after I deployed my django app to cpanel it doesn't save pictures that I upload it from django adminstration page Not: all data I enter it's save it and can return it to template but pictures not upload them How I can solve this problem? -
How to change the date of time instance using python?
I have start_time variable that stores a time string. start_time = '2022-12-21 22:00:00' Now Using python i want to change the date of start time to start_time = '2022-12-28 22:00:00' I have done this with very ugly approach. Please tell me easy and best way to do that. I tried with following code. #its not string its time instance replacing_date = 2022-12-28 00:00:00 #converting time into string replacing_date = datetime.strptime(replacing_date,'%Y-%m-%d %H:%M:%S') replacing_date =replacing_date.split(" ") start_time = start_time.split(" ") start_time = datetime.strptime(replacing_date[0]+start_time[1],'%Y-%m-%d %H:%M:%S') Basically i have to change date on many places. It doesn't seems to be good thing in that case. and it can break if time string format changes. i can also break if the years end. for example date change to. start_time = '2023-01-01 22:00:00' -
Why Django celery throws me a key error, not sure why?
Not sure why it throws this key error. My project/celery.py: import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') my project/init.py: from .celery import app as celery_app __all__ = ('celery_app',) My app/tasks.py from celery import shared_task from celery.schedules import crontab from project.celery import app @shared_task def my_test(): print('Celery from task says Hi') app.conf.beat_schedule = { 'my-task-every-2-minutes': { 'task': 'my_test', 'schedule': crontab(minute='*/1'), }, } when I run the command: celery -A project beat -l info I can see the trigger every 1 min there [2022-12-22 12:38:00,005: INFO/MainProcess] Scheduler: Sending due task my-task-every-2-minutes (celery_app.my_test) when running celery -A project worker -l info and triggers sends info I get KeyError: my_test It seems that it cannot find the task with that key but from my info everything running fine : -------------- celery@192.168.1.131 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- macOS-10.13.6-x86_64-i386-64bit 2022-12-22 12:43:22 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: project:0x10c757610 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- … -
Django: Template doesn't exist but on production
I have started another app inside my django project, and i already have multiple apps inside but only one return template doesnt exit but on production only, my project is deployed on heroku. I have done million of searches but couldnt find the solution. my static files and database are hosted on AWS here is some of my settings.py BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'erecruit', 'compensation', 'PMS', 'crispy_forms', 'forms_fieldset', 'django_filters', 'storages', 'gunicorn', 'foundation_filefield_widget', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], # 'DIRS': [BASE_DIR + "/templates", ], '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', ], }, }, ] AWS_ACCESS_KEY_ID = 'xxxx' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'xxxxx' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = "storages.backends.s3boto3.S3StaticStorage" DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False AWS_S3_VERIFY=False AWS_S3_USE_SSL = False STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') django_heroku.settings(locals()) here is the view.py @login_required(login_url='loginPage') def home(request): perm = 0 for i in request.user.groups.all(): if i.name == 'PMSupervisors': perm = 1 if perm == 0: context = {} return render(request, 'PMS/pms_home.html',context) if perm == 1: … -
Нужно получить данные из IMG для товара(Need to get data from IMG for a product)
В общем мне нужно достать текст ссылки фото, чтобы погружать карточки для товаров. Есть вот эти таблицы моделей Product и IMG. Я как только не пытался доставать IMG_Product (там текст(ссылка на локальный источник). Пробовал наверное все, но может ошибаюсь. Мне нужно чтобы из таблицы IMG забрались нужные IMG_Product для продуктов, у которых Subcategory_id = 4 (допустим это шуруповерты) Модель: ` lass Product(models.Model): id = models.AutoField(primary_key=True) Name = models.TextField() Price = models.IntegerField() # Гарантия в числовом выражении. 1 = 1 месяц Guarantee = models.IntegerField() Count = models.IntegerField() Description = models.TextField() Manufactur_id = models.ForeignKey(Manufacturer, on_delete = models.CASCADE) Subcategory_id = models.ForeignKey(Subcategory, on_delete = models.CASCADE) def __str__(self): return "%s"%(self.Name) class IMG(models.Model): id_Product = models.ForeignKey(Product, on_delete = models.CASCADE,related_name='Products') IMG_Product = models.TextField() def __str__(self): return "%s"%(self.id_Product) Недоделанный шаблон {% for i in Screwdriver_list %} {% for j in Img_Screwdriver_list %} <div class="card" > <div> <div class="Top_card"> <span>{{i.id}}</span> <!-- <span>Код товара:12345678</span> --> <img class="favorites_img" src="{% static "/img/LikeIt.png" %}" alt="В Избранное"> <img src="/{% static "img/Стрелки-Сравнения.png" %}" alt=""> </div> </div> <div class="Midle_card"> <img class="Midle_img" src="{{j.IMG_Product}}" class="card-img-top" alt=""> <!-- <img class="Midle_img" src="{% static "/img/img_catalog/cordless screwdriver/51106745.jpg" %}" class="card-img-top" alt="/img/img_catalog/cordless screwdriver/51106745.jpg"> --> </div> <div class="card-body"> <div class="Card_text"> <a class="card-text" href="#"><span>Импульсный винтоверт Ryobi 18 В ONE+ R18iD3-0 5133002613</span></a> </div> <div class="Bottom_Card"> <h3>5955 р.</h3> … -
custom authentication backend that can support non-unique usernames [closed]
How should I customize the authentication model to set unique=False in the field set in USERNAME_FIELD? # models/user.py class User(SafeDeleteModel, PermissionsMixin): id = models.UUIDField("아이디", primary_key=True, default=uuid.uuid4) email = models.EmailField("이메일", max_length=255) name = models.CharField("이름", max_length=255) provider = models.CharField("소셜 계정 제공 서비스", max_length=100, null=True, blank=True, default=None, editable=False) provider_id = models.CharField("소셜 계정 고유 식별자", max_length=255, null=True, blank=True, default=None, editable=False) [enter image description here](https://i.stack.imgur.com/nDev8.png) USERNAME_FIELD = "email" class CustomBackend(ModelBackend): def authenticate(self, request, password=None, **kwargs): username = kwargs.get("username", None) if username is None: username = kwargs.get("email") if username is None or password is None: return try: print("UserModel._default_manager : ", UserModel._default_manager) user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None # settings/base.py AUTHENTICATION_BACKENDS = ["app.settings.backend.CustomBackend"] https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD According to the django official document above I inherited ModelBackend and created a custom backend. [wanrring]enter image description here