Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Database Connections spiking randomly
I have an application with Django as backend. It is hosted on the EC2. The database is hosted on the AWS RDS Postgres SQL. The Connections to the database keep spiking to the maximum limit, even though we do not have that much users. The application is used by merely 10 people in the organization but the connections spike up to 80. Can anyone suggest what can be the issue behind this? I think it might be causing due to multiple requests from a single client leading to multiple connections. It will be great if somebody can help me out t find the cause. I tried redeploying the server as well as rebooting the rds instance but there is no change. I even tried adding the idle connection termination parameter through the rds parameter groups. When I checked the db for connection details, I saw multiple connections from same user ids. Can this be related to the issue? -
i can not install django framework on my pc. it showing " C:\Users\HomePC\AppData\Local\Programs\Python\Python312\python.exe: No module named pip"
i cannot not install django frame work on my pc it showing " i have modify my python to latest version and still showing that -
Making instances of Django records with a through model
Let's say you have a concept of a Battle, and in that battle there are Players and Enemies. The players are a simple ManyToMany, but Enemies require a Through model, because if there's a DB entry for "Goblin", players need to fight an INSTANCE of the Goblin model. Players may fight many Goblins, and each needs their own health/status at any given moment. So far, I've got a Django model like so (I'm simplifying the code for readability, and to focus on the main issue) class Battle(models.Model): players = ManyToMany(Player) enemies = ManyToMany(Enemy, through=EnemyThroughModel) With the appropriate adjustments to admin.py and such, this works in that I can attach multiple Enemies to a Battle and see them listed separately in admin, HOWEVER, those are all keyed to the same basic Enemy, and if I change one of them (say, they take damage), ALL the keyed references to that enemy now have their health reduced. Is there a neat way I can use through models to create a new instance of the enemies, so that they have independent health/mana/etc? -
VSCode not discovering pytests for Django Project
I am new to Pytest & Django, so all feedback and improvements are welcome. I am trying to use VSCode's testing sidebar with my Django Project, but it is unable to find the pytest files. Here are the commands I've run to create this example project: django-admin startproject LearningPytest pip install django-pytest Then I've created two files: pytest.ini and basic_tests.py, so my folder structure is as follows. DjangoPyTesting/ └───LearningPytest/ ├───LearningPytest/ │ ├───__init__.py │ ├───asgi.py │ ├───basic_tests.py │ ├───settings.py │ ├───urls.py │ ├───wsgi.py ├───manage.py └───pytest.ini pytest.ini [pytest] DJANGO_SETTINGS_MODULE = LearningPytest.settings python_files = tests.py test_*.py *_tests.py python_classes = Test* python_functions = test_* basic_tests.py class TestBasicMath: def setup_method(self, method): self.x = 2 self.y = 3 def test_addition(self): assert self.x + self.y == 5 def test_subtraction(self): assert self.y - self.x == 1 def test_multiplication(self): assert self.x * self.y == 6 Here is the problem, I want to use VSCode's sidebar to run my tests, but it cannot find them. This confuses me, because within my project if I run the following command: DjangoPytesting\LearningPytest>pytest it works successfully platform win32 -- Python 3.11.5, pytest-7.4.4, pluggy-1.3.0 rootdir: C:\Users\{me}\Desktop\DjangoPytesting\LearningPytest configfile: pytest.ini plugins: anyio-4.3.0, django-4.9.0 collected 3 items LearningPytest\basic_tests.py ...platform win32 -- Python 3.11.5, pytest-7.4.4, pluggy-1.3.0 rootdir: C:\Users\{me}\Desktop\DjangoPytesting\LearningPytest configfile: … -
Django backend user registration
I'm currently writing a system with users creation process involved. The system will have a 'site-administrator' who can create (and modify, delete) users. However, I'm stuck with the part of creating users. What I want is: Site Administrator creates a user Django will create a one time password and send this to the user (based on email) User logs in System detects it's the first time and forces the user (via frontend) to update password User updates password and logs in with new credentials Bearer tokens (access / refresh) are issued The frontend is VUE (with axios, pinia etc) but that's of no use for this question. The backend is Django, Djano Rest Framework, SimpleJWT and a MariaDB for storing info on the backend. Thank you for taking the time to answer this question. -
django stops running when i send an request to api
In the rest api I have a view that sends an otp sms to the user's phone . when I send a request to my api , It just sends another request to other server and waits for the response But It takes a while and django just stops working . I am worry about it . what if upload it to server and django can't handle multi requests and crashes in the real server with different request from multiple users? How can I fix this problem ? Also mu CPU has only 2 cores and I don't think using multi threading is an good idea! -
Automatically starting task queue for django-background-tasks
I'm building an application which involves a task queue from django-background-tasks. The issue that I'm facing is that I can't seem to start the queue automatically and have to manually run process_tasks in my application container. I've already tried running the process_tasks command within my Dockerfile, however this seems to not do anything as open tasks are not resolved. CMD ["bash", "-c", "python manage.py runserver 0.0.0.0:8000 && python manage.py process_tasks"] Has anyone experienced this issue, and if so how did you handle it? I tried to run the process_tasks command in my Dockerfile after executing runserver , I expected this to automatically start the task queue, however this did not yield any result. -
Django: Dynamic form doesn't correctly handle boolean inputs
This is a small form I have and dynamically construct: class AddonForm(Form): def __init__(self, addons, *args, **kwargs): super().__init__(self, *args, **kwargs) self.addons = {str(addon.pk): addon for addon in addons} for pk, addon in self.addons.items(): self.fields[str(pk)] = BooleanField(required=False, label=f"{addon} (x{addon.price_multiplier})") This is how I use it: form = AddonForm(ItemAddonTemplate.objects.filter(item=item_template_id), request.POST) if form.is_valid(): addons = form.cleaned_data This is the request.POST: <QueryDict: {'csrfmiddlewaretoken': ['cJS1fhGY3WqIflynGbZIh9TiRj8F9HjgoLOUL6TwWY4j4cotALGHpFDyQwjLiLMW'], '3': ['on'], '32': ['on']}> but when I print addons I see this: {'3': False, '30': False, '31': False, '32': False, '33': False, '34': False} 3 and 32 should be True. This is Django 5.1 and Python 3.12. -
What exactly are Django Widgets?
I am a little confused as to what exactly Django Widgets are. From https://docs.djangoproject.com/en/5.1/ref/forms/widgets/: The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget." What exactly is meant by extraction of data from GET/POST dict? That is done by the passing data argument to form instantiation, how does Widget come into picture here? If I understood correctly, Widgets just create the HTML <input> tags, and take attr parameters that set attributes of this input tag, viz. size (in case of text input), required (override on the field required value), class, etc. So how exactly do packages like crispy-forms+crispy-bootstrap5, django-bootstrap5 differ from these Widgets? And what do they do with Django Widgets? Also, these packages have parameters when rendering a field where css_class (the actual class of the input) can be modified. How does this play with Widget attr['class']? Does Django have templates for each Widget in files (like rest of the templates in the Django template system)? -
How to remove a field that was added by mistake from a form in Django
I have 3 password fields. The first one (password) is useless, it doesn't do anything literally. password1 and password2 are the real fields that are working.problem I was trying to change password and password2 ---> password and confirm password. But it didn't work, so I returned it back to password and password2, but it did this and I can't remove the extra password field that appeared there. I deleted the sql file and the migrations file and make migrations from the beginning and it didn't work.code -
How do password managers store passwords which can be shown in plain text in ui
So, I am building a password manager like Bitwarden. I have come to a point where I need to store passwords which the user provides and then later show the user the password in plain text obviously. Now my question is that how can I store passwords carefully without hashing otherwise they wont be in plain text next time the user wants it? I am building an API in Django https://github.com/Abled-Taha/apm-server -
Django Forms initials not working for some fields?
Something weird is happening. I am trying to get initial fields into my form but only some of then are filled. The address, latitude and longitude wont. this is my form: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'cpf', 'phone', 'email', 'address', 'street_name', 'street_number', 'address_complement', 'country', 'state', 'city', 'pin_code', 'latitude', 'longitude',] This is my view: default_values = { 'first_name': request.user.first_name, 'last_name': request.user.last_name, 'cpf': request.user.cpf, 'phone': request.user.phone_number, 'email': request.user.email, 'address': checkout_address.address, 'street_name': checkout_address.street_name, 'street_number': checkout_address.street_number, 'address_complement': checkout_address.address_complement, 'country': checkout_address.country, 'state': checkout_address.state, 'city': checkout_address.city, 'pin_code': checkout_address.pin_code, 'latitude': checkout_address.latitude, 'longitude': checkout_address.longitude } form = OrderForm(initial=default_values) When I print the default_values I got all right: {'first_name': 'Admin', 'last_name': 'Sistemas', 'cpf': '9999999', 'phone': '98989898', 'email': 'rm@rm.com', 'address': 'Rua dos Lamentos, 10, Armação dos Búzios - RJ', 'street_name': 'R. dos Lamentos', 'street_number': '10', 'address_complement': 'ap32', 'country': 'Brasil', 'state': 'Rio de Janeiro', 'city': 'Armação dos Búzios', 'pin_code': '28950-000', 'latitude': '-22.7980796', 'longitude': '-41.9321335'} But by some how those three fields are not filed: Does someone could give me a tip on what the wack is going on? I tried to take some fields out and in but those three fields wont appear! Thank you very much for any help! -
Django model class vs a dictionary for storing reference values
I'm fairly new to Django, and while creating a project, I've been going back and forth between using a fixed value dictionary for certain reference values, or using another model class which is referred using a Foreign Key field. A part of the code using the model class option is as follows: Models with reference values: class MaterialCategory(models.Model): name = models.CharField(max_length=32, unique=True, help_text="A primary class of materials.") class Meta: verbose_name_plural = 'Material categories' constraints = [ UniqueConstraint( Lower('name'), name='materialcategory_name_case_insensitive_unique', violation_error_message="Material category already exists in " "the database!" ), ] class ComponentType(models.Model): """Model for key component types of a water supply scheme.""" name = models.CharField(max_length=100, unique=True, help_text="Main categories of a water system") def __str__(self) -> str: return self.name class Meta: ordering = ["name", "id",] An example model referring to above: class Chlorinator(models.Model): """Model representing a chlorinator.""" CHOICES_YES_NO = {"yes": "Yes", "no": "No", "na": "Not applicable"} CHLORINATOR_TYPES = { 'cc' : 'Constant head chlorinator', 'nc' : 'Simple tank (non-constant head)', 'dp' : 'Chlorine dosing pump', 'gc' : 'Gas chlorination system', 'o' : 'Other', } id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text="Unique ID for the chlorinator instance", ) component_type = models.ForeignKey( ComponentType, on_delete=models.RESTRICT, limit_choices_to=Q(name__istartswith='treatment'), default='' ) chlorinator_type = models.CharField("Chlorinator type", max_length=2, choices=CHLORINATOR_TYPES) material = … -
Django post comments not working correctly
I'm trying to create a system for my Django project that allows users to post comments on specific posts. However, this isn't working. I tried to enter code into forms.py, views.py, urls.py and index.html in order to handle post entries. However, this has instead resulted in the submit button on index.html being without input boxes, and when it's clicked the page reloads with no update to the database. forms.py: class PostCommentForm(forms.ModelForm): class Meta: model = PostComment fields = ['post_comment'] views.py: from .forms import PostCommentForm from .models import * def post_comment(request, post_id): post = get_object_or_404(Post_Data, pk=post_id) if request.method == 'POST': form = PostCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.post = post comment.save() return redirect('/', pk=post_id) else: form=PostCommentForm() return render(request, 'index.html', {'form': form}) urls.py: from .views import create_post urlpatterns = [ path('post/<int:post_id>/comment/', views.post_comment, name='post_comment'), ] index.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit Comment</button> </form> models.py: class PostComment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post_Data, on_delete=models.CASCADE) post_comment = models.CharField(max_length=500) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Comment by {self.user} on {self.post}" -
How can I make a nested Serializer available inside the create() of a ModelSerializer without making the nested Serializer read_only=False
I'm in a bit of a dilemma. The task is to take in a json that has some Info about a Bunny Litter and the Birthed Bunnies. I got a ThrowInfoSerializer with the Throw Model (Throw = Litter, non-english speaking country). Inside the create of the ThrowInfoSerializer I want to save a new Litter and the corresponding new Bunnies so I call new_bunnies = validated_data.pop('new_bunnies') and want to extract the new Bunny data from the validated_data. The problem is: since the new Bunny data is stored inside another ModelSerializer that is linked to the Bunny Model, and is BunnySerializer(many=True, read_only=True) read_only it isn't available in the validated_data inside the create(). But if I want to make new_bunnies read_only=False to make the info part of the validated_data inside create() i get this error: AttributeError: Got AttributeError when attempting to get a value for field `new_bunnies` on serializer `ThrowInfoSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Throw` instance. Original exception text was: 'Throw' object has no attribute 'new_bunnies'. Which makes sense since the the ThrowInfoSerializer is tied to the Throw Model. I can't really make another serializer and put ThrowInfoSerializer and the BunnySerializers … -
How to change parent class from models.Model to PolymorphicModel
I have two django models, Tomato and Potato. Both are being referenced multiple times across my project. I recently created a foreign key field in a third model, ShoppingBag, which should be allowed to contain one instance from either Tomato or Potato. My first approach was to create an empty (since Tomato and Potato have no fields in common) superclass Buyable, which inherits PolymorphicModel. I then set the referenced model in ShoppingBag.myforeignkey to accept instances of Buyable and I thought that would be it. I am now facing lots of errors, mostly because Potato.id and Tomato.id are being replaced by .buyable_ptr and the already existing foreign key and m2m fields to Potato and Tomato don't really like that. I wanted to ask if there's an official way to face this switch between parents or an alternative, easier way to tackle this issue. I created a function that generates a new instance of the super class and returns its id. I then set that function as the default value in the migration file. The solution didn't work, as the generated id was always 1. import Buyable def generate_id(): new_instance = Buyable() new_instance.save() return new_instance -
How to Customize Validation Error Response in Django REST Framework?
I am developing a RESTful API using Django REST Framework (DRF) and I need to implement a common error handling mechanism for various validation errors that occur throughout the application, including but not limited to JWT authentication failures. when validation errors occur, DRF returns default error responses that may not be user-friendly or consistent across different endpoints. For example, a JWT token validation error produces a response that looks like this: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } I would like to standardize the error responses throughout my application to improve the user experience. Specifically, I want to create a common function that can return a structured error response for all validation errors in the following format: { "status": false, "responseCode": 0, "message": "Validation ", "data": {} } I tried by creating custom_exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: custom_response_data = { 'status': False, 'responseCode': 0, 'message': 'Validation error', 'data': {} } if isinstance(response.data, dict): errors = {} for field, detail in response.data.items(): if isinstance(detail, list): errors[field] = detail[0] if detail else 'Invalid … -
Django Progress bar for the backend to later integrate with frontend
I want to implement a progress bar since the request takes some time to give out the response when the api request is called i want the progress bar to start from 0 to 100 when the response loads views.py: class AllNodeReportView(View): def get(self, request, *args, **kwargs): start_date = request.GET.get('start') end_date = request.GET.get('end') format_type = request.GET.get('format', 'json') try: start_datetime = datetime.strptime(start_date, '%Y-%m-%d') end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1) except ValueError: return JsonResponse({"error": "Invalid date format. Use 'YYYY-MM-DD'."}, status=400) nodes = Node.objects.only('mac', 'location', 'unicast') response_data = [] node_unicasts = nodes.values_list('unicast', flat=True) loc_tag_relations = LocTagRelation.objects.filter( unicastAddr__in=node_unicasts, uuid__gte=start_datetime.timestamp(), uuid__lt=end_datetime.timestamp() ).values('unicastAddr', 'tagMac').annotate( intime=Min('uuid'), outtime=Max('uuid') ).order_by('tagMac', 'intime') loc_tag_relation_map = {} for relation in loc_tag_relations: if relation['unicastAddr'] not in loc_tag_relation_map: loc_tag_relation_map[relation['unicastAddr']] = [] loc_tag_relation_map[relation['unicastAddr']].append(relation) tag_macs = [relation['tagMac'] for relation in loc_tag_relations] tag_data = TagHistory.objects.filter( mac__in=tag_macs, lastUpdated__gte=start_datetime.timestamp(), lastUpdated__lt=end_datetime.timestamp() ).order_by('mac', 'lastUpdated') tag_data_map = {} for entry in tag_data: if entry.mac not in tag_data_map: tag_data_map[entry.mac] = [] tag_data_map[entry.mac].append(entry) for node in nodes: if node.unicast in loc_tag_relation_map: for relation in loc_tag_relation_map[node.unicast]: tag_mac = relation['tagMac'] if tag_mac in tag_data_map: tag_entries = tag_data_map[tag_mac] current_location = None entry_time = None entry_date = None # Capture the actual date of entry last_exit_time = None ongoing_entry = None for tag_entry in tag_entries: timestamp = datetime.fromtimestamp(float(tag_entry.lastUpdated)) … -
Apache Superset embed Dashboard with Guest Token in DJango
I have the following setup. I'm running a Django Application with Postgres and Apache Superset on the same network (through docker-compose). The setup works fine; I can access my data (Postgres) from both the Django application and Superset. I have created a dashboard in Superset with some data and want to embed it on a DJnago page. I have already enabled dashboard sharing and I can use an iFrame to do so. However, this works because I have an active tab in the same browser with Superset, which I'm logged in to. If I go to another browser, the embedded Superset dashboard will show the login page. This is logical. However, how can manage a guest login from my Django application to the Superset so my users won't receive Superset's login page? I've tried the following code, in which I'm using Superset Guest Token API, I managed to receive a token successfully but every time I'm going to access the following URL, I'm redirected to Superset's login page with a red message "Access Denied". http://localhost:8088/superset/dashboard/1/?access_token=TOKEN/?standalone=4 <- 1 is the dashboard ID import requests import json url = "http://127.0.0.1:8088/api/v1/security/login" headers = { 'Content-Type': 'application/json' } payload = json.dumps({ "username": "guest_username", "password": … -
Django: Custom BaseInlineFormSet. Extra forms
I'm trying to implement an inline for the Product model admin, so that in addition to the forms for existing ProductAttribute relationships, forms for all attributes of the category of the product currently being edited are also added by default. The problem is that while the forms are there, saving doesn't result in creating the ProductAttribute relationship in the database, and the cleaned_data of these forms is empty. My code: admin.py ... class ProductAttributeInline(admin.TabularInline): model = ProductAttribute formset = ProductAttributeInlineFormset extra = 0 fields = ('attribute', 'value') readonly_fields = ('attribute',) can_delete = False def has_add_permission(self, request, obj=None): return False @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ( 'name', 'category', 'price', 'sku', 'created_at', 'updated_at' ) search_fields = ('name', 'sku') list_filter = ('category',) inlines = (ProductAttributeInline,) ... forms.py from django import forms from .models import ProductAttribute class ProductAttributeInlineFormset(forms.models.BaseInlineFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance and self.instance.pk: category = self.instance.category if category: attributes = category.attributes.all() existing_attributes = set( self.queryset.values_list('attribute', flat=True) ) for attribute in attributes: if attribute.id not in existing_attributes: form_index = ( len(self.forms) + len(existing_attributes) - 1 ) form = self._construct_form( instance=ProductAttribute( product=self.instance, attribute=attribute, ), i=form_index ) self.forms.append(form) self.total_forms = len(self.forms) I noticed that 'attributes-TOTAL_FORMS' in form.data is equal to 1, but … -
Getting "Page not found (404) No Product matches the given query." error
I've started getting this error after deleting all my products from my database (I did this because it was dummy data just for testing). When I runserver and go to localhost I see this error The error states that this issue was raised in "home.views.index" despite the fact that the products are not called on the home page. I feel like my app is looking for the products and crashing when it cant find them. here is the code for my app urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('products/', include('products.urls')), path('checkout/', include('checkout.urls')), path('bag/', include('bag.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my product/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name='products'), path('<int:product_id>/', views.product_detail, name='product_detail'), ] Here is the code for products/views.py from django.shortcuts import render from .models import Product def all_products(request): products = Product.objects.all() context = { 'products': products, } return render(request, "products/products.html", context ) def product_detail(request, product_id): product = get_object_or_404(Product, pk=product_id) context = { 'product': product, } return render(request, 'products/product_detail.html', context) Any help you can offer is greatly appreciated and sorry if I'm … -
raise ValueError( ValueError: Cannot assign "'TJFIDEL2401'": "Order.discount_code" must be a "DiscountCode" instance
I'm trying to implement a checkout page using Django framework. I have DiscountCode model linked to the Order model as "discount_code = models.ForeignKey(DiscountCode, on_delete=models.SET_NULL, null=True, blank=True)". When I proceed to click on the place order button on the checkout page, an error message occurs that is, "raise ValueError(ValueError: Cannot assign "''": "Order.discount_code" must be a "DiscountCode" instance." - I have spent already a couple of hours trying to resolve this issue. The problem occurs when the form.is_valid() is triggered Models: class DiscountCode(models.Model): code = models.CharField(max_length=50, unique=True) # Unique discount code discount_amount = models.DecimalField(max_digits=5, decimal_places=2) # e.g., 10.00 for a fixed amount discount discount_percent = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # e.g., 10.00% for percentage discount valid_from = models.DateTimeField() valid_until = models.DateTimeField() max_uses = models.PositiveIntegerField(default=1) # Number of times the discount can be used users = models.ManyToManyField(Account, blank=True) # Assign to specific users or leave empty for all users is_active = models.BooleanField(default=True) # Active status def __str__(self): return self.code def is_valid(self): now = timezone.now() return self.is_active and self.valid_from <= now <= self.valid_until and self.max_uses > 0 class Order(models.Model): STATUS_CHOICES = ( ('New', 'New'), ('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Cancelled', 'Cancelled'), ) user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, … -
Djongo y Django REST Framework
Actualmente trabajo en el desarrollo de una red social y estoy usando Django para crear el back de la aplicación, pero la estoy conectando con Mongo usando el paquete de Djongo: https://www.djongomapper.com/using-django-with-mongodb-array-reference-field/ para el tema de los likes quiero referenciar con otra colección pero tengo problemas al usar REST framework para crear las API's de este modelo El post ya lo puedo crear sin problema pero a la hora de enviar un like o un comentario no se incrustan o no se referencian he usado ArrayField y actualmente estoy usando ArrayReferenceField -
assert not sociallogin.is_existing error when logging in using google with allauth
So I have been trying to login using google to my website but when I try to login it gets an assert error. I tried to add a presocial adapter to override it but I still get it. My settings are good I think. Even if I take off the adapter I try to login and get the same error. This is the error. AssertionError at /accounts/google/login/callback/ No exception message supplied Request Method: GET Request URL: http://127.0.0.1:8000/accounts/google/login/callback/?state=F6gfXDcxDejwMv6J&code=4%2F0AQlEd8z3snMAR_7qPFDabY-q_zHedLdND40cQdWn7AH_Akjs3q7R8hx0cjOlB_K0LrQBJQ&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&hd=afreebird.org&prompt=none Django Version: 4.2.13 Exception Type: AssertionError Exception Location: C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 36, in pre_social_login Raised during: allauth.socialaccount.providers.oauth2.views.view Python Executable: C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\Scripts\python.exe Python Version: 3.8.10 Python Path: ['C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\python38.zip', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\DLLs', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10\\lib', 'C:\\Users\\TinaPC\\.pyenv\\pyenv-win\\versions\\3.8.10', 'C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0\\env', 'C:\\Users\\TinaPC\\Documents\\GitHub\\afreebird_website_2.0\\env\\lib\\site-packages'] Server time: Mon, 30 Sep 2024 09:11:33 -0500 Traceback Switch to copy-and-paste view C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 103, in view return self.dispatch(request, *args, **kwargs) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 152, in dispatch return complete_social_login(request, login) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\helpers.py, line 67, in complete_social_login return flows.login.complete_login(request, sociallogin) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 46, in complete_login pre_social_login(request, sociallogin) … Local vars C:\Users\TinaPC\Documents\GitHub\afreebird_website_2.0\env\lib\site-packages\allauth\socialaccount\internal\flows\login.py, line 36, in pre_social_login assert not sociallogin.is_existing … Local vars … -
DRF Custom Generic View
I tried create a complete generic view with mixins to automate my app, and write less code. When i try make a 'POST' request i receive a 405 error = code(method_not_allowed) I cant find the error I also want to know if is this a good aproac to improve my code. `class BaseGenericView(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): serializer_class = YourModelSerializer permission_classes = [IsAuthenticated] # Adapte conforme necessário def get_queryset(self): return YourModel.objects.all() def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response({'message': 'Dados encontrados', 'data': serializer.data}, status=status.HTTP_200_OK) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) return Response({'message': 'Criado com sucesso!', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response({'message': 'Erro na validação', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response({'message': 'Dados encontrados', 'data': serializer.data}, status=status.HTTP_200_OK) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response({'message': 'Atualizado com sucesso!', 'data': serializer.data}, status=status.HTTP_200_OK) return Response({'message': 'Erro na validação', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response({'message': 'Removido com sucesso!'}, status=status.HTTP_200_OK)`