Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting two "https://" in the url of image
I'm developing a project using Django and Django Rest Framework in which I have to save an image in a model. I'm using S3 bucket as a storage device. I'm able to upload the image and save it to the model. The Problem When getting response (either getting a single object or an array of objects), I'm getting the url of image with two https://. This only happens when I'm using the Django server that's hosted on AWS Ec2. The url of the image is returned normally when using localhost, the problem is with static files as well (but they aren't used, only the admin panel and rest-framework templates use it) Example: When calling the API from the hosted server This is the response. Notice the image field. [ { "id": 5, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/Myron/Section_2_img.png", "name": "Myron", "message": "Cool Website", "position": "CEO", "company": "ME Ltd." }, { "id": 6, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/phoenix0347/Section_2_img.png", "name": "phoenix0347", "message": "askjn", "position": "false", "company": "false" }, { "id": 7, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/Kushagra%20Gupta/Section_9.png", "name": "Kushagra Gupta", "message": "jksabdsadb", "position": "1jb", "company": "sajd" }, { "id": 8, "image": "https://https://d2to87w45k79nd.cloudfront.net/media/testimonies/jksadb/hero_img.png", "name": "jksadb", "message": "akjsbasjdb", "position": "213u3", "company": "129ujieo2" } ] The same API when called from localhost gives A response like … -
Overriding Function for Password Reset via Email with drf-social-oauth2 and djoser Libraries
What function should I override to enable password reset via email when using both drf-social-oauth2 and djoser libraries, considering that user is active but I'm encountering issues with password reset through djoser after creating a user via email through the drf-social library? -
Why does it change the field without saving the form?
I want to implement the functionality of changing the email address. But before that, I want to check whether the user has changed his email. But for some reason, even without saving the form, the email automatically changes in the database. def form_valid(self, form): new_email = form.cleaned_data['email'] current_email = self.object.email if current_email == new_email: # same values ???? return super().form_valid(form) else: self.request.user.is_active = False self.request.user.save() reset_email_task(self.request.user, new_email) logout(self.request) return HttpResponseRedirect(reverse_lazy('email-done')) I tried a lot, nothing worked -
Django Error DisallowedHost at / Invalid HTTP_HOST header: 'xx.xx.xx.xx' again and again
Error: DisallowedHost at / Invalid HTTP_HOST header: '3.17.142.65'. You may need to add '3.17.142.65' to ALLOWED_HOSTS. I am trying to deploy my django site om AWS EC2 while deploying through github using git clone on AWS live cli. I am getting the following errors again and again. My EC2 instance ip is 3.17.142.65 and in my settings file first i kept it like this ALLOWED_HOSTS = ['3.17.142.65', 'localhost', '127.0.0.1'] this shows me the same error then i changed it to ALLOWED_HOSTS = ['3.17.142.65'] this also giving same error. (One thing i am not getting like i cloned my github project once at starting after then if i am changing on my github setting file how aws cli knows these changes. Btw i run the command git pull origin master Am i right that i should run this command while making any changes on github files? ) I am new to ubuntu and deploying websites so please guide me what mistake i am dong here. To run the server i executing these commands sudo systemctl restart nginx sudo service gunicorn restart sudo service nginx restart My Configured Nginx file server { listen 80; server_name 3.17.142.65; location = /favicon.ico { access_log off; … -
Django with djoser and social auth not working as expected, I have problem when post my state and code on URL
`I'm using Django with Djoser to be able to use google/facebook as social authentication, I created the CustomUserModel. Im using OAuth2 for social login, I got credentials on google etc. When I GET request on this url: enter image description here My Redirect_url config on google console developer platform: enter image description here I have back the response with state and code at URL. But when I try to POST these 2 as params (state and code), I'm facing some error: { "non_field_errors": [ "Authentication process canceled" ] } I'm including also the state on the cookies, because I'm using cookie HttpOnly I tried to remake project on Google to get new credentials, but still not working. How can i solve this error? thanks guys settings.py: from pathlib import Path from os import getenv, path import os from pathlib import Path from django.core.management.utils import get_random_secret_key from datetime import timedelta from django.utils.translation import gettext_lazy as _ import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Take environment variables from .env file dotenv_file = BASE_DIR / ".env" SECRET_KEY = getenv("SECRET_KEY", get_random_secret_key()) API_KEY_NEWS = getenv("API_KEY_NEWS") DEBUG = True ALLOWED_HOSTS = getenv("DJANGO_ALLOWED_HOSTS") CORS_ALLOWED_ORIGINS = [ .... … -
Soft deletion in many-to-many relationships with through model in Django
I'm facing an issue in my Django project related to soft deletion in many-to-many relationships using a through model. I'd appreciate any help or advice on how to resolve this issue. I have three models in my application: Author, Book, and BookAuthor. The many-to-many relationship between Author and Book is defined through the BookAuthor model. Here are the definitions of my models: from django.db import models class Author(SoftDeleteModel): name = models.CharField(max_length=100) class Book(SoftDeleteModel): title = models.CharField(max_length=200) authors = models.ManyToManyField(Author, through='BookAuthor', related_name='books') class BookAuthor(SoftDeleteModel): book = models.ForeignKey(Book, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Meta: # Other necessary meta definitions pass The issue arises when I soft delete a relationship in the BookAuthor model and then try to access the books of an author using the query author.books.all(). Even though I have soft deleted the relationship in BookAuthor, I still see all the books associated with the author. I'm using the django-soft-delete package (https://pypi.org/project/django-soft-delete/), Does anyone have any suggestions on how I can address this issue and ensure that softly deleted relationships are not displayed when accessing through the many-to-many relationship? Any help or advice would be greatly appreciated! Thank you in advance! -
To remove intermedite Page like signup page when login with linkedin using OpenId Connect with django-allauth
In settings.py file 'allauth.socialaccount.providers.openid_connect', SOCIALACCOUNT_PROVIDERS = { "google":{ "SCOPE":[ "profile", "email" ], "AUTH_PARAMS": {"access_type": "online"}, "EMAIL_AUTHENTICATION": True, }, "openid_connect": { "APPS": [ { "provider_id": "linkedin_oidc", "name": "hrms", "client_id": os.environ.get("linkdin_id"), "secret": os.environ.get("linkdin_secret"), "settings": { "server_url": "https://www.linkedin.com/oauth", "token_auth_method": "client_secret_post", "scope": ["openid", "email"] }, } ] } } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 4 LOGIN_REDIRECT_URL = 'dashboard' LOGIN_URL = "login" LOGOUT_REDIRECT_URL = 'login' SOCIALACCOUNT_LOGIN_ON_GET=True ACCOUNT_EMAIL_VERIFICATION = 'none' SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_LOGIN_REDIRECT_URL = 'dashboard' When I complete login with linkedin then page redirect to http://localhost:8000/accounts/social/signup/ url, If anyone know how to remove this intermediate page -
django fail to run front-end file
I can run this part of the code successfully using node.js, but there are some issues with transferring this part of the code to django. node.js run node.js success django fail The code has been modified into a django format errors I tried to add this part of the code to the django project, but it failed. -
Django and creating superuser_bot
How to create superuser_bot admin via Django? With user registration and authorization. I am interested in everything that will help me create this telegram bot (a kind of superuser_bot admin). Using the Python programming language, Django framework and of course aiogram (version 3.11, this is very important). I tried to put the project together and it led to a huge quantity of errors. -
Can someone please help me convert my Django project to an exe file?
I am new to Django and I have done a project using Django which has four Django apps. I am trying to distribute my project to someone as a standalone executable file. I am using PyInstaller for that. But, it detects only the main Django app and it can't find the other three apps. What am i doing wrong? Please help me ! I have successfully created an exe file. But upon running it i get an error saying that it doesn't find one of my Django apps. This is the error i got on the window. homepage is one my four apps. core is my main app which settings.py and the other two are transactions and inventory. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "django\core\management\__init__.py", line 416, in execute django.setup() File "django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "django\apps\config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen … -
Invalid block tag on line 126: 'set', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I want to use {% set … } but it has problem is django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 126: ‘set’, expected ‘empty’ or ‘endfor’. Did you forget to register or load this tag? what should i do ? html file <div class="carousel-inner"> {% for knowledge in knowledges %} {% set count = 0 %} {% for photo in photo01s %} {% if photo.category01 == knowledge %} {% set count = count + 1 %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <div class="row"> <div class="card" style="background-image: url('{{ photo.image01.url }}');"></div> </div> </div> {% endif %} {% endfor %} {% endfor %} </div> models.py class Knowledge(models.Model): name01 = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name01 class Photo01(models.Model): category01 = models.ForeignKey(Knowledge, on_delete=models.SET_NULL, null=True, blank=True) image01 = models.ImageField(null=False, blank=False) description01 = models.TextField() title01 = models.CharField(max_length=100, default='') def __str__(self): return self.title01 views.py def knowledge01(request): knowledges = Knowledge.objects.all() photo01s = Photo01.objects.all() context = {'knowledges': knowledges, 'photo01s': photo01s} return render(request, 'photos/knowledge01.html', context) I have tried several ways but it does not work. -
How to create two users of different permissions in Django?
How to set up two different types of users in Django: Superuser, who has access to all system functionalities, and Maintenance user, who can perform system maintenance. Automatically create them upon system initialization.Thanks in advance. As a beginner, there is not much thought. I will only create an initial user. I hope you can provide ideas and related reference codes. Thanks here to thank you -
Send and receive socket without opening the html web page
I am having a django project where I have chat.html, journey.html, and manager.html. One of the flows is that I am sending socket for triggering journey from chat.html. And in the journey.html, I have a flow for approval where the socket gets sent to manager.html. This flow is working only when I keep all these 3 pages open in browser. But if I don't keep the "journey" page open in a browser, the socket is not getting received and send is not happening from "journey". This should work without the need to open "journey" page in the browser. How can I do that? -
Design patterns and user control in Django
I'm a new web developer building a system using Django for users across multiple departments to streamline data uploading, processing, and downloading. Most users will be restricted to uploading, modifying, and viewing data within their own department. Some privileged users will have additional download permissions for their department's data. Additionally, there will be super users who can view data from all departments. However, I'm stuck on implementing user permission control (effective translation depends on context, but "user permission control" works well here). I've considered two approaches: Multiple Web Pages: The simplest method would involve creating separate web pages for users with different permissions. Users with limited access would only see upload, modify, and view functionalities for their department's data, with no download button. Super users would have access to all functionalities and data across departments. While straightforward, this approach requires significant development time as separate pages need to be built for each permission level. Single Integrated Web Page: A more elegant but potentially complex solution would be to develop a single, comprehensive web page for all users. This page would have all functionalities, but user permissions would control what each user can actually see and interact with. This approach offers … -
Django_mailbox, similar queries
Help me remove duplicates please, I’ve already tried everything, documentation, chatGPT, I don’t know how to remove it, it’s just that when I access the .html attribute a new request to the database is generated messagesDB = Message.objects.filter(mailbox=mailbox).select_related('mailbox', 'message_used').prefetch_related(Prefetch('attachments', queryset=MessageAttachment.objects.all(), to_attr='all_attachments')) for message in messagesDB: print(message.html) SELECT ••• FROM "django_mailbox_messageattachment" WHERE "django_mailbox_messageattachment"."id" = 44 LIMIT 21 13 similar queries. SELECT "django_mailbox_messageattachment"."id", "django_mailbox_messageattachment"."message_id", "django_mailbox_messageattachment"."headers", "django_mailbox_messageattachment"."document" FROM "django_mailbox_messageattachment" WHERE "django_mailbox_messageattachment"."id" = 44 LIMIT 21 13 similar queries. C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\staticfiles\handlers.py in call(80) return self.application(environ, start_response) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\whitenoise\middleware.py in call(124) return self.get_response(request) C:\Users\user\AppData\Local\Programs\Python\Python310\lib\contextlib.py in inner(79) return func(*args, **kwds) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in view(104) return self.dispatch(request, *args, **kwargs) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\auth\mixins.py in dispatch(73) return super().dispatch(request, *args, **kwargs) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\contrib\auth\mixins.py in dispatch(109) return super().dispatch(request, *args, **kwargs) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in dispatch(143) return handler(request, *args, **kwargs) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django\views\generic\base.py in get(226) context = self.get_context_data(**kwargs) C:\Users\user\Desktop\Задачник\ProjectsDashboard\dashboard\timetable\views.py in get_context_data(2109) messagesDB = self.get_message_telegram(self.mailbox) C:\Users\user\Desktop\Задачник\ProjectsDashboard\dashboard\timetable\views.py in get_message_telegram(2058) print(message.html) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in html(671) self.get_email_object(), 'text', 'html' C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in get_email_object(783) self._email_object = self._rehydrate(flat) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(683) self._rehydrate(part) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(683) self._rehydrate(part) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\django_mailbox\models.py in _rehydrate(687) attachment = MessageAttachment.objects.get( C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\cacheops\query.py in get(327) return qs._no_monkey.get(qs, *args, **kwargs) C:\Users\user.virtualenvs\dashboard-APxxHYiU\lib\site-packages\cacheops\query.py in _fetch_all(250) return self._no_monkey._fetch_all(self) -
ValueError: Django can only handle ASGI/HTTP connections, not websocket
I'll try to explain in great detail what is my problem and how the project is structured. I want to make a real time chat applications. So far my project has: SignupLoginApp ProgettoDiGruppo (Main app) Home ChatManagement(Websocket app). Now the problem is I can't get the websocket to run and since it's my first time I don't really know what I'm doing. Here is my ProgettoDiGruppo.settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # ThirdParty 'crispy_forms', 'crispy_bootstrap4', 'channels', # MyApp 'SignupLoginApp.apps.SignupappConfig', 'Home.apps.HomeConfig', 'ChatManagement.apps.ChatmanagementConfig' ] WSGI_APPLICATION = 'ProgettoDiGruppo.wsgi.application' ASGI_APPLICATION = 'ProgettoDiGruppo.routing.application' CHANNEL_LAYERS = { 'default': { "BACKEND": "channels.layers.InMemoryChannelLayer", } } Here is my ProgettoDiGruppo.routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter `import ChatManagement.routing `websocket_urlpatterns = [ ] application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( ChatManagement.routing.websocket_urlpatterns ) ), }) This is my ChatManagement.routing.py from django.urls import re_path from ChatManagement import consumers websocket_urlpatterns = [ re_path(r'/ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] ChatMAnagement.consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer 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 await self.channel_layer.group_add( self.room_group_name, `self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': self.scope['user'].username } ) async def chat_message(self, event): # This method will be called when a 'chat_message' event is … -
Django Bootstrap Datepicker Plus. Set maxDate as another DatePicker value plus 2 years
I need to set maxDate for DatePickerInput as another DatePickerInput value plus 2 years. From the documentation I've learned, that we can use link to another datepicker to set minDate (range_from attribute), but I'm not sure how to set maxDate like that. Can we do something like this? from bootstrap_datepicker_plus.widgets import DatePickerInput from .models import Event from django import forms from dateutil.relativedelta import relativedelta class ToDoForm(forms.Form): start_date = forms.DateField(widget=DatePickerInput()) end_date = forms.DateField(widget=DatePickerInput(range_from="start_date", options={ 'maxDate': start_date.date + relativedelta(years=2) })) -
Restrict Multiple Login for Same User with DRF
I'm trying to delete any existing sessions associated with the user and create a new session. So that the user can only be authenticated in one browser or device at a time. If user is logged in to browser_1 and user is logged in again on browser_2, then in that case, I want to log out of user_1 from browser_1. Here is models.py: class User(AbstractBaseUser, PermissionsMixin): '''User in the system.''' email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' class UserSession(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.CharField(max_length=100) Here is views.py: from core.models import UserSession class CreateTokenView(ObtainAuthToken): '''Create a new auth token for user.''' serializer_class = AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES def post(self, request, *args, **kwargs): response = super().post(request, *args, **kwargs) serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] UserSession.objects.filter(user=user).delete() token, _ = Token.objects.get_or_create(user=user) session = UserSession.objects.create(user=user, token=token.key) session.save() response.data['token'] = token.key return response Here I tried to make user create a new session and token when authenticated from browser_2, thus deleting the session in browser_1 and deactivating the token. But this didn't work. -
Django combing multiple managers from inherited classes
I have model that inherits from 2 abstract classes with overridden managers: class ManagerA(models.Manager): def get_queryset(self): return super().get_queryset().filter(attrA="A") class A(models.Model): objects = ManagerA() class Meta: abstract = True class ManagerB(models.Manager): def get_queryset(self): return super().get_queryset().filter(attrB="B") class B(models.Model): objects = ManagerB() class Meta: abstract = True class Main(A, B): pass How to override manager in Main class, that it combines both filters from ManagerA and ManagerB? I want ot have something like: Main.objects.all() -> works like Main.objects.filter(attrA="A", attrB="B") -
django Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead
hi i have aproject in django when i try to runserver the message above is shwon this is models.py fo class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display) user= models.ManyToManyField(User) choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and this the view.py tdef submit_operation(request): if request.method == 'POST': url = request.POST.get('url') text = request.POST.get('title') choosenum = request.POST.get('CHOOSE') if Display.objects.filter(url=url).exists(): display = Display.objects.get(url=url) display_data = Display_Data.objects.create(choosenum=choosenum, user=request.user, date_published=datetime.now()) display_data.displays.add(display) else: display = Display.objects.create(url=url, text=text) display_data = Display_Data.objects.create(choosenum=choosenum, user=request.user, date_published=datetime.now()) display_data.displays.add(display) # ... (إعادة توجيه المستخدم) #return redirect('searchpage') return redirect(request.META.get('HTTP_REFERER'))ype herea `and when i try to refer to vidion saved before the message above abeer i make a site show video from youtube in a frame and asked a user to value the vidio i saved vidio url and when i want from user to again evluate the vidio the mistake apeer -
Html template from contributions-django libraty not rendering properly
I want to use a GitHub-like contributions calendar in my Django project. After a quick research, I found the contributions_django library. After some problems, I managed to install it, but even after following the instructions, the contributions graph does not load properly on the page. What should be an empty contributions graph looks like this: First I imported the library to my views.py file: from contributions_django.graphs import generate_contributors_graph Then I used 'generate_contributions_graph' method in my view: contributions = [] calendar = generate_contributors_graph(contributions, title="Decks reviews") return render(request, "myapp/user_stats.html", {"calendar":calendar} Finally, I placed this line of code in the "user_stats" HTML template: {% include "contributions_django/graph.html" %} And that's it. It should display an empty graph, but it doesn't. I also tried to insert some dates in the "calendar", but it didn't work; nothing changed: today = timezone.now() last_week = today - timedelta(days=7) contributions = [last_week, today] calendar = generate_contributors_graph(contributions, title="Decks reviews") If you have any idea what the cause of the problem might be, please help. Thanks in advance. -
directly compute a geohash with django without creating a model
is it possible to use this GeoHash class directly without creating a model on a db? e.g.: from django.contrib.gis.geos import Point from django.contrib.gis.db.models.functions import GeoHash p = Point(x=lon, y=lat, srid=4326) geohash_str = GeoHash(p).??? # i want the actual geohash string here -
White screen while trying to make auth through google in Django project
I followed this guide https://www.photondesigner.com/articles/google-sign-in?ref=yt-google-sign-in First of all, I could not create button through the https://developers.google.com/identity/gsi/web/tools/configurator, but I copied the code from guide and changed the client id, but anyway I get this, when I click the button to auth through google after clicking the google auth button I tried to follow the guide, but it didn't help. Maybe someone got the same problem and know how to fix it -
Django REST Authentication credentials were not provided
I'm developing an API using Django Rest Framework. but when i'm trying to access the console gives me this error: @api_view(['GET']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def get_all_messages(request, user_id): messages = Message.objects.filter(receiver_id=user_id) serializer = MessageSerializer(messages, many=True) return Response(serializer.data) from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('admin/', admin.site.urls), path('api/get-all-messages/<int:user_id>/', get_all_messages), ] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ # Corrected typo here 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } http://localhost:8000/api/token/ copy the token I have searched but they say to change the REST_FRAMEWORK's AUTHENTICATION PERMISSIONS which I have done as you can see, but to no avail. -
Drawbacks of customer save method to avoid user getting a userprofile_id with a specific value. (Django/Heroku)
In my Django project, I need to avoid users creating a userprofile_id with a value of 3 (3, 13, 203...). This is an interim workaround another issue which will probably take longer to result. I posted the code below. But my question relates more to the drawbacks of this interim fix. What sort of problem could this generate. This is the list I came up with and my answers to each of them: User_id will be different than userprofile_id - cant see any problems here. Affect to database integrity when custom method is removed - I cannot see how the remove of the method would affect the database. Hopefully I am right.; Some performance issue - The save is at the database level which might cause some delays I suppose. This is for a pilot+. I dont expect 1000s of new users a day. Could two users who signup at the same time end up with the same userprofile_id? Would there be a wait to limit potential of deadlocks? the code for those who are curious: class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) def __str__(self): return str(self.user) def save(self, *args, **kwargs): if not self.pk: # Logic for generating userprofile_id without …