Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to get One object value from database in Django
The situation is I have a table named Status consists of two fields. one is id which is primary key and based on auto increment and second is status which is integer. Now, the scenario is that I only want to get the value of status not id. Here are the details: views.py: from cvs.models import status_mod field_object = status_mod.objects.get(status) print(field_object) models.py: class status_mod(models.Model): id = models.BigIntegerField status = models.BigIntegerField class Meta: db_table = "status" The issue is that I want to store status value in a variable and want to call him in my template. Any solvable solution please -
legacy-install-failure when installing mysqlclient on mac
In django project I set the database as the rds mysql database and after running the server I got thie error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Naturally I tried to install mysqlclient package with pip3 install mysqlclient and I'm running into this error. I also tried pip3 install mysqlclient --use-pep517 but it results a different error [ -
How do I access static files using Jinja in Django
I am using Jinja templating within Django and I am having trouble getting static files to load. I have tried setting up the back end per this documentation (I've included the code below): https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2 However, I am getting an "Encountered unknown tag 'static'" if I include a {% load static 'path' %} tag. If I include a {% load static %} tag, I get "Encountered unknown tag 'load'." error. I have setup a "jinja2.py" file in the main folder with the following code: from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env settings.py has the following code: TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "environment": 'valuation.jinja2.environment', } }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', ], }, }, ] Any guidance is very much appreciated. See above code for what I tried. -
Django's CORS_ALLOWED_ORIGINS and CORS_ALLOW_ALL_ORIGINS not working
I have a very strange problem with Django's corsheaders. I have tried all sorts of permutations and combinations by playing with all the possible settings but of no use. My current settings look like this: ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = ['*'] CORS_ALLOW_ALL_ORIGINS = True This is still causing the following error when the frontend sends an API request: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I am not sure what else needs to be added, please let me know if I am missing anything here. I have already added 'corsheaders' in INSTALLED_APPS and also 'corsheaders.middleware.CorsMiddleware'in the MIDDLEWARE list (on top) I have tried adding domains one by one in the lists and verified by loading the changes, but still nothing worked. Even though I have now allowed for any origin and any host to send cross-origin requests, it is still throwing the CORS error. -
Can I use pretty-errors with gunicorn
I work on a project where in development I run a django webapp in gunicorn on docker. I want to use pretty-errors or any other tool that gives me pretty stacktrace. I have installed it and it works in the docker container because I can use it when I start a python shell. However when I start gunicorn instead of python, the stacktrace doest use pretty-errors. So does gunicorn interfere with pretty-errors?