Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get all related objects of all objects in a Queryset?
Unfortunately I cant find a straight-forward answer to this even though there are several related quesitions. Say we have: class Category(models.Model): name = models.CharField(max_length=50) class SubCategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category,on_delete=CASCADE, related_name='subcategories') I know I can get all the subcategories of a specific category by some_category.subcategories.all() But how do I get a queryset of all subcategories of all categories in a queryset? -
Django forms field
class Registration(forms.Form): Name=CharField() So, CharField input is showing in the browser but when I submit this field without filling any data it's doesn't show django error. And if I apply min_length and max_length both are not working What should I do -
Is there a way to force django to check for static files in the current app before checking other apps
I'm working with multiple apps and it helps to have the static files named the same way. Is there a way to force Django to search for static files based on the app I'm working in? For example. For a page in app3, It should check app3/static first for "style.css" before checking app1 even though app1 also has "style.css" -
How to use Multiple Inheritance in Django Rest Framework
I have two serializers which are identical except for their parent class. One inherits from DRF's serailizers.Serializer. The other inherets from a class called HalModelSerializer from a package called drf_hal_json. class BriefcaseSerializer(HalModelSerializer): contexts = BriefcaseContextLinkSerializer(many=True, required=False) username = serializers.CharField(write_only=True) class Meta: model = Briefcase fields = ( 'contexts', 'username', ) class SimpleBriefcaseSerializer(serializers.Serializer): contexts = BriefcaseContextLinkSerializer(many=True, required=False) username = serializers.CharField(write_only=True) class Meta: model = Briefcase fields = ( 'contexts', 'username', ) In my views.py I've overridden the get_serializer_class method to select one of these two serializers depending on the Accept header in the request. typing both classes out in full is bad for obvious reasons. Eg if I change one and forget to change the other. My attempt to fix this was to use multiple inheritance. This is the first time I've ever tried to use multiple inheritance. Attempt: class BriefcaseMixin: contexts = BriefcaseContextLinkSerializer(many=True, required=False) username = serializers.CharField(write_only=True) class Meta: model = Briefcase fields = ( 'contexts', 'username', ) class BriefcaseSerializer(HalModelSerializer, BriefcaseMixin): pass class SimpleBriefcaseSerializer(serializers.Serializer, BriefcaseMixin): pass This didn't work. GET Requests now error with django.core.exceptions.ImproperlyConfigured: Field name `username` is not valid for model `Briefcase`. Note I did have a custom create method as well for POSTs that used username. I've … -
Django Create post and send mail
after saving my variables in views.py that I have forwarded, can I send them as mail while saving the same fields? My mail sending codes are below but I didn't know how to do it. def gcreate(request): if request.method == 'POST': gmember = gunluk( adsoyad=request.POST['adsoyad'], adsoyad2=request.POST['adsoyad2'], vardiya=request.POST['vardiya'], aciklama=request.POST['aciklama'], incident=request.POST['incident'], alinanaksiyon=request.POST['alinanaksiyon'], ulasilmayanekip=request.POST['ulasilmayanekip'], ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],) try: gmember.full_clean() except ValidationError as e: pass send_mail( 'test', 'testmessage', 'xx@xx.com', ['xx@xx.com'], fail_silently=False ) gmember.save() messages.success(request, 'Ekleme İşlemi Başarılı!') return redirect('/gunlukistakibi') else: return render(request, 'gcreate.html') -
How to pass value to Django Custom template tag's function
Got an error in my pet project: TemplateSyntaxError at /car/2/ 'get_car_info' did not receive value(s) for the argument(s): 'car_id' As I can see, function in custom template tags can not receive a value, but Django log shows that car_id variable is exists: Local vars Variable Value car_id 2 context {'spare_parts': <QuerySet [<Mileage: Рулевой наконечник Sasic 7674007>]>, 'title': 'Список запчастей для'} request <WSGIRequest: GET '/car/2/'> models.py class Car(models.Model): brand = models.CharField(max_length=40, db_index=True, verbose_name="Марка") model_name = models.CharField(max_length=60, db_index=True, verbose_name="Модель") model_variant = models.CharField(max_length=100, db_index=True, verbose_name="Модификация") age = models.SmallIntegerField(verbose_name="Год выпуска") views.py (commented code moved to custom template tags) def get_car_spare_parts(request, car_id): spare_parts = Mileage.objects.filter(car_id=car_id) # car = Car.objects.get(id=car_id) context = { 'spare_parts': spare_parts, 'title': 'Список запчастей для', # 'model_name': car.model_name, # 'brand': car.brand, # 'car_age': car.age, } return render(request, 'mileage/car.html', context) urls.py urlpatterns = [ path('car/<int:car_id>/', get_car_spare_parts, name='car_spare_parts'),] mileage_tags.py @register.simple_tag def get_car_info(car_id): car = get_object_or_404(Car, car_id=car_id) return car car.html {% extends 'base.html' %} {% load mileage_tags %} {% block head %} <title>{{ title }}</title> {% endblock %} {% block body %} <h1>{{ title }} {{ brand }} {{ model_name }} {{ car_age }} г./в.</h1> {% get_car_info %} <ol class="list-group list-group-numbered"> {% for item in spare_parts %} <li class="list-group-item"><a href="{% url 'spare_parts_mileages' item.car_id item.spare_part_id %}">{{ … -
convert timestamp to date in custom commands
i am creating custom commands in django. i have a problem with conversion timestamp to date by methods like fromtimestamp. i have such error: line 13, in handle timest_conv = datetime.fromtimestamp(timest) OSError: [Errno 22] Invalid argument this is my class with handle class Command(BaseCommand): def handle(self, *args , **options): r = requests.get('https://api.metals.live/v1/spot/silver').json() price = r[0]['price'] timest = r[0]['timestamp'] timest_conv = datetime.fromtimestamp(timest) print(price,timest, timest_conv ) return -
Django won't show models pictures in templates
images used to show but i think I have changed something that made it won't show this is my files if you could find the issue that made pictures don't show i would be glad this is my model.py : from django.db import models import uuid from django.contrib.auth.models import User from django.db.models.expressions import F from django import forms class Author(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50) description = models.TextField(max_length=1000) id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) image = models.ImageField(null=True, blank=True, default='default_EtYECuR.jpg', upload_to='profilePics') email = models.EmailField(max_length=200, null=True, blank=False) password = models.CharField(max_length=50, null=True, blank=False) brief = models.CharField(max_length=100, null=True, blank=True) skills = models.ManyToManyField('Skill', blank=False) def __str__(self): return self.name class Skill(models.Model): name = models.CharField(max_length=100, blank=False, null=True) description = models.TextField(max_length=500) uuid = models.UUIDField(unique=True, primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.name and this is what I wrote for static files in settings.py: DEBUG = TRUE . . . . STATIC_URL = '/static/' MEDIA_URL = '/img/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/img') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') this is my function in views.py def profiles(request): profiles = [profile for profile in Author.objects.all()] return render(request, 'users/index.html', {'profiles': profiles}) and this is my template {% for profile in profiles %} <div class="column card"> <div class="dev"> <a … -
Module 'project_name' has no attribute 'celery'
I'm trying to set up a background task using celery and rabbitmq on django but I'm getting an error saying that my project has no attribute celery. I'm using PyCharm and installed celery through that. I'm new to celery but I've read a lot of articles similar to this issue (AttributeError: module 'module' has no attribute 'celery' this one seems the closest but not sure it's quite the same) Project structure: project_name ├──project_name | ├── settings.py ├──app_name1 | └──celery.py ├──app_name2 | └──tasks.py I run the following command: celery -A project_name worker -l info --pool=solo But I get the following error: Error: Invalid value for "-A" / "--app": Unable to load celery application. Module 'project_name' has no attribute 'celery' celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') app = Celery('project_name') app.config_from_object('django.config:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py file: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y -
Procfile for Heroku
So Heroku's explanation is useless if you don't already know what you're doing and I have no clue what should go in my Procfile. I tried: web: python appname.py because I found an example like that for python apps (I used Django so used the python build). Further searching didn't make things any clearer except for that I might need to use gunicorn instead of python. I found various posts suggesting various formats such as: web gunicorn web:gunicorn web: gunicorn I have no clue what should come after gunicorn, some posts have the programming language, some have an IP address, some have various other things. Some suggest running: heroku ps:scale web=1 but that results in an error: Scaling dynos... ! ! Couldn't find that process type (web). I just haven't got a clue and don't know where to turn; Heroku explains nothing. -
Django | admin account page group display
I created a custom admin page with a custom user account, but in the admin page when editing a user the group section is not showing properly admin.py: class AccountAdmin(UserAdmin): list_display = ('id' , 'email','username' , 'first_name' , 'last_name' , 'date_joined', 'is_admin' , 'is_staff') search_fields = ('email','username' , 'first_name' , 'last_name' ) readonly_fields = ('id','date_joined' , 'last_login') filter_horizontal = () list_filter = () fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name','last_name')}), ('Permissions', {'fields': ('is_active','is_staff', 'groups')}), ('Dates', {'fields': ('last_login', 'date_joined')}), ) admin.site.register(Account ,AccountAdmin) models.py class Account(AbstractBaseUser , PermissionsMixin): id = models.UUIDField(verbose_name="ID" , primary_key=True, default=uuid.uuid4, editable=False, unique=True) email = models.EmailField(verbose_name="email",max_length=64,unique=True) username = models.CharField(max_length=32, unique=True) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) date_joined = models.DateTimeField(verbose_name="date joined",auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login",auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name' , 'last_name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Admin view: -
Getting Search Query and Pagination at the same time in Django in request.GET
class HomeView(ListView)://views.py model=Movement template_name='home.html' paginate_by = 10 def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) mov_objs = Movement.objects.all() paginator = MyPaginator(mov_objs, self.paginate_by) page = self.request.GET.get('page', paginator.num_pages) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context['page_obj'] = page_obj ids=list(page_obj.object_list.values_list('id', flat=True)) sale_id = str(Sale.objects.filter(stored_ids=sorted(ids))).split('(')[1].split(')')[0] if self.request.method == 'GET': inv_no = self.request.GET.get('inv_no','0') context['inv_no']=inv_no else: inv_no = '0' sale_data=sale_id+','+inv_no context['sale_data']=sale_data return context def TallyExport(request,sale_data): t = loader.get_template('template.xml') [sale_id , inv_no] = [int(item) for item in sale_data.split(',')] mov_obj_ids = Sale.objects.filter(id=sale_id).values_list('stored_ids')[0][0] mov_obj = Movement.objects.filter(id__in=mov_obj_ids) response = HttpResponse(t.render({'mov_obj':mov_obj,'inv_no':inv_no}), content_type="application/xml") response['Content-Disposition'] = 'attachment; filename=file.xml' return response <center><h1>Title Page</h1></center> <h4> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page=1">&laquo; first</a> <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Sale {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page={{ page_obj.next_page_number }}">next</a> <a href="?{% if inv_no %}inv_no={{inv_no}}&{% endif %}page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </h4> <form method="GET"> <input type="number" id="inv_no" name="inv_no" placeholder = "Invoice No"> <input type="submit" value="Save"> </form> {% if 'inv_no' in request.GET %} <a href="{% url 'tally' sale_data %}">Export To Tally</a> {% endif %} <ul> {% for post in … -
Best practice for designing models in Django project?
I am currently creating a hobby project using Django and am completely new to web dev. It's just a basic language tutoring application. Where a user can visit the website, click on which language they want to learn, and then select a tutor to learn from based on the language chosen. Currently, I was thinking of designing the database with the following tables - Languages, Tutors, Students - not sure if I should add any more? My main question is - if I create a languages app, can I just define all 3 models within that app and then use those same models in every other app I create? For example, I have a language app with the models - language, tutor and student If i create a booking system app, can I use those same models within that app? -
How to safely make Typescript work with a custom backend API
I am making use of API endpoint routes in my application. In these endpoints http requests about the data are processed by the backend with the help of a PRISMA ORM. However, i have to use something else for the frontend and started to write typescript types that resemble my backend types. This is very counterintuitive coming from programming languages like haskell or other typed languages. It seems the endpoint sits in the middle and is a source of all kinds of incompatibilities that might arise in the future. Because now I have 3 points of failure, the endpoint, the API and frontend typescript types (that are not even compiled and available at runtime.) Is there a more type-safe way to fix the endpoint-in-the-middle-problem? I've looked at several obscure fullstack projects such as Urweb and the less obscure Django but they lack an expressive templating language such as in Svelte or Vue. Are there other ways to make automatic type safe api endpoint code? -
Django get() got an unexpected keyword argument 'slug'
I need to use Korean in the url, but it doesn't work. views.py class BuildingInfoAPI(APIView): def get(self, request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(self, request): queryset = ReviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] I've tried slug:slug and url with re_path, but these methods says 'page not found' so I tried str:slug but it says get() got an unexpected keyword argument 'slug' This is slug data in my model. slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) 'allow_unicode' allows using Korean in the url. I can't find which code is wrong. Is there any problem with views.py or urls.py? -
Python Django Operational error, no such table
I'm trying to use a sqlite database from a different project in my django project. I've added the .db file to my project structure and added the following code (new database contains info about companies): In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'companies':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'companies/db/company_financials002.db' } } In companies/admin.py: from .models import Companies, RowData, StatementRows, Statements admin.site.register(Companies) admin.site.register(RowData) admin.site.register(StatementRows) admin.site.register(Statements) Next, I ran the manage.py makemigrations and migrate If I log into the admin panel, all tables are shown: admin panel However, if I try to access a table it hits me with an operational error/no such table: error message The autogenerated models says in the top comments: Remove managed = False lines if you wish to allow Django to create, modify, and delete the table so I did. I'm really at a loss as to how to acces my data now and I can't seem to find the solution anywhere on the internet. -
I get ModuleNotFoundError although i have the module in my django project
I am using Django 3.2.8 and also Django Rest Framework. Also using python 3.6.8. My directory structure is : iomobileproj >>iomobileapp ... apps.py ... >>iomobileproj ... settings.py ... In apps.py : from django.apps import AppConfig class IomobileappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'iomobileapp' In settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'iomobileapp.apps.iomobileappConfig' ] When i try to run the project i get below error : ModuleNotFoundError: No module named 'iomobileapp.apps.iomobileappConfig'; 'iomobileapp.apps' is not a package. But module is there. I am running similar project with same config in another project without error. -
self.scope['user'] always shows me the same user, Django Channels
I am a beginner in Django Channels and I try to make a chat app. I think everything works fine, but the problem is that the message is not send to both of users connected to the room. I think the problem is inside consumer.py in user = self.scope['user'] becuase if I print the user it shows me every time only the first user that wrote something. So if I have two users: user1 and user2 and if user2 write something as first, it user = self.scope['user'] will always give me the second user. I am using Redis by WSL2. an example console log if one of the user send something: receive {'type': 'websocket.receive', 'text': '{"message":"abc"}'} message {'type': 'chat_message', 'text': '{"message": "abc", "username": "test"}'} message {'type': 'chat_message', 'text': '{"message": "abc", "username": "test"}'} templates/thread.html {% extends "base.html" %} {% block content %} <h3>Thread for {% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif %}</h3> <ul id='chat-items'> {% for chat in object.chatmessage_set.all %} <li>{{ chat.message }} via {{ chat.user }}</li> {% endfor %} </ul> <form id='form' method='POST'> {% csrf_token %} <input type='hidden' id='myUsername' value='{{ user.username }}'/> {{form.as_p }} <input type='submit' class='btn btn-primary'/> </form> {% endblock %} {% block … -
Best practice for validating a date in url in django?
I have a logging system, where users can log several symptoms for any given day. Im getting the date as slug in my url, but I need to validate it. Which one is best practice, and why? make a validator function in the class view and use it there add a hidden form field, and write a custom DateValidator for it? -
Relation "auth_user" does not exist error when running a GitHub action
I have the following GitHub CI configuration for the Django app. The action fails on error relation "auth_user" does not exist. The project has a custom authorization model AUTH_USER_MODEL = "uzivatel.User", which is developed in the uzivatel app. Here is the ci.yml file. The project configuration can be found here: https://github.com/ARUP-CAS/aiscr-webamcr/blob/dev/webclient/webclient/settings/base.py. name: Django Tests on: push: branches: - dev jobs: build: runs-on: ubuntu-20.04 services: postgres: # we need a postgres docker image to be booted a side car service to run the tests that needs a db image: postgis/postgis env: # the environment variable must match with app/settings.py if block of DATBASES variable otherwise test will fail due to connectivity issue. POSTGRES_USER: test_user POSTGRES_PASSWORD: test_secretpass POSTGRES_DB: test_db ports: - 5432:5432 # exposing 5432 port for application to use # needed because the postgres container does not provide a healthcheck options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install wheel pip install -r webclient/webclient/requirements/dev.txt - name: Install gdal dependencies run: | sudo apt-get update sudo apt-get install -y libgdal-dev locales gdal-config --version … -
Error when adding a warning before deleting a django model record
I am looking to popup a model warning about the deletion of a model record, however when looping into a table, all links lead to delete the very first record in the table, what I am doing wrong? Here is my code: #models: class Company(models.Model): teamname = models.CharField(max_length=100,unique=True) address = models.CharField(max_length=300) office = models.CharField(max_length=100) def __str__(self): return self.teamname class Meta: ordering = ['teamname'] class Contact(models.Model): teamname = models.ForeignKey(Company,on_delete=CASCADE) firstname = models.CharField(blank=True,null=True,max_length=20) lastname = models.CharField(blank=True,null=True,max_length=20) position = models.CharField(max_length=30,choices=( ('Option1','Option1'), ('Option2','Option2'), )) cellphone = models.CharField(max_length=30,null=True,blank=True) email = models.EmailField(blank=True,null=True) birthday = models.DateField(blank=True,null=True) def __str__(self): return str('%s, %s' % (self.lastname, self.firstname)) class Meta: ordering = ['id','position','lastname','firstname'] html/bootstrap code: <table id="datatable" class="table table-bordered dt-responsive nowrap w-100"> <thead> <div style="text-align: center;" class="card-body"> <h4>Contact list</h4> </div> <tr> <th style="text-align: center;">First name</th> <th style="text-align: center;">Last Name</th> <th style="text-align: center;">Position</th> <th style="text-align: center;">Cellphone</th> <th style="text-align: center;">Email</th> <th style="text-align: center;">Birthday</th> <th style="text-align: center;">Edit</th> <th style="text-align: center;">Delete</th> </tr> </thead> {% for j in obj2 %} <tbody> <tr> <td style="text-align: center;">{{j.firstname}}</td> <td style="text-align: center;">{{j.lastname}}</td> <td style="text-align: center;">{{j.position}}</td> <td style="text-align: center;">{{j.cellphone}}</td> <td style="text-align: center;"><a href="mailto:{{j.email}}">{{j.email}}</a></td> <td style="text-align: center;">{{j.birthday}}</td> <td style="text-align: center;"><a href="/clients/edit/contact/{{j.id}}" class="text-success"><i class="mdi mdi-pencil font-size-18"></i></a></td> <td style="text-align: center;"> <i style="color: red; font-size: 16px; cursor: pointer;" data-bs-toggle="modal" data-bs-target="#deleteRecord" class="bx bx-trash"></i> </td> <div class="modal … -
Django DurationField and 00:00:00 versus NULL
Using Django 3.2.7, python 3.9.x and Mysql 8.x. With models like this: class Object(models.Model): period = models.DurationField('Period', null=False, blank=False, default=timedelta(days=1)) class Subobject(models.Model): object = models.ForeignKey(Object, null=False, blank=False, on_delete=models.CASCASE) period = models.DurationField('Period', null=True, blank=True) and the following query: sub_objs = Subobject.objects.select_related( 'object' ).annotate( actual_period=Case( When( period__isnull=False, then=F('period') ), default=F('object__period'), output_fields=models.DurationField() ) ).filter( actual_period__gte=timedelta(seconds=3600) ) Which could be humanly translated as: "for each subobject, assign a variable named actual_period, whose value is period when found 'locally' in each object, with a fallback to the parent object.period property when not; then filter, etc." This works, but let us imagine a case where a subobject has to have a period property set to "no time at all", i.e., a timedelta == 0 seconds. I tried setting a subobject.period field to 00:00:00 in the admin, or to timedelta(seconds=0) programmatically, and it seems django (Mysql?) always considers such a timedelta as being null. The consequence being that, in the above query, the parent object's period property is applied in the annotation. Is this working as intended? Is there a way to have django/mysql consider that a "zero-time timedelta" is not a null value? -
Django sudden error: "AuthMissingParameter at /complete/google-oauth2/", when using GoogleOAuth2 from social-auth-app-django package
I have a running Django application (runs for already 2 years+). I'm using the social-auth-app-django to manage my users authentication with Google. Suddenly today i got errors from users that can not get inside my app. I also get the same error on my local and production environment: My settings.py related params are: AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) ## Google Credentials SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('GOOGLE_AUTH_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('GOOGLE_AUTH_SECRET') print("TESTING") print("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY:\n", SOCIAL_AUTH_GOOGLE_OAUTH2_KEY) print("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET:\n", SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://MyAppHost/complete/google-oauth2/' # Login URL LOGIN_URL = '/login/google-oauth2/' # Where user is directed after login/logout LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' I double verified that the SOCIAL_AUTH_GOOGLE_OAUTH2_KEY and SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET really match what i see in the google API-credentials page Moreover, i verified that my Authorized redirect URIs configured properly. When i try to enter the URL presented in the redirect_uri (http://localhost:5000/complete/google-oauth2/) i get the error: AuthMissingParameter at /complete/google-oauth2/ Missing needed parameter state Request Method: GET Request URL: http://localhost:8000/complete/google-oauth2/ Django Version: 2.2.3 Exception Type: AuthMissingParameter Exception Value: Missing needed parameter state Exception Location: /Volumes/dev/venv/lib/python3.6/site-packages/social_core/backends/oauth.py in validate_state, line 85 Python Executable: /Volumes/dev/venv/bin/python3 Python Version: 3.6.2 -
Getting commanderror although i set debug is true in django settings
I am using django 3.2.8. I set DEBUG = True and ALLOWED_HOSTS = ['*'] in my project settings.py file. When i try to "python3 manage.py runserver" it gives below error. I is strange, because DEBUG is set to True in settings.py. But it says debug is false. Also i have this setting in my other project and it is working with Debug=True. -
Django view get() takes 1 positional argument but 2 were given
I am making API with Django. Crawled data is saved well in DB, but I have a problem with making API. views.py from django.shortcuts import render from rest_framework.response import Response from .models import ReviewData from .models import BuildingData from rest_framework.views import APIView from .serializers import ReviewSerializer from .serializers import BuildingSerializer from django.shortcuts import render, get_object_or_404 class BuildingInfoAPI(APIView): def get(request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(request): queryset = ReviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<slug:slug>/', ReviewListAPI.as_view()) ] serializers.py from rest_framework import serializers from .models import ReviewData from .models import BuildingData class BuildingSerializer(serializers.ModelSerializer) : class Meta : model = BuildingData fields = '__all__' class ReviewSerializer(serializers.ModelSerializer) : class Meta : model = ReviewData fields = '__all__' models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc …