Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
inlineformset_factory shows empty dropdown for id_modelname
when creating a formset from a fromset_factory, I get an empty dropdown menu for the model id. How to prevent django from doing this? Related code: Experience model class Experience(models.Model): hnuser = models.ForeignKey(HNuser, on_delete=models.CASCADE, blank=True, default='') activity = models.CharField(max_length=30, null=True, blank=True, default='') campaign = models.CharField(max_length=30, null=True, blank=True, default='') location = models.CharField(max_length=30, null=True, blank=True, default='') year = models.CharField(max_length=4, null=True, blank=True, default='') def __str__(self): return '' class Meta: ordering = ['-year'] verbose_name_plural = 'Experiences' Related HNuser model: class HNuser(AbstractUser): username = None # Make the email field required and unique email = models.EmailField('email address', unique=True) # Set the USERNAME_FIELD--which defines the unique identifier for the User model--to email USERNAME_FIELD = 'email' # additional required fields REQUIRED_FIELDS = [] # Specified that all objects for the class come from the CustomUserManager objects = HNuserManager() def __str__(self): return str(self.id) To be short, in view.py I did this exp_form = ExpFormSet(instance=HNuser.objects.get(pk=user_id)) return render(request,'users/edit_profile.html', { 'exp_form':exp_form, }) And in the template <table class="table"> {{exp_form}} </table> I tried to exclude the field 'id_experiences' in exp_form definition. But since it is not an Experience model attribute, this didn't work. Is anybody out there with an idea what is going on? Any hint is appreciated. -
How to run django migrations when deploying to google app engine from bitbucket pipeline?
I am trying to setup pipelines on bitbucket for my django project. I am using the google-app-engine pipe on bitbucket. But I don't exactly know how I can run my migrations to google cloud sql. -
hide database credentials from template javascript in django
I'm interfacing my Django application with a Neo4J database. I use both the python interface in backend to pass some data to a template with views.py, in this case the credentials are automatically catched from settings. from neo4j import GraphDatabase driver = GraphDatabase.driver(settings.NEO4J_URI, auth=(settings.NEO4J_USERNAME, settings.NEO4J_PASSWORD)) But in other cases, in order to allow more interactivity, I have some tables completely built in javascript, using the neo4j javascrips drivers. In this case, during development I was just creating the driver, with username and password hardcoded inside the script in the head of the template. Now I'm in a more advanced stage of development and I'm of course worried of having username and password in clear in the source code, I can see it quite easily on chrome browser with the "inspect" button. I seen some people suggest just to uglify it, however this is quite risky and I would really like to avoid it. Is there a way to retrieve the driver credentials from backend in order to make them not visible in the code? I also seen this package, would it work in my case? https://pypi.org/project/django-javascript-settings/ I did some research on the topic, however I'm looking for some suggestions as … -
How to implement followers/following using ManyToManyField in Django?
I want to implement the following feature using manytomanyfield in my Django Application. I have created UserProfile class for every user with two attributes: user and follows. User inherit the default Django user model. class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'user', on_delete=models.CASCADE) follows = models.ManyToManyField("self", related_name = 'follower',symmetrical=False ) I tried this in python shell: >>> lily = User(username="Lily") >>> lily.save() >>> mary = User(username="Mary") >>> mary.save() >>> lily_profile = UserProfile(user=lily) >>> lily_profile.save() >>> mary_profile = UserProfile(user=mary) >>> mary_profile.save() >>> lily_profile.follows.add(mary_profile) But I got this error after I do lily_profile.follows.add(mary_profile) : django.db.utils.OperationalError: table polls_userprofile_follows has no column named from_userprofile_id Does anyone know how to fix this error? Thanks a lot! -
Django not redirecting to next page
I don't know what's happening with my code, once a user that is not authenticated tries to access a page and it redirects to the login page, I can see the next parameter in the browser but after the user logins, it takes the user to the default LOGIN_REDIRECT_URL and not the next page. Also on the template next returns none, so seems the template is not getting thee next value, but in the url it shows the /?next=, thanks in advance. urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomeView.as_view(),name="index"), path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'), path('accounts/profile/', views.ProfileView.as_view(), name='profile'), ] registration/login.html {% extends 'app/base.html' %} {% block link %} id="active" {%endblock%} {% block content %} <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="jumbotron" id="font"> {% if next %} {% if user.is_authenticated %} <h2 class="customtext" align="center">Your account doesn't have access to this page. To proceed, please login with an account that has access.</h2> {% else %} <h2 class="customtext" align="center">Please login.</h2> {% endif %} {% else %} <h2 class="customtext" align="center">Enter your login details.</h2> {% endif %} <form action="{% url 'login' %}" method="POST"> … -
Docker Setup Issue
while setting my project on windows 10 home using docker I am getting this error ERROR: for django Cannot start service django: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"./docker/wait-for-it.sh\": stat ./docker/wait-for-it.sh: no such file or directory": unknown ERROR: Encountered errors while bringing up the project. https://i.stack.imgur.com/q6LJm.png https://i.stack.imgur.com/V6oCz.png https://i.stack.imgur.com/92b9z.png -
Django return format_html
I have a function to return an result in an html_format, but I can´t figure out how to return the value in a dynamic way. Currently this is what I have: this is the function: class ImageColumn(tables.Column): def render(self, value): return format_html('<a href="/media/{}" download>Imagen</a>', value) As you can see I have the value 'Image' hardcoded, but what I want is the name of the Image, something like this 'CFE.jpg' to be shown. I have tried this: return format_html('<a href="/media/{}" download>{}</a>', value) but I get a Index Tuple error also I have tried: return format_html('<a href="/media/{}" download>{{object.id}}</a>', value) but in the front end it only shows a '{}' -
Why django gives me this get error while making my first poll apps
I was following this tutorial: "https://docs.djangoproject.com/es/3.0/intro/tutorial03/", and it was all good until this part, where I encountered this error. django error mysite/urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls', include('polls.urls')), path('admin/', admin.site.urls), ] mysite/polls/models import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text mysite/polls/urls from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), ] mysite/polls/views from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world, this is Hernán.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) and at mysite/settings is all default, except I changed this TIME_ZONE = 'America/Belem' I hope you guys can help me, … -
Django: 'User' object has no attribute 'perfil_de_usuario'
I'm trying to make a page that, after the user is logued in, shows a list of diferent actions. The proble is that, when the user is succesfully authenticated, the resulting page is this error: AttributeError at /iniciar_sesion/ 'User' object has no attribute 'perfil_de_usuario' Request Method: POST Request URL: http://127.0.0.1:8000/iniciar_sesion/ Django Version: 3.0.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'perfil_de_usuario' Exception Location: /home/jenifer/Documentos/qbit/mysite4/usuarios/models.py in guardar_usuario_perfil, line 25 The model is as follows: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Perfil_de_Usuario(models.Model): idusuario = models.AutoField(db_column='idUsuario', primary_key=True) nombres = models.CharField(max_length=45, blank=True, null=True) apellidos = models.CharField(max_length=45, blank=True, null=True) clave = models.CharField(max_length=45, blank=True, null=True) email = models.CharField(max_length=45, blank=True, null=True) web = models.URLField(blank=True) class Meta: managed = False db_table = 'Usuario' @receiver(post_save, sender=User) def crear_usuario_perfil(sender, instance, created, **kwargs): if created: perfil_de_usuario.objects.create(usuario=instance) @receiver(post_save, sender=User) def guardar_usuario_perfil(sender, instance, **kwargs): instance.perfil_de_usuario.save() For what the error says, the problem is with guardar_usuario_perfil, but I'm not getting how to modify it for this thing to work. I know there are similar posts and I've tried different solutions like rename instance.perfil_de_usuario.save() part but the result is the same. If somebody can help me I will apreciate it very … -
Textinput not displaying on HTML page
class NewDeviceWidget(MultiWidget): def __init__(self, attrs=None, admin=False): self.attrs = attrs self.admin = admin widgets = ( TextInput(), # device_type TextInput(), # os_type TextInput(), # bitness TextInput(), # file_system ) if self.admin: widgets = widgets + (CheckboxInput(attrs={'value': False}),) # add device to database? super(NewDeviceWidget, self).__init__(widgets, attrs) def decompress(self, value): # decompress stored database format to HTML form format if value: value = json.loads(value) if self.admin: return value return value[:len(value)-1] # return all but the last element return "" def render(self, name, value, attrs=None): # formats the fields to be displayed horizontally context = {'fields': self.widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) Its not displaying textinputs, instead it is displaying <django.forms.widgets.TextInput object at 0x7ff13ca89470> ... The newdevicewidget html is below too.I am on django 2.2 and python 3.6.9 </br><table style="width:100%"><tr><td>Device Type</td><td>OS Type</td><td>Bitness</td><td>File System</td></tr> <tr> {% for field in fields %} <td>{{ field }}{% if forloop.counter0 == 4 %} Add this device to the database?{% endif %}</td> {% endfor %} </tr></table> -
Django: how to set custom pagination in restapi?
i recently followed django custom pagination(pagination-link). here i tried something in my code but it's showing empty pages(usually nothing result). i am not sure where i made mistake, i usually feel stupid. class Order_ListAPIView(APIView): def get(self,request,format=None): totalData=[] if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details ''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_detail_query) order_detail_result = cursor.fetchall() order_detail_data = list(order_detail_result) # print(order_detail_data) cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) dic = {} def merge_order_data_and_detail(order_data, order_detail_data): for d in order_detail_data: if d['order_id'] not in dic: dic[d['order_id']] = [] dic[d['order_id']].append(d) for o in order_data: if o['order_id'] in dic: o['order_detail_data'] = dic[o['order_id']] merge_order_data_and_detail(order_data, order_detail_data) def page_list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) totalData.append({"order_data":order_data, }) return Response({"totalData":totalData,},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
Could not import Django, working last week
This was working last week, when running python manage.py runserver 8080 I get this new error, a week after it was working fine. Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
ForeignKey to AnonymousUser
I would like to follow this guideline and avoid a nullable ForeignKey. I have a ForeignKey to the django User model. If I try to store request.user in an instance of this model, I get this error: ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser>>": "MyModel.user" must be a "User" instance. I think it is feasible to avoid the non-conditionless data schema (nullable foreign key). How could I solve this? -
how to easily pass from django views to django-rest-framework views
I created a nice Django app, anything worked perfectly. Unfortunely I have now to QUICKLY migrate everything to django-rest-framework and to a VUE frontend. I'm in "charge" just of the backend side, someone else will write the frontend code. The problem is that I have really complex Django views and I can't figure out how to change them correctly and easily and, most important, how to test them without a frontend. Have you got any idea how to help? anything would be appreciated!!!!! -
How do you call the default add user form for a custom admin
I created a customized User Admin change form but when I create a new user it goes to the Change form. The Base Admin add form meets what I want hence why I want to keep it? Also how do I encrypt the password once I reverted back to the Base admin create form? How do I change this? Admin.py: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminChangeForm from .models import User # Register your models here. User=get_user_model() class UserAdmin(admin.ModelAdmin): form = UserAdminChangeForm search_fields=['username','user_type'] list_display=('username','full_name','password','email','user_type','ad','pqa','ts','tl','tm','stm','active') list_filter = ('ad',) fieldsets = ( (None, {'fields': ('username', 'password')}), ('Personal info', {'fields': ('full_name','birth_date','hire_date',)}), ('Permissions', {'fields': ('ad','tm','pqa','stm','ts','tl')}), ) class Meta: model = User admin.site.register(User,UserAdmin) forms.py: from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) usertype= forms.Select(choices=User.USER_TYPE_CHOICES) class Meta: model = User fields = ('username',) def clean_username(self): username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("Username is taken") return username def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") … -
how to generate builtin model permissions for non-managed models?
I have model like this: class Venue(models.Model): name = models.CharField(max_length=255) class Meta: managed = False db_table = 'venue' permissions = [ ('change_venue', 'Can change venue'), ] It is not managed because it already exists in the database (which was created before django project). I want to use django's builtin model permissions, but they are not created by default. I tried to add them by changing Meta.permissions field but got an error: The permission codenamed 'change_venue' clashes with a builtin permission for model 'events.Venue' What should I do? Just make migration and create permissions manually? -
How do I do atomic updates to a directory?
I have a directory with some files in it (they're mostly images with a JSON file). I want to process those files, possibly overwrite some of them and possibly create some new files from some other source. I can have an error happen at any point in this process. How do I ensure that if an error occurs as I'm processing one of the files that I won't end up with the directory in a weird state? I want to only change the contents of the directory if everything went well. Should I create a temporary directory with tempfile.mkdtemp, put my code in a try, do my update in the "temporary" directory, swap the existing directory with the temporary directory, and delete the temporary directory if it still exists in the finally? I'm using Python (Django). -
Format_output not working, and not rendering the page
SO I got application written in django 1.8 and migrating to django 2.2 def format_output(self, rendered_widgets): # formats the fields to be displayed horizontally context = {'fields': rendered_widgets} return render_to_string('tifact/widgets/newdevicewidget.html', context) THis piece of code is no more working, and i read format output disappaered from djanhgo 2.2 I Am trying to get alternate solution to make that work? anyone can help? Thank You -
Python/Django How to find img tag in response using assertContains
I am writing a test. I need to find the img tag on the post page in Django. How to do it ? I'll beat it like that, but it doesn’t work out. Tag not found. with open('media/posts/starlink4_website_Qhna5v6.jpg', 'rb') as fp: self.client.post('/new/', {'text': 'test post with image oh-ye', 'image': 'fp', 'author': 'agent007'}) def test_image_post(self): response = self.client.get('/agent007/1/') self.assertContains(response, '<img ', html=True, status_code=200) -
django-allauth not working with apache2+wsgi
I am using Django 1.8 on python3.6 with virtualenv , trying to integrate google login with django-allauth 0.23.0.it is working fine fine on python3 server (python3 manage.py runserver) but gives below error on production server(apache2+wsgi) ***Social Network Login Failure An error occurred while attempting to login via your social network account. Code: unknown, Error: Error retrieving access token: b'{\n "error": "invalid_scope",\n "error_description": "Some requested scopes were invalid. {valid\\u003d[https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email, openid], invalid\\u003d[https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email, https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile]}",\n "error_uri": "http://code.google.com/apis/accounts/docs/OAuth2.html"\n}'*** the installed apps are given bellow asgiref==3.2.3 certifi==2019.11.28 chardet==3.0.4 confusable-homoglyphs==3.2.0 defusedxml==0.6.0 Django==1.8 django-allauth==0.23.0 django-crispy-forms==1.8.1 django-registration==2.0 idna==2.9 mysqlclient==1.4.6 oauthlib==3.1.0 python3-openid==3.1.0 pytz==2019.3 requests==2.23.0 requests-oauthlib==1.3.0 sqlparse==0.3.0 urllib3==1.25.8 the setting.py file included bellow INSTALLED_APPS = ( #django apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'crispy_forms', 'registration', # 'custom_user', #my app # 'login', 'newsletter', 'accounts', # #social login 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', ) AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailBackend', 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # 'allauth.account.auth_backends.AuthenticationBackend', ] # AUTH_USER_MODEL = 'auth.User' # AUTH_USER_MODEL = 'custom_user.EmailUser' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'tryDjango18.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], … -
is it possible to communicate through socket with django
Hello i have a server program in python built with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) I have to make a web application for the users. the web application must send a string to the server. my question is : Can i use django to build a web application, and send a string to the python server ? thank you for reading. -
Django authlib MismatchingStateError on authorize_access_token
I have some issue on django authlib client https://docs.authlib.org/en/latest/client/django.html. On redirect url, authorize_access_token raise raise MismatchingStateError(). This is my code: def login(request): # google = oauth.create_client('google') authservice = oauth.create_client('authservice') redirect_uri = 'http://localhost:8050/authorize' authservice.save_authorize_data(request) return authservice.authorize_redirect(request, redirect_uri) def authorize(request): token = oauth.authservice.authorize_access_token(request) userinfo = oauth.authservice.parse_id_token(request, token) resp = oauth.authservice.userinfo(token=token) return JsonResponse(token, safe=False) And the stacktrace : Internal Server Error: /authorize/ app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner app_1 | response = get_response(request) app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response app_1 | response = self.process_exception_by_middleware(e, request) app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) app_1 | File "/opt/project/access/views.py", line 141, in authorize app_1 | token = oauth.authservice.authorize_access_token(request) app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/django_client/integration.py", line 66, in authorize_access_token app_1 | params = self.retrieve_access_token_params(request) app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/base_client/base_app.py", line 144, in retrieve_access_token_params app_1 | params = self._retrieve_oauth2_access_token_params(request, params) app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/base_client/base_app.py", line 126, in _retrieve_oauth2_access_token_params app_1 | raise MismatchingStateError() app_1 | authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response. If someone has an idea on how to fix it, it will be great. Thank you guys :) -
Finding amount of maximum items at a time in Django
I'm trying out Django on my backend and currently have a reservation database schema that is similar to the following: | Equipment id | Amount | Starting time | Ending time | 1 | 2 | 2021-09-21 12:30 | 2021-09-21 16:00 | 1 | 3 | 2021-09-21 15:00 | 2021-09-21 20:00 | 1 | 5 | 2021-09-21 18:00 | 2021-09-21 20:00 1) I would have to calculate the amount of maximum equipments reserved at a certain time window, for example 17:00-21:00 should return 8. I tried to use queryset.annotate(maxAmount=Sum(amount)) but it returns in this case the sum of all equipments reserved in the queryset. Could the possible solution be to group the reservations with overlapping time windows and then find out the greatest amount from that? What could be the command to group them that way? 2) Kind of same problem, but I would also have to find the time windows where the amount of reserved equipments is less than a certain threshold. Example with above data: I would want to find times where the amount of reserved equipments is less than 4: it should return 00:00 -> 15:00 and 20:00 -> 00:00. -
Get external API information using serializer data before creating a new object in Django Rest Framework
I've added a Profile model linked to User model in Django REST Framework. Before create a new object through a ModelViewSet I have to create a "customer" in an external API (Python requests) using profile information (not saved yet) and I want to save the returned ID in my Profile model. Now my ModelViewSet looks like: views.py class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Profile.objects.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) When and which is the best way to create the external customer and pass the ID to the serializer? -
Django function based view allow in_active user whereas ClassBasedView does not allow in_active user
I have 2 views.One is function based and the other is class based.When I call function based view with in_active user django does not give any error but when I call the class based view it gives 403 error from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import api_view, permission_classes @require_POST @permission_classes([IsAuthenticated,]) def test_function_based_view(request): return JsonResponse({ 'success': "True", }) class TestClassBasedView(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request): return JsonResponse({ 'success': "True", }) Django Version 1.11.21