Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can use slug for all urls in django without anything before or after?
I want all djaango urls use slug field without any parameter before or after, by default just one url can use this metod ex: path('<slug:slug>', Article.as_View(), name="articledetail"), path('<slug:slug>', Category.as_View(), name="category"), path('<slug:slug>', Product.as_View(), name="productdetail"), mysite .com/articleslug mysite .com/categoryslug mysite .com/productslug How can I do it? Thank you -
connection error while using requests module in my django project
I was trying to create a django project. Everything was fine until I did a get request using requests.get() in python in my views.py Following is what my views.py have from django.shortcuts import render import re, requests def codify_data(data_raw): data = data_raw.json()['data'] if language == 'web': html_cd = data['sourceCode'] css_cd = data['cssCode'] js_cd = data['jsCode'] def home_page(request): return render(request,'home/index.html') def code(request): link = request.GET.get('link', 'https://code.sololearn.com/c5I5H9T7viyb/?ref=app') result = re.search(r'https://code.sololearn.com/(.*)/?ref=app',link).group(1)[0:-2] data_raw = requests.get('https://api2.sololearn.com/v2/codeplayground/usercodes/'+result) codify_data(data_raw)``` [Error shown in image][1] [1]: https://i.stack.imgur.com/2Uao9.jpg -
get False Booleans one by one from the list
I am building a blog app in which, I have created about 10+ Booleans and I am trying to track Booleans according to the list. I mean, Suppose, there are 5 Booleans and all are in the sequence, like `[boolean_1, boolean_2, boolean_3, boolean_4, boolean_5] and they are all false. then I am trying to get first Boolean on a page until (turning True a Boolean can take days) it is True and then boolean_2 will be seen on page boolean_1 will be removed after True. then I am trying to get the Booleans which are False one by one But I have no idea how can I filter Booleans which are False one by one. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) boolean_1 = models.BooleanField(default=False) boolean_2 = models.BooleanField(default=False) boolean_3 = models.BooleanField(default=False) boolean_4 = models.BooleanField(default=False) boolean_5 = models.BooleanField(default=False) boolean_6 = models.BooleanField(default=False) views.py def page(request): listOfBooleans = [request.user.profile.boolean_1, request.user.profile.boolean_2, request.user.profile.boolean_3] get_first_boolean = listOfBooleans(0) context = {'listOfBooleans':listOfBooleans} return render(request, 'page.html', context) I have tried by using compress :- from itertools import compress list_num = [1, 2, 3, 4] profile_booleans = [request.user.profile.boolean_1, request.user.profile.boolean_2, request.user.profile.boolean_3] list(compress(list_num, profile_booleans)) But this :- It is returning True instead of False I cannot access first from it, if I … -
Accessing query parameter in serializer in Django
I just wanted to access a query parameter in serializer like class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['request'].query_params['page'] But its showing Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'request' Thanks in advance. -
Getting value from View to Serializer in Django
I am not sure what I am doing wrong, I tried to follow a few solution. class MyViewSet(viewsets.ModelViewSet): filterset_class = IngredientFilter def get_serializer_context(self): context = super().get_serializer_context() context['test'] = "something" return context In my Serializer, class MySerializer(BaseSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['test'] I am getting this error, Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'test' Any suggestions? -
Probkem in Django with runserver command
I started a project in django and everything was okay, but i closed my project and fews days later i tried to reopen, but this error appeared when i put the command "django-admin runserver" : Traceback (most recent call last): File "c:\users\moren\appdata\local\programs\python\python37-32\lib\runpy.py", line 193, in run_module_as_main "main", mod_spec) File "c:\users\moren\appdata\local\programs\python\python37-32\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\moren\Envs\myapp\Scripts\django-admin.exe_main.py", line 7, in File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management_init.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\moren\Envs\myapp\lib\site-packages\django\conf_init_.py", line 82, in getattr self.setup(name) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\conf_init.py", line 67, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. And when i put "python manage.py runserver" this appear : c:\users\moren\appdata\local\programs\python\python37-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory if anyone can help me I would be very grateful -
Hello, I encountered this problem. I tried to solve it through searching. I found solutions even here in stack overflow, but I did not understand how
My problem is a ValueError: Field 'id' expected a number but got 'passwprd'. I tried to delete the password field and then re-create it, but to no avail. I also tried to change the default for it too, to no avail. This problem appears when I give it a migrate command. Please help. Any other information I am ready to provide, thank you. PS C:\Users\user\Desktop\test1\prj> python manage.py migrate ←[36;1mOperations to perform:←[0m ←[1m Apply all migrations: ←[0madmin, auth, contenttypes, products, sessions, shop ←[36;1mRunning migrations:←[0m Applying products.0007_user_purshase...Traceback (most recent call last): File "C:\python\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'passwprd' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\python\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\python\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\python\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\python\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
Setting some fields to be automatically filled in using CreateVeiw in Django
I'm using Django's CreateView in order to fill a form and I want some of the fields to be automatically filled in, looking for ides how I could that -
trying to update DjangoREST API using calls from a Golang Job runnier. For some reason i keep receiving None Value in request.POST in django
Below is the function i run to update a Django REST API. The Map is correctly constructed as check by the println but Django server shows the value received as None. The similar API is called successfully using Python requests module. What might be the error here ? func upd_prices() { for i:=0; i<501; i++ { co_id:=strconv.Itoa(i) // co_obj:=Company{co_id} co_obj:=map[string]string{"id":co_id} jsonStr,err:=json.Marshal(co_obj) if err!=nil { log.Println(err) } // var jsonStr = []byte(`{"co_id":`+co_id+`}`) // responseBody:=bytes.NewBuffer(postBody) fmt.Println(string(jsonStr)) resp,err:=http.Post("http://127.0.0.1:8000/insert_prices/","application/json", bytes.NewBuffer(jsonStr)) if err!=nil { log.Print(err) } defer resp.Body.Close() _, err2 := ioutil.ReadAll(resp.Body) if err2 != nil { log.Fatalln(err) } // sb := string(body) // log.Print(sb) // // file,_:=os.Create("log.txt") // file.WriteString(sb) // defer file.Close() time.Sleep(time.Second*5) } }``` -
Display image and filter team members according to id in django
I want to display and team members of selected photographer id. But I am not getting image as well as team. Nothing is showing. models.py class Photographer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) location = models.CharField(max_length=100) studio_name = models.CharField(max_length=100) mobile = models.CharField(max_length=100) address = models.CharField(max_length=200) category = models.ManyToManyField(Category) class Gallery(models.Model): photographer = models.ForeignKey(User,on_delete=models.CASCADE) photo = models.ImageField(upload_to='gallery') cover_photo = models.ImageField(upload_to='cover_photos/',null=True,blank=True) class Team(models.Model): photographer = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=100) speciality = models.CharField(max_length=100) I am using foreignkey in Gallery table and in Team table. views.py def visit_photography_site(request,id): photographer = Photographer.objects.get(id=id) gallery = Gallery.objects.filter(photographer=photographer.user.id) team = Team.objects.filter(photographer=photographer.user.id) context = { 'photographer':photographer, 'gallery':gallery, 'team':team, } return render(request,'app/home.html',context) I want to display/filter gallery and team of the photographer according to particular photographer id. home.html <img class="sp-image" src="{{ gallery.cover_photo.url }}" alt="Slider 1"/> <h1 class="sp-layer slider-text-big" data-position="bottom" data-vertical="25%" data-show-transition="top" data-hide-transition="top" data-show-delay="1500" data-hide-delay="200"> <span class="highlight-texts">{{ photographer.studio_name }}</span> Here I want to display cover photo which is field in Gallery table and there is Foreign Key from Photographer table. If I click on photographer whose id is 1 then I should get cover photo of that photographer whose id is 1. -
Why Heroku can't find my Django templates?
I deployed my project on Heroku. But it can't find my templates(Source doesn't exist): My project architecture: settings.py: from pathlib import Path import sys import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { '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', ], }, }, ] -
Unable to install mysqlclient with pip on ubuntu
I'm trying to install mysqlclient on Ubuntu 20.04LTS, the main error is: mysql_config not found. Whole Error: $ pip3 install mysqlclient==2.0.3 Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient==2.0.3 Using cached mysqlclient-2.0.3.tar.gz (88 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup.py'"'"'; _file__='"'"'/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file_) if os.path.exists(_file_) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, _file_, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ehrlbbbl cwd: /tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/ Complete output (15 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/3c/df/59cd2fa5e48d0804d213bdcb1acb4d08c403b61c7ff7ed4dd4a6a2deb3f7/mysqlclient-2.0.3.tar.gz#sha256=f6ebea7c008f155baeefe16c56cd3ee6239f7a5a9ae42396c2f1860f08a7c432 (from https://pypi.org/simple/mysqlclient/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement mysqlclient==2.0.3 (from versions: 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, … -
Dockerizing django, postgres, gunicorn, ngnix - only admin static works, other 404
As in topic. I have tried to apply solutions I found in internet, but no success :( I am pretty new to programming and as making an app is one thing, deploying it just overwhelmed me. I have managed to put it on server, run it on docker with SSL, but main problem is that only admin static files load, other give 404 error. Weird thing is that static subdirectories structure is kept, but there are no files inside. Please help me, I am really stuck :( If you require any other data, please write Note that neither STATIC_ROOT or STATIC_DIRS work (in some cases changing it helped, not here). Thank you very much in advance Directory structure: ├── app │ ├── Dockerfile.prod │ ├── entrypoint.prod.sh │ ├── manage.py │ ├── requirements.txt │ ├── sancor │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ ├── views.py │ │ └── wsgi.py │ ├── static │ │ ├── css │ │ ├── favicon.ico │ │ ├── fonts │ │ ├── js │ │ ├── less │ │ ├── sancor │ │ │ ├── css │ │ │ └── js … -
im not able to send data to view due json serializable
i am getting error set object is not JSON serializable i also used json.dumps but still getting this error ? actually i am trying to save form data to django database with help of ajax but where i am doing mistake def update_ajax(request): if request.method == "GET" and request.is_ajax(): nam1 = request.GET.get('nam1') nam2 = request.GET.get('nam2') nam3 = request.GET.get('nam3') n1 = json.loads(nam1) n2 = json.loads(nam2) n3 = json.loads(nam3) print(n1, n2, n3) return JsonResponse({'success'}, safe=False) script function myfun(){ let nam1=document.getElementById('name').value; let nam2=document.getElementById('email').value; let nam3=document.getElementById('phone').value; obj ={ 'nam1': JSON.stringify(nam1), 'nam2':JSON.stringify(nam2), 'nam3':JSON.stringify(nam2), } $.ajax({ type:"GET", url: "{% url 'update_ajax' %}", dataType: "json", data: obj, success:function(){ alert('success') } }); } -
A question about django:TypeError: 'builtin_function_or_method' object is not subscriptable
models.py class User_db(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=64) here is shell code >>>python manage.py shell >>>from appName.models import User_db *i dont konw why it is wrong,maybe about QuerySet?* >>>User_db.objects.all().values() **TypeError: 'builtin_function_or_method' object is not subscriptable** >>> User_db.objects.get(id=1) <User_db: User_db object (1)> the problem also occurs with "filter()". this error makes me confuse,help me,plz!!! -
How to display Data of relative foreign key in Django html page?
I saw may answer but i don't know why in my page its not working can anyone help me to find the mistake. model class SchoollModel(models.Model): title = models.CharField(max_length=60 ) image = models.FileField(upload_to = 'static/img' ,help_text='cover img') desc = models.TextField(null=True, blank=False) def __str__(self): return self.title class SchoolImage(models.Model): post = models.ForeignKey(SchoollModel, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'static/img') def __str__(self): return self.post.title views.py after importing all def school_view(request , id): school_model =SchoollModel.objects.all().filter(id=id)[0] school_image = SchoolImage.objects.all() return render(request,'school.html' ,{'school_model':school_model,'school_image':school_image}) school.html i wanna display multiple image of school. i have inlined in admin. how we can get all the images that foreign-key to SchoolModel {% for sch in SchoollModel.SchoolImage_set.all %} <img style = 'max-height:14rem ;max-width:14rem;' src="{{sch.images.url}}" alt="image"> {% endfor %} -
Django Not able to retrieve/fetch versatileImage link (Cropped URL) in SerializerMethodField()
class GetUserImageOneSerializer(serializers.ModelSerializer): class Meta: image_one = VersatileImageFieldSerializer( sizes=[ ('medium_square_crop', 'crop__400x400'), ] ) model = UserImage fields = ('image_one',) class ChatUserSerializer(serializers.ModelSerializer): chatImage = serializers.SerializerMethodField() class Meta: model = Chat fields = ('roome_name','chat_user_one','chat_user_two','lastUpdated','chatImage') def get_chatImage(self, obj): image=UserImage.objects.filter().first() //(for Test) serializer = GetUserImageOneSerializer(image) return serializer.data Here I am trying to pass image of the user in chat serializer ('ChatImage') .For better behavior in UI I need square crop image ,so I tried to use nested serializer ('GetUserImageOneSerializer' inside 'ChatUserSerializer'). But I am getting normal URL only . can you help me to find better way to implement my idea :) OUT PUT : [ { "roome_name": "BISM1000BISM1000", "chat_user_one": 6, "chat_user_two": 5, "lastUpdated": "2021-12-11T10:29:21.589947Z", "chatImage": { "image_one": "/media/userimage/team-1.jpg" } } ] -
Django deploy to production with nginx gunicorn and SSL - How to deploy?
I am trying to deploy my Django app to my domain but I do not know how to set this up, I currently have the app running in development only. There are many components involved, like Nginx, gunicorn, uvicorn, and apparently, I have to set up some SSL certificates. The relevant files: This is my folder structure now, and it seems like I need to add the certificates to certs/, which is currently empty: .rw-r--r-- 53k 5 Dec 13:28 -- .coverage drwxr-sr-x - 11 Dec 12:32 -- .git/ .rw-r--r-- 52 2 Dec 12:05 -- .gitignore .rw-r--r-- 3.0k 11 Dec 01:05 -- .gitlab-ci.yml drwxr-sr-x - 2 Dec 21:09 -- app/ drwxr-sr-x - 10 Dec 15:06 -- bank/ drwxr-sr-x - 11 Dec 12:26 -- certs/ drwxr-sr-x - 6 Dec 14:40 -- config/ drwxr-sr-x - 2 Dec 21:33 -- data/ .rw-r--r-- 197k 5 Dec 13:28 -- db.sqlite3 .rw-r--r-- 182 11 Dec 01:05 -- db_dev.env .rw-r--r-- 185 10 Dec 15:06 -- db_prod.env .rw-r--r-- 185 10 Dec 15:06 -- db_test.env drwxr-sr-x - 2 Dec 19:57 -- dbscripts/ .rw-r--r-- 733 10 Dec 15:06 -- docker-compose.yml .rw-r--r-- 378 10 Dec 15:06 -- Dockerfile .rw-r--r-- 1.0k 11 Dec 12:03 -- entrypoint.sh drwxr-sr-x - 4 Dec 00:23 -- htmlcov/ … -
Django CORS issue with flutter web
I want to connect flutter web with Django server. flutter with mobile works well, but I can't solve the problem about flutter web. when I run server with my ipv4 Django python manage.py runserver 192:168:0:9:8000 Flutter Uri.parse("http://192.168.0.9:8000/api/buildingdata/"), headers: {"Access-Control-Allow-Origin": "*"}); flutter run -d chrome --web-port=8000 Mobile version works well, but web version makes CORS error. Access to XMLHttpRequest at 'http://192.168.0.9:8000/api/buildingdata/' from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field access-control- allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. browser_client.dart:74 GET http://192.168.0.9:8000/api/buildingdata/ net::ERR_FAILED I tried to find solutions but none of them worked, such as web-hostname command(this command can't even run flutter), deleting flutter_tools.stamp and adding disable-web-security Also I've tried to disable chrome CORS. This is my django settings about cors settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ALLOWED_HOSTS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) Where should I fix to solve CORS error? -
django rest api permission problem with post and put
I have a problem with post and put request. My requests with axios in react: handleSubmit() { axios.post('http://127.0.0.1:8000/api/tasks/',{ headers:{"Authorization":`Token ${this.state.token}`}, author:this.state.id, title:this.state.title, desc:this.state.desc, done:false, }) .then( response =>{console.log(response);} ) .then( ()=>{window.location.reload(false);} ) } Everything works fine but when i change AllowAny to IsAuthenticated in code below: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } i'm getting an error like this POST http://127.0.0.1:8000/api/tasks/ 403 (Forbidden) dispatchXhrRequest @ xhr.js:210 xhrAdapter @ xhr.js:15 dispatchRequest @ dispatchRequest.js:58 request @ Axios.js:108 Axios.<computed> @ Axios.js:140 wrap @ bind.js:9 handleSubmit @ TaskCreate.js:41 onClick @ TaskCreate.js:73 callCallback @ react-dom.development.js:3945 invokeGuardedCallbackDev @ react-dom.development.js:3994 invokeGuardedCallback @ react-dom.development.js:4056 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4070 executeDispatch @ react-dom.development.js:8243 processDispatchQueueItemsInOrder @ react-dom.development.js:8275 processDispatchQueue @ react-dom.development.js:8288 dispatchEventsForPlugins @ react-dom.development.js:8299 (anonymous) @ react-dom.development.js:8508 batchedEventUpdates$1 @ react-dom.development.js:22396 batchedEventUpdates @ react-dom.development.js:3745 dispatchEventForPluginEventSystem @ react-dom.development.js:8507 attemptToDispatchEvent @ react-dom.development.js:6005 dispatchEvent @ react-dom.development.js:5924 unstable_runWithPriority @ scheduler.development.js:468 runWithPriority$1 @ react-dom.development.js:11276 discreteUpdates$1 @ react-dom.development.js:22413 discreteUpdates @ react-dom.development.js:3756 dispatchDiscreteEvent @ react-dom.development.js:5889 createError.js:16 Uncaught (in promise) Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.onloadend (xhr.js:66) In addition to that, get requests work correctly even if i change to isAuthenticated. const getTasks = () =>{ //this works fine axios.get("http://127.0.0.1:8000/api/tasks/"+`user/${id}/` ,{headers:{"Authorization":`Token ${props.token}`}}) .then( response => { setTasks(response.data); … -
I am not receiving any error when i run my application but when a user registers he gets added to both client and worker tables. instead of one table
Someone show me where my code is not correct. during registration, am having a user who is a client getting added to both client and worker tables, while a worker is getting added to both client and worker tables, which is not okay. Am not getting any traceback error when i run the app the duplication could mean that there is code which is running twice signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from django.dispatch.dispatcher import receiver from .models import Worker,Client @receiver(post_save, sender=User) def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='Client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, email=instance.email, ) print('Profile created!') @receiver(post_save, sender=User) def worker_profile(sender, instance, created, **kwargs): if created: Worker.objects.create( user=instance, name=instance.username, email=instance.email, ) models.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ # Create your models here. class Client(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Worker(models.Model): CATEGORY = ( ('Plumber', 'Plumber'), ('Electrician', 'Electrician'), ('Cleaner', 'Cleaner'), ) user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = … -
How to optimize a DjangoORM reverse foreign key query?
I have the following relationships: I'm trying to select all tasks with all instances and their vehicle. This however is a very slow query. To my understand I have to use prefetch_related because it's a OneToMany relationship. My InstanceModel has a reverse foreign key to Task: task = models.ForeignKey(TaskModel, on_delete=models.CASCADE, related_name="instances") I've attempted a query like this in DjangoORM: TaskModel.objects.filter(department_id=department_id).prefetch_related("instances", "instances__vehicle") But it's very slow. Is there any way to optimize this or due the relationship inherently restrict this query pattern? Running in Django 3.x -
How to convert ' to quotes in javascript?
I am trying to pass a python list with string values from views.py to the template where a javascript uses the same for labels of a pie chart(plotly). The issue is when the list is received at the front-end, the list is getting the hexcode of the quote which is ' instead of the quotes. How to convert it to quote? Here is the snippet: var trace1 = { x: {{labels}}, y: {{values}}, marker:{ color: ['rgba(204,204,204,1)', 'rgba(222,45,38,0.8)', 'rgba(204,204,204,1)', ] }, type: 'bar' }; Now, i am getting the values for 'labels' as: [&#x27;One&#x27;, &#x27;Two&#x27;, &#x27;Three&#x27;] Instead of: ['One','Two','Three'] Just wanted to know are there any methods to avoid this easily instead of using string replace methods? -
Get first element from many to many relationship django in template
I'm trying to get the first element from queryset which is returned by a Model Field which is a ManyToManyField right in the template. models.py class CraftImage(models.Model): image = models.ImageField(upload_to='crafts_images/', null=True) class Craft(models.Model): title = models.CharField(max_length=100, null=False, blank=False) images = models.ManyToManyField(CraftImage, blank=True, related_name='craft_images') views.py def work_all(request): crafts = Craft.objects.all() context = { 'crafts': crafts, } template.py {% for craft in crafts %} <div style="background-image: url('{% static 'craft.images[0].image.url' %}');"></div> {% endfor %} Something like this. I've also tried following some solutions I found which didn't work for me such as.. views.py crafts = Craft.objects.all() images = Craft.objects.values_list('images').first() print(images) context = { 'crafts': crafts, 'images': images } templates.py {% for craft in crafts %} <div style="background-image: url('{% static 'images.image.url' %}');"></div> {% endfor %} -
Running deferred SQL in django
Whenever i run python3 manage.py makemigrations python3 manage.py migrate I get this Running deferred SQL... I am not getting any error but curious to know will it affect in long term? Any way to remove this? My custom user model is from django.contrib.auth.models import AbstractUser class MyUser(AbstractUser): ...