Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku release fails, error related to django.utils
So I updated my python code to Django 4.0 and with that, had to remove and update some deprecated code as "ungettext_lazy" and similar. Locally, the code is compiling well but when I push it to heroku, I get this error: from django.utils.translation import ungettext_lazy ImportError: cannot import name 'ungettext_lazy' from 'django.utils.translation' (/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py) I've tried a few things but haven't been able to update this on heroku. -
Django rest framework ListApiView slow query
I have a displays table with 147 rows. I am not doing any heavy computation on this data set I just need to get it fast from the database. For now, the load time is 3-4 seconds. Other data comes really fast, why? Does the ListApiView work slow? @permission_classes([AllowAny]) class DisplaysList(generics.ListAPIView): queryset = Displays.objects.all() serializer_class = serializers.DisplaySerializer -
How to resolve an error after deploy on heroku?
After deploy I have an error whenever I try to push a button. What to do? Text of error: ProgrammingError at /notion/ relation "base_notion" does not exist LINE 1: ... "base_notion"."title", "base_notion"."body" FROM "base_noti... -
How to connect redis heroku for websocket?
I'm making chat. I need to deploy my django app to heroku. I did it via the docker. I use free heroku redis and django-channels. Redis cancels my connection and I'm getting ConnectionResetError: [Errno 104] Connection reset by peer In settings i have CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get("REDIS_URI")], }, }, } And my REDIS_URI I got from heroku-resources-heroku_redis-settings consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print('==================================') print('==================================') print(self.room_name) print(self.room_group_name) print('==================================') print('==================================') await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() .................... And the traceback 2021-12-24T15:59:15.190002+00:00 heroku[router]: at=info method=GET path="/ws/chat/FIRST/?access=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQwMzY1MDY5LCJpYXQiOjE2NDAzNTQyNjksImp0aSI6ImZiNTg2N2MzNzg4NzRiN2M4NmJjNzM1YTJmNmQ1MTFmIiwidXNlcl9pZCI6MX0.JPPRPZAWE0iJ9BqBXYNZLc27u_CNqX90zX9F6MMJpf4" host=ggaekappdocker.herokuapp.com request_id=47782ca1-01c4-42e5-a589-5502869d2393 fwd="178.121.19.23" dyno=web.1 connect=0ms service=569ms status=500 bytes=38 protocol=https 2021-12-24T15:59:14.973191+00:00 app[web.1]: 2021-12-24 15:59:14,972 INFO ================================== 2021-12-24T15:59:14.973292+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.973402+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO FIRST 2021-12-24T15:59:14.973507+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO chat_FIRST 2021-12-24T15:59:14.973604+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.973719+00:00 app[web.1]: 2021-12-24 15:59:14,973 INFO ================================== 2021-12-24T15:59:14.974246+00:00 app[web.1]: 2021-12-24 15:59:14,974 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-24T15:59:14.975178+00:00 app[web.1]: 2021-12-24 15:59:14,975 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-24T15:59:14.979031+00:00 app[web.1]: 2021-12-24 15:59:14,978 DEBUG Cancelling waiter (<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f3c21189c40>()]>, [None, None]) 2021-12-24T15:59:14.979466+00:00 app[web.1]: 2021-12-24 15:59:14,979 DEBUG Closed 0 connection(s) 2021-12-24T15:59:14.979729+00:00 app[web.1]: 2021-12-24 15:59:14,979 DEBUG Cancelling waiter (<Future cancelled>, [None, … -
cannot upload HTML image to a website, however local file URL works fine
before you say that it's a duplicate, please read the entire thing. I have the following piece of code: <title>the-doge.net</title> <!-- add the image--> <img src="doge-poster1.png" height="500" width="800" style="display: block; margin-left: auto; margin-right: auto;"/> <body style="background-color:black;"> <!--add the login and register buttons--> <input type="image" src="register.png" style="display:inline; position:absolute; top:50px; right: 7%;"/> <input type="image" src="login.png" style="display:inline; position:absolute; top:50px; left: 12%;"/> </body> however, it says Not Found: /login.png Not Found: /doge-poster1.png Not Found: /register.png I have looked at various answers on Stack Overflow, including this, and also a few websites like here and provided full directory, and a image on img.bb, but it all did not work. Here is my file structure: ... landing(folder) --migrations (folder) --templates (folder) ----landing (folder) ------base.html ------doge-poster1.png ------index.html ------login.png ------navbar.html ------register.png note: In PyCharm there is a way to open a local file URL and it works fine, but python manage.py runserver doesn't seem to display any of the images. -
How to hash strings in python(django) and compare the hashed value with a given string
I'm working on a web app that allows users to sign up then login, I used the following functions to hash the password from passlib.hash import pbkdf2_sha256 import math def encrypt_password(pswd): encrypt_pswd = pbkdf2_sha256.encrypt(pswd, rounds=(int(math.pow(len(pswd),3))), salt_size=(len(pswd)*2)) return encrypt_pswd def verify_password(pswd, e_pswd): en_pswd = encrypt_password(pswd) if en_pswd == e_pswd: return True else: return False my problem is that the string I hashed doesn't produce the same result when I hash it for a second time. How can I resolve this issue or what methods can I use hash the password, store in the database and compare that value with the one from the login form -
Apache + mod_wsgi + Django + dataclasses stopped working after upgrade to python3.10
After upgrading to python3.10 code with dataclasses stopped working with mod_wsgi. If a class is created with @dataclass decorator (with just a single attribute x: str) and then instantiated somewhere in apps.py at module level, an exception is thrown. The reason is missing generated __init__ method (I confirmed that everything works if I define __init__ manually). Unfortunately, in real project it's part of external library and dataclass is instantiated in imported module, so there's no way to define __init__ by hands. The code without changes (all packages have same versions too) works with python3.9. To be clear, here's the code: # models.py from dataclasses import dataclass @dataclass class Test: foo: str # apps.py from django.apps import AppConfig from .models import Test Test('bar') # Error is thrown here class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' It seems like there's a bug somewhere. I also know that mod_wsgi only support python up to 3.8, according to data on pypi, but can't believe the answer is "Look for other wsgi solution or don't upgrade yet" (if so - tell me too, it might be true). You might notice that Django is of version 3.2 in requirements while 4.0 is available: I tried … -
Django Wrong File Path / Redirect and Pass Data
I am struggling to get this right. I am trying to redirect from PageOne to PageTwo and while supplying PageTwo with selected data from PageOne. I have tried a few things and can't seem to get this right. Method 1 Changing File Path class PageOne(TemplateView): template_name = 'home/pageone.html' def get(self, request): args = {} return render(request, self.template_name, args) def post(self, request, *args, **kwargs): if request.POST.get('confirm'): name = request.POST.get('hidden_get_client_name') data= request.POST.get('get_data') args = {'name':name,'data':data} new_template_name = 'home/PageTwo.html' return render(request, new_template_name, args) This works, but the file path is still /PageOne when the page loads. How do I change this to PageTwo? Method 2 Redirect response = redirect('/PageTwo/') return response Using this method, the file path is correct, but I am unable to pass data? Any help would be greatly appreciated. I am struggling to effectively redirect between pages while passing data. -
Django new project ModuleNotFoundError: No module named 'demoapp' (virtual env's name)
I am trying to start a new Django project but running into the error ModuleNotFoundError: No module named '<XYZ>' where XYZ is the name of my virtual environment created using mkvirtualenv. This is really weird and I can't say what has changed in my system recently to cause this. Here are steps showing how this error occurs in a brand new project: Create the virtual environment: ~/code/projects/temp$ mkvirtualenv demoapp created virtual environment CPython3.9.6.final.0-64 in 237ms creator CPython3Posix(dest=/Users/ankush/.virtualenvs/demoapp, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/ankush/Library/Application Support/virtualenv) added seed packages: pip==20.3.3, setuptools==51.3.3, wheel==0.36.2 activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/predeactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/postdeactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/preactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/postactivate virtualenvwrapper.user_scripts creating /Users/ankush/.virtualenvs/demoapp/bin/get_env_details Install Django: (demoapp) ~/code/projects/temp$ pip install django Collecting django Using cached Django-4.0-py3-none-any.whl (8.0 MB) Collecting asgiref<4,>=3.4.1 Using cached asgiref-3.4.1-py3-none-any.whl (25 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB) Installing collected packages: sqlparse, asgiref, django Successfully installed asgiref-3.4.1 django-4.0 sqlparse-0.4.2 WARNING: You are using pip version 20.3.3; however, version 21.3.1 is available. You should consider upgrading via the '/Users/ankush/.virtualenvs/demoapp/bin/python -m pip install --upgrade pip' command. Start a new project (demoapp) ~/code/projects/temp$ django-admin startproject uberclone Run the new project right away: (demoapp) ~/code/projects/temp$ cd uberclone/ (demoapp) ~/code/projects/temp/uberclone$ ./manage.py runserver Traceback (most … -
Django testing CSV response
i'm writing a simple app whose job is to scrape data from some api, add data to database, and finally load this data and generate CSV file. Its main funcionality is working, but i have to write unit tests, and I have no idea what should I focus on. This is my main function which task is to call another function that scrape and save data to database, and then it generate CSV file. def csv_output(request): api_get_data() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=users_tasks.csv' writer = csv.writer(response) writer.writerow(['User name', 'City', 'Task title', 'Task boolean']) for task in Task.objects.all().order_by('user_id'): user = User.objects.get(id=task.user_id) writer.writerow([user.full_name, user.address.city, task.title, task.completed]) return response This is function that scrapes data from api, and saves it in database. def api_get_data(): user_response = get_data_from_url('users') if user_response: for item in user_response: obj_user, created_user = User.objects.update_or_create( id=int(item.get('id')), defaults={ 'full_name': item.get('name'), 'username': item.get('username'), 'email': item.get('email'), 'phone_number': item.get('phone'), 'website': item.get('website') } ) addr_items = item.get('address') obj_address, created_address = Address.objects.update_or_create( user=obj_user, defaults={ 'street': addr_items.get('street'), 'suite': addr_items.get('suite'), 'city': addr_items.get('city'), 'zipcode': addr_items.get('zipcode') } ) task_response = get_data_from_url('todos') if task_response: for item in task_response: task_obj, task_created = Task.objects.update_or_create( user_id=item.get('userId'), id=item.get('id'), defaults={ 'id': item.get('id'), 'title': item.get('title'), 'completed': item.get('completed') } ) My question is, what should i focus on? … -
"You need to enable JavaScript to run this app"; response is html instead of json
Technologies used: Django, Djoser, react.js, webpack I made the request in react.js: const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ email, first_name, last_name, password, re_password, }); const response = await axios.post( `http://127.0.0.1:8000/auth/users/`, body, config ) I used Djoser in the backend to handle the auth requests. I console.log the response and find that the response is html instead of JSON. The status is 200 but it should be HTTP_201_CREATED based on Djoser's documentation. I checked that Djoser is in INSTALLED_APPS in Django and I have djoser==2.1.0. I try to add "proxy": "http://127.0.0.1:8000", in package.json, not working. I also try to use fetch instead of axios, also not working. I am not sure where the problem comes from. -
How to populate second drop down by using the selection of first drop down in django?
I have tree dropdowns ! Lets say Drop1, Drop2, Drop3. Now each populates data's from database. Now my problem is as below. I need to somehome populate the Drop2 data based on Drop1 and Drop3 data based on Drop2. Lets say if user selects Drop1 - Option A //selected By using this Option A i need to filter and fetch data for Drop2 Drop2 - Option A2 // fetched based on Drop1 Selection And same applies to Drop3 How to handle this ? I have populated the data for Drop1, but confused on how to select for Drop2 based on Drop1. Please guide Thank you. I dont know what code to share, so please let me know if you guys need anything -
TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type
enter image description here i am trying to run this project but its giving TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type Project Github Link: https://github.com/prathmachowksey/Attendance-System-Face-Recognition -
TypeError at /register/ list indices must be integers or slices, not str
How can i solve this issue in my forms.py from django import forms from django.forms.widgets import EmailInput, FileInput, PasswordInput, TextInput, Textarea from django.contrib.auth.models import User from django.contrib.auth import authenticate,get_user_model User = get_user_model() class RegistertionForm(forms.Form): first_name = forms.CharField(widget=TextInput(attrs={ 'class': 'validate form-control', 'placeholder': 'Full Name', 'type': 'text', 'id': 'first_name'}), min_length=2, max_length=150) username = forms.CharField(widget=TextInput(attrs={'class': 'validate form-control', 'placeholder': 'Username', 'type': 'text', 'id': 'username'}), min_length=4, max_length=150) email = forms.CharField(widget=EmailInput(attrs={'class': 'validate form-control', 'type': 'email', 'placeholder': 'Enter your email address', 'id': 'email'})) number = forms.CharField(widget=TextInput(attrs={'class': 'validate form-control', 'type': 'number', 'placeholder': 'phone number', 'id': 'number'})) password = forms.CharField(widget=PasswordInput(attrs={'class': 'validate form-control', 'type': 'password', 'placeholder': 'Password', 'id': 'password'})) password2 = forms.CharField(widget=PasswordInput(attrs={'class': 'validate form-control', 'type': 'password', 'placeholder': 'Confirm-password', 'id': 'password2'})) description = forms.CharField(widget=Textarea(attrs={'class': 'validate form-control', 'placeholder': 'Write about yourself', 'id': 'description'})) # picture = forms.CharField(widget=FileInput(attrs={'class': 'validate form-control', 'type': 'file', 'id': 'profile', 'name': 'profile'})) def clean_firstname(self): firstname = self.cleaned_data['firstname'].lower() qs = User.objects.filter(firstname=firstname) if qs.count(): raise forms.ValidationError("Name already exists") return firstname def clean_username(self): username = self.cleaned_data['username'].lower() qp = User.objects.filter(username=username) if qp.count(): raise forms.ValidationError("Username already exist") return username def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise forms.ValidationError("Email already exists") return email def clean_phone(self): number = self.cleaned_data['email'].lower() r = User.objects.filter(number=number) if r.count(): raise forms.ValidationError("Phone number already exists") return number def clean_password2(self): … -
Make API call on page load (Django)
I'm trying to figure out a way to make an API call and retrieve the results on page load. Any pointers would be appreciated! -
Why am i getting server 500 error in Django?
I have been trying to use the Django template inheritance feature for my project Since I've added {% block content %}s I am now getting a server error 500 whenever I try to run the child template. The base template runs fine. I am quite sure it has something to do with the content blocks, but I'm not sure why as I don't repeat any names of blocks and everything on the child template is contained within a block. Code goes like this: Base.html <!DOCTYPE html> <style> 'My style' </style> <html lang='en'> <head> <meta charset='UTF-8' {% block title %} webpage {% endblock %} <script>'Jquery reference'</script> </head> {% block script %} 'empty' {% endblock %} <body> <div id='navbar'> 'My navbar' </div> <div id='main_content_block'> {% block content %} <h1>This is my base</h1> {% endblock %} </div> </body> </html> Home.html {% extends 'main/base.html' %} {% block title %} <title>Home</title> {% endblock %} {% block script %} 'My javascript' {% endblock %} {% block content %} 'My content' {% endblock %} Thanks for your time -
How to deploy django app with channels and websocket to Heroku?
I'm creating messanger. I met a need to deploy my app to heroku. My config/settings.py from pathlib import Path from datetime import timedelta import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'corsheaders', 'users', 'tokens', 'channels', 'chat', 'college' ] AUTH_USER_MODEL = 'users.User' ASGI_APPLICATION = 'config.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(os.environ.get('REDIS_URI'), 25690)], }, }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('ELEPHANT_NAME'), 'USER': os.environ.get('ELEPHANT_USER'), 'PASSWORD': os.environ.get('ELEPHANT_PASSWORD'), 'HOST': os.environ.get('ELEPHANT_HOST'), 'PORT': 5432 } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ........................ I user heroku-redis config.asgi import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing from config.middlewares import TokenAuthMiddleware os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": TokenAuthMiddleware( URLRouter( chat.routing.websocket_urlpatterns ) ), }) Procfile release: python manage.py migrate web: daphne config.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=core.settings -v2 Honestly I don't know which port i should specify. Don't … -
Heroku Serving Localhost URL (127.0.0.1:8000) in Ajax API URLs in Django App
I'm currently working on a Django project and it's hosted on Heroku from GitHub. The front-end is served via Ajax calls to an API. let myurl = "/api/properties/"; $.ajax({ async: true, url:myurl, method:'GET', success: function(result){ .... } }); Everything works well on localhost, but on Heroku, I keep getting the error: GET http://127.0.0.1:8000/api/properties/ net::ERR_CONNECTION_REFUSED My API URL has no http://127.0.0.1:8000 on GitHub but on Heroku it has it after analyzing the source code on the Sources tab on Chrome: let myurl = "http://127.0.0.1:8000/api/properties/"; $.ajax({ async: true, url:myurl, method:'GET', success: function(result){ .... } }); I don't understand why my app's API URL isn't taking the domain URL https://appname.herokuapp.com/api/properties/ and it's across all the Ajax API URLs on the Django app. I have cleared my browser cache, opened the app in 'incognito mode' and even redeployed the project several times but not change. Kindly help me debug this and understand where the localhost URL is coming from. -
Django 3.2.8: 0 static files copied to '/static'
This error occurs when performing command python manage.py collectstatic: 0 static files copied to '/home/project'. That means there is no changes and my static files already exist in the destination but in this folder only one file: static/ - staticfiles.json But I want all my CSS, js, HTML for panel admin to be in it. Django Settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static/") STATICFILES_DIRS = ( STATIC_ROOT, ) urls.py ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I also tried these 1, 2 but no results were found. -
How to set subdomain from django-host in cpanel?
I have a Django based web application. I deploy the website on hosting using cPanel. There is already provided for the installation of Python-based applications. On my website I use a subdomain that I created with the django-host library. When run on localhost, like http://driver.localhost:8000 and can run. How do I make the subdomain accessible when I deploy the website to hosting? Seperti https://driver.gatotkacatravel.com -
Function view throws an exception of UnboundLocalError at /group/share/42/ when a user tries share a post
What could possibly be the course of this exception UnboundLocalError at /group/share/42/ when i try sharing post of another user in a group.The exception trace seems to be on the the first line of the forloop ( new = new_post.video.add(img) ) Here is my view for users to share post def share_post(request, pk): original_post = Post.objects.get(pk=pk) form = ShareForm(request.POST) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, shared_on = timezone.now(), shared_user = request.user) new_post.save() for img in original_post.video: shared = new_post.video.add(img) shared.save() return redirect('group:main',original_post.group.pk) Here is my model Post. -
django "can't adapt type '__proxy__'" error message
class GenderTypeEnum: FEMALE = 1 MALE = 2 UNKNOWN = 3 types = ( (FEMALE, _("Female")), (MALE, _("Male")), (UNKNOWN, _("Unknown")) ) class PersonModel(models.Model): identity = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=75) last_name = models.CharField(max_length=75) gender = models.PositiveIntegerField(choices=GenderTypeEnum.types) class StaffModel(models.Model): person = models.ForeignKey('PersonModel', on_delete=models.CASCADE, related_name='staffs') registration_number = models.CharField(max_length=50, unique=True) start_date = models.DateField() finish_date = models.DateField(null=True, blank=True) I am using the following query to list the gender statistics of the staff StaffModel.objects.values("person__gender").annotate(count=Count("person__gender")) output: [ {"person__gender":1, "count":1}, {"person_gender":2, "count":5} ] But gender field is a choices field so that, output that I want like this: [ {"person__gender":1, "gender_exp":"Male", "count":1}, {"person_gender":2, "gender_exp":"Female", "count":5} ] I created the following class by looking at the answer given to @bachkoi32 Display name of a choice field in Django while using annotate In order to output, I use this class: class WithChoices(Case): def __init__(self, model, field, condition=None, then=None, **lookups): fields = field.split('__') for f in fields: model = model._meta.get_field(f) if model.related_model: model = model.related_model choices = dict(model.flatchoices) whens = [When(**{field: k, 'then': Value(v)}) for k, v in choices.items()] return super().__init__(*whens, output_field=CharField()) I changed my query: qs = StaffModel.objects.values("person__gender").annotate(gender_exp=WithChoices(StaffModel, 'person__gender'), count=Count("person__gender")).values("person__gender","gender_exp","count") When I want to print the query result, it raise the error; django.db.utils.ProgrammingError: can't adapt type 'proxy' qs = … -
django input in form returns None
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="{% url 'newlink' %}" method="POST"> {%csrf_token%} <input type="text" name="urllink"/> <button type ="submit" id="submit">등록하기</button> </form> <div id="crawling"> title : {{crawling_title}} <img src="{{crawling_img_link}}"/> </div> </body> </html> ▲ rental_newlink.html def newlink(request): if request.method == 'POST': #폼 다채우고 저장버튼 눌렀을 때 url = request.GET.get("urllink") url_link = str(url) print("url link : ", url_link) driver = webdriver.Chrome('C:/Users/박철현/파일들/멋쟁이사자처럼/단풍톤/BILLIM/chromedriver') driver.get('https://book.naver.com/bookdb/book_detail.naver?bid=21312636') title = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="container"]/div[4]/div[1]/h2/a'))).text img = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="container"]/div[4]/div[1]/div[1]/div/a/img'))) img_link = img.get_attribute("src") print("이미지 링크 : ", img_link) driver.quit() return render(request, 'rental_newlink.html', {'crawling_title':title, 'crawling_img_link':img_link}) else: #글을 쓰기위해 들어갔을 때 return render(request,'rental_newlink.html') ▲ views.py The problem is url = request.GET.get("urllink") in views.py results in None value(from <input type="text" name="urllink">) I think request.GET.get("urllink") can't parsing the <input> in html. I don't know the reason why it can't parsing the <input> and returns None value. Rest of the Code work fine. (Below print("url link : ", url_link) works fine.) -
Integrate python-social-auth to drf-spectacular (Swagger)
I have a Django (DRF) project with OAuth2 based on python-social-auth and Swagger based on drf-spectacular. I need to integrate these two libraries together so that Swagger allow OAuth2 authorization, for example Google OAuth2. I found OAuth2 configuration for drf-spectacular in settings: SPECTACULAR_SETTINGS = { ... 'SWAGGER_UI_OAUTH2_CONFIG': { ... # Oauth2 related settings. used for example by django-oauth2-toolkit. # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#oauth-flows-object 'OAUTH2_FLOWS': [], 'OAUTH2_AUTHORIZATION_URL': None, 'OAUTH2_TOKEN_URL': None, 'OAUTH2_REFRESH_URL': None, 'OAUTH2_SCOPES': None, }, ... } But I'm not really sure whether it fits me or not. I wrote this in my version of this config, but it appearently has no effect: 'SWAGGER_UI_OAUTH2_CONFIG': { 'OAUTH2_AUTHORIZATION_URL': 'https://accounts.google.com/o/oauth2/auth', 'OAUTH2_TOKEN_URL': 'https://accounts.google.com/o/oauth2/token', 'OAUTH2_SCOPES': ['openid', 'email', 'profile'], } Swagger still has no OAuth2. Any idea how to manage it? -
how to submit a form and display output without refreshing
I'm trying to create a simple calculator which gets an input number from the user and shows the calculated output below it. The code works fine but it redirects and reloads the page, obviously. I don't want that I want the output to be displayed as soon as the user fills the form. I have 0 knowledge of js and ajax so I would appreciate you guys helping me with that part. I searched a lot but couldn't understand what to do. this is my form: <form id="myform" method="POST"> {% csrf_token %} Enter first number: <input type="text" name="num1"><br><br> <input type="submit"> </form> and this is the output bellow the form I want: <h1>congrats!</h1> as simple as that. fill the form, submit and display a simple message without refreshing