Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File upload from Docker container to Google Cloud Storage
I'm putting together a CI/CD pipeline on Google Cloud and would like to upload files (created by the Django collectstatic command) from within a Docker container (on Kubernetes) to Google Cloud Storage. What's the best way to upload files from a Docker container? I'm currently trying to use gsutil, but not sure how to authenticate. Is a service account json key file the way to go, or can I somehow use Application Default Credentials from within the container? -
how to create django form text/char field which give suggestion(auto) from database
I created a simple model of drugs in Django which contain thousands of complex drugs name, now I create a form which gives the user a text/char field Since drugs name a long and complex I want to give them autocomplete suggestion when they start writing drugs name to prevent spelling mistakes -
Should buisness logîc be enforced in django python or in sql?
I am writing a rest backend for a project. Heres a basic example of the kind of problems I'm trying to solve. These students have tests with grades and each student has a column current_average_grade. Everytime a test is stored, this average_grade_should be updated (using all existing tests). So the question is, should this be calculated and stored with within the post view of django (get all grades from db and then do the calculation) or with an sql trigger and only use django to convert json to sql. The advantage of using sql for this, is of course it should theoretically be much faster and you also get concurrency for free. The disadvantage is that since I am now programming sql, I have yet another codebase to manage and it might even create problems with django. So whats the ideal solution here? How do I enforce buisness logic in an elegant way? -
is it possible to select a field to apply a distinct method?
I hope my title is enough to understand what my problem is, i am having trouble in distinct method i tried this: teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade).values('Teacher,grading_Period,Subjects,Grading_Categories,GradeLevel,','Date').distinct('Teacher,grading_Period,Subjects,Grading_Categories,GradeLevel','Date') and i've got no result def periods(request): global i, date category = request.GET.get('category') subject = request.GET.get('subject') teacher = request.GET.get('teacher') grade = request.GET.get('grade') period = request.GET.get('period') teacherStudents = studentsEnrolledSubjectsGrade.objects.filter(Teacher = teacher).filter(grading_Period = period).filter(Subjects = subject).filter(Grading_Categories = category).filter(GradeLevel = grade) this is my models.py class studentsEnrolledSubjectsGrade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True,blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True,blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Date = models.DateField(null=True, blank=True) Grade = models.FloatField(null=True, blank=True) this is the result (when i tried to removed the values and distinct()) this my data in studentsEnrolledSubjectsGrade -
MultipleChoiceField with massive choices best practice
I need have MultipleChoiceField field in a form that should have over 50000 choices, therefore I cannot render it properly; I emptied the choices and went through an Ajax call to filter the options depending on the user inputs. Problem is that Django is obviously complaining that the choice is not part of the empty choices I provided. I think of three solutions to fix this but would like to know which one is 'best practice' or if there was a better one : Create a second form which I check when the request is POST, same as the first one but with the choices initialized at the server starts Define the __init__ of the form where if passed a parameter it would set choices to a variable initialized outside the form at the server starts Find a way to display the input without displaying the options in the template -
How to show time value based on user's time zone using Django template tags
I'm saving all timing to my database in 'UTC' time zone, but I want every user to see this value converted to his own timezone. is it possible to be used in Django? my settings.py : TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True Here is what I tried: {% load tz %} <p> Leave on {{ request.date_time.date|localtime }} at {{ request.date_time.time|localtime }} </p> But it gives me a blank result, and when I remove the |localtime part, it shows it in the UTC format. any help with this? -
Redirect to different pages based on query result before CreateView
What I'm trying to do is implement a checking mechanism (based on the data in the db) before CreateView to redirect to different pages. Currently, when the user presses the button, it will lead to a form: dashboard.html: {% url 'xxx_create' as xxx_create_url %} <a href="{% url 'xxx_create' %}" class="btn btn-primary hidden-xs" role="button"> <i class="fa fa-plus"></i>&nbsp;{% trans 'New XXX' %}</a> <a href="{{ xxx_create_url }}" class="btn btn-primary visible-xs-inline" role="button"> <i class="fa fa-plus"></i></a> and there is a customized.html but the content doesn't really matter. views.py class CustomizedCreateView(LoginRequiredMixin, ..., CreateView): form = CustomizedForm template_name = 'customized.html' def get_form_valid_message(self): msg = gettext('{title} created') return format_html(msg, title=self.object.title) urls.py: urlpatterns = [ ..., url(r'^xxx/$', views.CustomizedCreateView.as_view(), name='xxx_create'), ... ] What I'm trying to implement is when the user presses the button, check if the mapped string (named foo here) of the current user in the model (named Check here) is equal to predefined string bar. If matched, create the view as mentioned above. If not, redirect to another form and then redirect to the original form after submitting it. models.py class Check(models.Model): user = models.ForeignKey( verbose_name=_('user'), to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) foo = models.CharField( verbose_name=_('blah'), max_length=15 ) What's the best practice to implement this kind of feature? using a … -
Sq3Lite Query handling with python forms and datatables
Hello iam trying to get this to work but have no clue whats wrong in my code.... pls help:) views.py @login_required() def Info_anlegen(request, id=None): item = get_object_or_404(Kunden, id=id) itemKN = Kunden.objects.raw('SELECT KN FROM blog_Kunden WHERE id = 'id'') item1 = get_object_or_404(WindowsPro, id=itemKN) kontaktform_form = InfoForm(request.POST or None, instance=item) winform_form = InfoWinForm(request.POST or None, instance=item1) if kontaktform_form.is_valid(): return redirect('/Verwaltung/KontaktAnlegen') else: form = acroniform(instance=item) return render(request, 'blog/infokontakt.html', {'kontaktform_form': kontaktform_form, 'winform_form': winform_form}) -
Not able to generate migrations in docker django application
I am trying to run migrations in the Django application that is using docker but the changes are not reflecting. I had no issue with the initial migrations but after that, if I make any changes to my models that are not reflected in the migrations and it keeps generating initial migrations. I am not able to find any migration file too maybe that is causing this problem but I am not able to find any solution. I am using amazon RDS as database and application is also hosted on AWS and I am using this command for migrations. docker-compose -f production.yml run django python manage.py makemigrations app_name -
Get All Parents/ Children Of Record In Table
I have an SQL (Postgres) table named “Items” with the following schema. id | parent_id | name Where the parent_id column is a ForeignKey to the same table. (E.g items have parent items and those items can have parent items) This makes a simple branching hierarchy. Currently I query for the specific record and use a for loop to get each of its parents/ children. This results in numerous queries being executed. What I’m wanting to do is query this table using the id of one of the items and get all of its parents/ children returned using a single query. I can accomplish this by using .select_related(“parent__parent”) or .prefetch_related(“item_set”)for the children, but both of these approaches would require knowing the depth of the hierarchy before hand. Is there a way in Django to get all of the related rows in a single query? Raw SQL is fine too. -
Django foreignkey issue in html
Why i cant display the teacher name in my html? it is clearly that in my models StudentsEnrolledSubject i have foreignkey that connects in my another model SubjectSectionTeacher, and i just want to display the name of the teacher in my html, did i miss something? or i have query wrong? i have this code in my html {% for student in studentenrolledsubject %} <tr class="tr2"> <td class="td" ><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{student.Students_Enrollment_Records}}</td> <td class="td" ><input type="text" name="students" value="{{student.id}}" id="student" hidden>{{student.Subject_Section_Teacher__Employee_Users}}</td> <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" readonly/></td> </tr> {%endfor%} this is my views.py studentenrolledsubject= StudentsEnrolledSubject.objects.filter(Subject_Section_Teacher__in = teacher.values_list('id')).distinct().order_by('id') this is my models.py class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) -
how to insert item in a table through SQL query using djangorestapi
I have a table which has productID, productTitle, QueryValue column. I need to insert item using SQL query through Djangorestapi. But I am having trouble to insert item through SQL-query. here is my 'products' table, click to view product table -
How to prevent user to be a both of types?
I have a model like from this answer: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) Is it possible to prevent create new user both of types simultaneously at model level? In other words, it could be ONLY is_student == False and is_teacher == True or vise versa. -
I have created my model but im confused with creating views to save my data from submitted form in database
models.py from django.db import models class Aganwadi(models.Model): name= models.CharField(max_length=30) email= models.EmailField() district=models.TextField() phone=models.IntegerField() def __str__(self): return self.name I have a template for the the form called aganwadi.html in users/templates/users/aganwadi.html views.py from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.decorators import login_required def Aganwadi(request): return render(request,'users/aganwadi.html') urls.py from django.urls import path,include from users import views as user_views from django.contrib.auth import views as auth_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('aganwadi/',user_views.Aganwadi,name='aganwadi'), path('', include('pmmvyapp.urls')), ] I want to store the data submitted on my form to be stored on the database -
Why am I getting this error when adding djang-tems and conditions and captcha?
ADMINS, HOW DO I ADD ERROR TEXT????? I'm adding django-termsandconditions and django-simple-captcha and I have django-q for task scheduling which uses the cache system and I have the cache table set as 'default' but now I'm getting no such table: default. I have to have the cache backend set up to use django-q but somehow it's conflicting with either terms and conditions or the captcha. I've got the middle ware for the cache in the proper place (beginning and end) and have terms and conditions middle ware second to last. Do I need to make custom migrations for this? Someone suggested these packages to me and now I'm stuck here. MiddleWare MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'termsandconditions.middleware.TermsAndConditionsRedirectMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] -
Wanted to add custom initial value from DB when change wanted to append initial value
I have a requirement in Django 2.1 admin, form have a custom filed which display as multi select when add form is called and when form change called then previously selected value should shown as selected using javascript. But I am unable to show the already chosen value. Model class from django.db import models from django.utils import timezone # Create your models here. class Notification(models.Model): id = models.AutoField(primary_key=True) notif_ty = models.CharField(max_length=24) alert_ty = models.CharField(max_length=30) scheduler = models.IntegerField(default=0) box_ty = models.TextField(verbose_name="Box Type", max_length=200, blank=True, null=True) Admin class from django.contrib import admin from django import forms from django.contrib import messages from constants import constants from string import Template import json from django.conf import settings # Register your models here. from .models import Notification import logging logger = logging.getLogger('django') class NotificationAdmin(admin.ModelAdmin): class Media: js = ['admin/js/notification/pn1.js',] def formfield_for_dbfield(self, db_field, **kwargs): logger.debug("formfield_for_dbfield method get called...") field = super(NotificationAdmin, self).formfield_for_dbfield(db_field, **kwargs) # We can't assume that kwargs['initial'] exists! if 'initial' not in kwargs: kwargs['initial'] = {} if db_field.name == 'box_ty': logger.debug("fileds name>>>>>>>>> %r " , field) field.initial = get_box_types() #'My initial description' return field def get_changeform_initial_data(self, request): logger.debug("get_changeform_initial_data...") boxes = get_box_types() return {'box_ty': boxes} def save_model(self, request, obj, form, change): obj_x = Notification.objects.filter(schedule=0) ... def … -
botocore.exceptions.ClientError: AccessDenied
I am currently trying practice on Django. I am trying to do python manage.py collectsatic However, I keep getting the errors like below. raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied my settings.py code for this issue is as below. AWS_ACCESS_KEY_ID = #Access ID AWS_SECRET_ACCESS_KEY = # ACCESS KEY AWS_REGION = 'ap-northeast-2' AWS_STORAGE_BUCKET_NAME = # Bucket Name AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I seriously do not see as to why I keep getting the access denied as I believe I put the correct codes in the settings.py. I referred to couple of threads on this matter, I tried what the others tried to resolve the case. However, it seems like my case is not getting resolved. Does anyone have any ideas on how to get this right? Thank you very much in advance. -
Getting stuck with sending password reset email in django
I am trying to add user password reset functionality in my Django app using its core password reset functionality, with the help of a tutorial from Corey MS's youtube channel. I did exactly what he did. I am getting no error, but no emails are being sent. I have tried with my personal email server. I checked it using another python script using python smtplib and MIME, sending emails for me perfectly. But in Django, nothing happening. Then, I have gone through several articles and QAs. At last, I set up a local email server using the command-line with this python -m smtpd -n -c DebuggingServer localhost:1025 command. But the result is the same. Command-line says an email sent. But its not actually. Here are my screenshots and relevant codes. my app says, email sent. success message and project structure: urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' … -
Admin site is not working and throwing Error about one of the views but views are still working django
This is the Error it is throwing Plz check I am trying to get the posts related to certain tag and I did that but when I accessing admin panel it is showing on posts_tag view, I am not able to debug that why it is related to admin panel class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) tags = models.ManyToManyField('Tag',through='Tagged') class Meta: ordering=['-date_posted'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) `class Tag(models.Model): name=models.CharField(max_length=50) posts = models.ManyToManyField('Post',through='Tagged') def __str__(self): return self.name class Tagged(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE) tag = models.ForeignKey(Tag,on_delete=models.CASCADE) urls.py urlpatterns=[ path('',views.post_list,name='blog-home'), path('<tag>/',views.post_tag,name='blog-tag'), path('post/<int:pk>/',views.post_detail,name='post-detail'), path('post/new/',views.post_create,name='post-create'), path('post/<int:pk>/update/',views.post_update,name='post-update'), path('post/<int:pk>/delete/',views.post_delete,name='post-delete'), path('about/',views.about,name='blog-about')] views.py def post_tag(request,tag): t=Tag.objects.get(name=tag).posts.all() tags = Tagged.objects.all() return render(request,'blog/home.html',context={'posts':posts,'tags':tags})` -
How to render data based on condition statements in CHOICES field in django template?
Let me explain my question in simpler terms. I have the following code: models.py class Hotel(models.Model): name = models.CharField('Hotel Name', max_length=2000) Comfort = 'EC' Elite = 'EE' Smart = 'ES' Inn = 'EI' Consultancy = 'EY' CHOICES = [ (Comfort, 'Erica Comfort'), (Elite, 'Erica Elite'), (Smart, 'Erica Smart'), (Inn, 'Erica Inn'), (Consultancy, 'Erica Consultancy'), ] category = models.CharField(max_length=2, choices=CHOICES, default=Elite) def __str__(self): return self.name views.py def index_view(request): hotel = Hotel.objects.all() context = { 'hotel_list' : hotel, } return render(request, 'index.html', context) index.html <div class="col-lg-2"> <h2 class="cat_title">Erica Smart</h2> {% if hotel_list.category.choices == Smart %} {% for hotel in hotel_list %} <a class="dropdown-item" href="{{ hotel.get_absolute_url }}">{{ hotel.name }}</a> {% endfor %} {% endif %} </div> As you can see, in the above code, I want the list of hotels to be rendered based on their category which is going to be derived from one of the given choices in category field in models.py Note: There is no user input in this code, i.e. I am not using forms.py in the project. -
Multiple model form using class based views in django
I am trying to add two model forms in one class based view where i have a School model and Student model models.py from django.db import models from django.urls import reverse # Create your models here. class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse('app:detail',kwargs={'pk':self.pk}) class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name = 'students',on_delete=models.CASCADE) def __str__(self): return self.name forms.py from django import forms from app.models import School,Student class SchoolForm(forms.ModelForm): class Meta(): model = School fields = '__all__' widgets = { 'name':forms.TextInput(attrs={'class':'form-control'}) } class StudentForm(forms.ModelForm): class Meta(): model = Student field views.py from app.forms import SchoolForm,StudentForm from . import models from django.views.generic import CreateView class Register(CreateView): form_classes = {'school':SchoolForm,'student':StudentForm} #dont know how to include models models = [models.School,models.Student] template_name = 'school_form.html' and in school_form.html form.school, form.student plase help me how to add two model form in one class based view -
Google App Engine: error relation does not exist
so i'm deploying my django app to google app engine but after deploying i'm getting this error Exception Type: ProgrammingError at /api/seller/ Exception Value: relation "api_seller" does not exist LINE 1: ...ller"."user_id", "api_seller"."phone_number" FROM "api_selle... ^ -
django-tenant-schemas 1.10.0: TypeError: TenantTutorialMiddleware() takes no arguments
I am trying to use django-tenant-schemas 1.10.0. I have installed it and made migrations successfully. But the command "python manage.py runserver" produces the error: Exception ignored in thread started by: .wrapper at 0x000002282DBC2790> Traceback (most recent call last): File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\management\commands\runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super(Command, self).get_handler(*args, **options) File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\management\commands\runserver.py", line 68, in get_handler return get_internal_wsgi_application() File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\utils\module_loading.py", line 20, in import_string module = import_module(module_path) File "c:\program files\python38\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\tenant_tutorial\tenant_tutorial\wsgi.py", line 28, in application = get_wsgi_application() File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\handlers\wsgi.py", line 151, in init self.load_middleware() File "D:\projects\django-tenant-schemas-master\django-tenant-schemas-master\examples\lib\site-packages\django\core\handlers\base.py", line 82, in load_middleware mw_instance = middleware(handler) TypeError: TenantTutorialMiddleware() takes no arguments I'm using Postgres database. The error was the same when I tried with Django 1.11, 2.2, and 3.0. Please someone help me! -
django oscar bulk offer
Im new to Django Oscar framework. My goal is admin can create a product package with quantity. and also he can add bulk offer to that package (Absolute or FIxed Benefit). product package need to meets the product quantity in the basket, then the offer will apply. as example PRODUCT PACKAGE A PRODUCT A has 1 quantity PRODUCT B has 2 quantity to create this thing, i extend the range model and add quantity field. and also i extend condition and create custom package condition. to check if basket meets this product quantity. if basket has this product quantity or above quantity benefit will added. and another thing is if PRODUCT A has single offer. and if basket has 2 or more quantity in PRODUCT A, above product package offer and single offer also need to be applied separately, as example, class RangeProduct(AbstractRangeProduct): ''' add quantity field to default model ''' quantity = models.PositiveIntegerField(default=0) def __str__(self): return "{} quantity {}".format(self.product, self.quantity) class Package(models.Model): DISCOUNT_FIXED = 'DISCOUNT_FIXED' DISCOUNT_PERCENTAGE = 'DISCOUNT_PERCENTAGE' DISCOUNT_TYPES = ( (DISCOUNT_FIXED, 'Discount is a fixed amount off of the products value'), (DISCOUNT_PERCENTAGE, 'Discount is a percentage off of the products value') ) package_type = models.ForeignKey( PackageType, on_delete=models.CASCADE, related_name='packages', … -
In DjangoRF, how restrict some post only for post authors?
Can someone help me on this? I have an API that allows users to post some data and I would like to ONLY the author of the post visualize it. The API is working with Token Authentication and is set to avoid anonymous user see or update these posts... But I can't block logged users from viewing all posts. I have this model on models.py: class UserDataFeed(models.Model): user_profile = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) data = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) Here is the respective code on views.py: class UserData(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) serializer_class = serializers.UserDataSerializer queryset = models.UserDataFeed.objects.all() permission_classes = (permissions.UpdateOwnData, IsAuthenticated) def perform_create(self, serializer): """Sets the user profile to the logged in user""" serializer.save(user_profile=self.request.user) My serializers.py: class UserDataSerializer(serializers.ModelSerializer): class Meta: model = models.UserDataFeed fields = ('id', 'user_profile', 'data', 'created_on') extra_kwargs = {'user_profile': {'read_only': True}} And this is inside permissions.py: class UpdateOwnData(permissions.BasePermission): """Allow user to edit their own profile""" def has_object_permission(self, request, view, obj): """Check user is trying to edit their own profile""" if request.method in permissions.SAFE_METHODS: return True else: if request.user.is_superuser: return True else: return obj.user_profile.id == request.user.id I have already tried to change the BasePermissions and the logic on permissions.py, without success. Changing UpdateOwnData.has_object_permission seems to have no effect …