Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dictsort or dictsortreverse doesn't work second time in same template of Django, How can I do that?
Here is my template code in template.html file {% for obj in dictionary|dictsort:"name" %} do something {%endfor%} {% for obj in dictionary|dictsort:"age" %} do other thing {%endfor%} but in second iteration there is nothing hapening, on the first iteration everything is ok. -
How to achieve this type of API in Django rest framework
I am new to the Django rest framework and I am wanting to acheive this kind of API: { question_no: "1", question: "How many sides are equal in a scalene triangle?", options: [ { que_options: "3", selected: false, isCorrect: true }, { que_options: "2", selected: false, isCorrect: true }, { que_options: "0", selected: false, isCorrect: true }, ], }, How can I achieve the above type of API? I have tried to make make it work with the following code but it doesn't work: from django.db import models # Create your models here. class AnswerOptions(models.Model): option= models.CharField(max_length=500) isCorrect = models.BooleanField(default=False) class Quiz(models.Model): question = models.TextField() options = models.ManyToManyField(AnswerOptions) -
Django PDF parser on POST request
I hope for your help. Because I have been struggling with this problem for a long time. A POST request comes from the frontend with one PDF file, after which I need to take a screenshot of the first page and extract its metadata and save it all in the database. at the moment I have overridden the POST method and am intercepting the JSON which contains the PDF. I pass this file to my parsing function. But other than the file name, the function cannot find the file. What could be the problem? view import fitz as fitz from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer def parce_pdf(test): doc = fitz.open(test) # open document pixel = doc[0] # page pdf pix = pixel.get_pixmap() # render page to an image pix.save("media/page.png") # store image as a PNG print(doc.metadata) class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) # test = request.data['file'].content_type test = request.data['file'] # print(request.data.get) print(test) print(request.accepted_media_type) parce_pdf(test) print(file_serializer) # print(test) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer from rest_framework import serializers from .models import File class … -
Django admin wont let me log in with a custom user model
I've done a custom user model and when I try to log in to django admin it says "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.". I've tried creating a superuser using python manage.py createsuperuser but it returns: 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 "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 156, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' I've tried creating a user through CustomUser.objects.create(email=email, ...) I've tried checking if it is a staff, superuser and active. All of these returned True. Code Models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ class CustomUser(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(_('email address'), blank=False, null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True) user_id = models.CharField(_('session id'), max_length=10000, … -
Why Inline elements are disappearing when I use a filter through the get_queryset() in model.Admin?
I have a problem with Inline elements disappearing. It is linked to my overriding of get_queryset. I don't understand the mechanism which is behind. Any help would be great. I have two models like this : class Aventure(models.Model): title = models.CharField(max_length=30) sub_title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) archive = models.BooleanField(default=False) def __str__(self): return self.title class Scene(models.Model): title = models.CharField(max_length=30) description = models.TextField() aventure = models.ForeignKey(Aventure, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title And two model.Admins like this : class AventureAdmin(admin.ModelAdmin): readonly_fields = ('author',) list_display = ('title', 'author',) inlines = [ SceneInline, ] # allow to save the logged in user to be set has the author def save_model(self, request, obj, form, change): # dans le cas où l’utilisateur n’est pas renseigné if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() # Allow to show only the 'Aventure' instances where the author is the logged in user. def get_queryset(self, request): qs = super().get_queryset(request) print(qs) if request.user.is_superuser: return qs return qs.filter(author=request.user) class SceneInline(admin.TabularInline): list_display = ('title', 'author',) model = Scene show_change_link = True extra = 0 fields = ('title', 'author') And when the queryset is filtered on the author (means I am not superuser), the inline scene elements … -
How can we check on every login using stripe, Is payment of that specific user is successful?
How can we check on every login using stripe in DJANGO, Is payment of that specific user is successful? Because you know sometimes the payment is disrupted by the client or it may get unsuccessful after some time of successful payment of some reasons? -
Django - Wagtail: How to add classes to generated HTML elements from RichTextField
Using Wagtail 2.16.1, I have a BlogPage model that contains a body field which is a RichTextField. When I put {{ page.body|richtext }} into the template, the HTML that is rendered contains various html elements, as expected. I'd like to specify (tailwind) classes for these elements. E.g. every <p> element in a richtextfield should have <p class="mx-2 my-3">, h2 elements should have <h2 class="mt-5">, etc. -
Cannot add Django range filter to template
I am trying to get working the range-slider code from https://hackernoon.com/django-tutorial-creating-a-range-slider-filter-tt28359e I have got as far as creating views, models, templates adding some data to the Peoples model and displaying it. The code that works correctly displays the data from People model in a simple table. However, I cannot get the filter working. I have had to change some names in the sample code because of name conflicts with pre-existing items in my existing Django application. The first set of code works to display all the records from the model Peoples: #views.py from .models import People from .filters import PeopleFilter def Peopleindex(request): # display all the records from the People model/table all_people = People.objects.all() return render(request, 'pollapp2/Peopleindex.html', {'all_people':all_people}) template: <table border='1' style="width:50%; text-align:center"> <thead> <tr> <th> Name </th> <th> Surname </th> <th> Age </th> </tr> </thead> <tbody> {% for person in all_people %} <!-- for person in all_people --> <!-- for person in people_filter.qs --> <tr> <td> {{ person.name }} </td> <td> {{ person.surname }} </td> <td> {{ person.age }} </td> </tr> {% endfor %} </tbody> </table> The above correctly displays in an HTML table, all records from the Peoples model. Then when I try to modify the code to … -
Django multi-domain view set up / Django Sites. help needed
I'm trying to understand how to set up a Multisite codebase with Django (no external addons like Wagtail). I created several dummy domains and registered them on etc/hosts "example.com", "example2.com". They now both respond as if it's "localhost". I'm trying to find a way to make them go to different pages/views according to their different domains. I went through https://docs.djangoproject.com/en/4.0/ref/contrib/sites/ Sites documentation and am still stuck. The view that I'm trying to make work is this: def my_view(request): # current_site = request.get_host current_site = Site.objects.get_current() if current_site.domain == 'example2.com': html = "<html><body>Hello World at Example2 two</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass elif current_site.domain == 'example.com': html = "<html><body>Hello World at Example1 one</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass else: html = "<html><body>Hello World</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass I also tried changing the domain like below(It was done within a python shell within a pipenv shell), however it doesn't change it automatically by the domain address and will set it permanently to whichever one I saved: ((django-todo-react) ) ➜ backend git:(master) ✗ ./manage.py shell Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", … -
What are the risk for Secret KEy in Django?
I have a question regarding Django and Secret Key. Unfortunately, I've did a commit to a public repositary with secret key visible. Then I got a message: GitGuardian has detected the following Django Secret Key exposed within your GitHub account. I then immediatelly deleted this repo from my github but still worried if something can happen to me. The app was just hello world on my localserver. I red some articles that it is very dangerous but I am not sure if someone can hack me by this. Can you advise? Thanks. -
Django-Reactjs : No Access-Control-Allow-Origin header is present on the requested resource
I'm trying to load an image from an image url and try to crop that image. Access to image at 'https://example.com/image.png' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I'm using React and Django. app.js import { useState,useCallback,useRef, useEffect} from 'react'; import React, { Component } from "react"; import ReactCrop from "react-image-crop"; import 'react-image-crop/dist/ReactCrop.css' function App() { const [crop, setCrop] = useState({ aspect: 1.7777777777777777, height: 84.92083740234375, unit: "px", width: 325.97037760416663, x: 0, y: 140.07916259765625} ); function onImageLoad() { const image = new Image(); image.src = "https://example.com/image.png"; image.crossOrigin = "Anonymous"; const canvas = document.createElement('canvas'); const scaleX = image.naturalWidth / image.width; const scaleY = image.naturalHeight / image.height; const ctx = canvas.getContext('2d'); const pixelRatio = window.devicePixelRatio; canvas.width = crop.width * pixelRatio * scaleX; canvas.height = crop.height * pixelRatio * scaleY; ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); ctx.imageSmoothingQuality = 'high'; image.onload = function() { ctx.drawImage( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width * scaleX, crop.height * scaleY ); } const base64Image = canvas.toDataURL("image/jpeg", 1); setResult(base64Image); console.log(result); } useEffect(() => { onImageLoad(); }, []); return ( { result && <div> <h2>Cropped Image</h2> <img alt="Cropped Image" src={result} … -
'Connection aborted.', ConnectionResetError 10054 error in django while trying to make a post request with files
I'm working on a django project for which I'm using an external API service. I have to send image files in the payload as well. When making a post request to the service, I'm getting this error: ConnectionError ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) Some key points are: The request works perfectly fine on Postman. The error appears only when I attach FILES in the payload, without which it works fine. -
Accessing the "many" side from the "one" side effectively
Considering the following models: class ManySide(django.db.models.Model): one_side = models.ForeignKey( to=OneSide, on_delete=models.PROTECT, related_name="related_one_side" ) class OneSide(django.db.models:model): # not containing any field relevant here def many_side_elements(self): pass # ? What should I include in method many_side_elements so that calling it from a OneSide Model instance would list a queryset of ManySide elements? Official docs imply that given o is a OneSide isntance, o.many_side_set.all() should work but it returns an error in shell. My current solution is the following: from django.apps import apps [...] def many_side_elements(self): ManySideModel = apps.get_model('<app_name_here>', 'ManySide') val = ManySideModel.objects.filter(one_side=self) But I'm concerned it's ineffective since it requires importing the other Model. Actually it caused a circular dependency error message in my project, hence the get_model usage. Is there any better way? Or xy_set should work in the first place? Then what am I doing wrong? -
No module named '_overlapped'
Working on a masters project and a fellow course mate has developed a web application using Django on a windows computer and has sent the file to us. I am trying to run the server on my MacBook terminal but when I run it, get the error "ModuleNotFoundError: No module named '_overlapped'. I have installed trollius as recommended in a previous post but hasn't worked for me. any help? -
The value I got from the jQuery is NoneType in django
I want to implement a function that updates the graph and displays the number of updates when the button is pressed. However, when I try to get the parameter in view.py using jQuery, it returns NoneType instead of the intended value. What is the problem? Also, I don't know if this is related, but when I use console.log() in a jQuery function, there is no output on the console of the browser developer tools. This doesn't seem to have anything to do with the error-only mode or the filter I entered in Console. The error is TypeError at /graph/update_graph int() argument must be a string, a bytes-like object or a number, not 'NoneType' Thank you. Here is the code views.py from xml.etree.ElementInclude import include from django.shortcuts import render from django.http import JsonResponse from . import graphdata def index(request): fig = graphdata.get_scatter_figure() plot_fig = fig.to_html(fig, include_plotlyjs=False) return render(request, 'graph/index.html', {'graph':plot_fig}) def update_graph(request): graph = graphdata.get_scatter_figure() grahp_html = graph.to_html(graph, include_plotlyjs=False) cnt = int(request.POST.get('count')) # <-- This is the error point cnt += 1 data = { "graph": grahp_html, "count": cnt, } return JsonResponse(data) index.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- plotly JS Files --> <script … -
Two forms, one view, one ONE-TO-MANY relationship, how to get the id, the FK - DJANGO
First of all, just a disclaimer, i'm only posting because none of the topics here on the stack helped me, not even the related suggestions when i named this topic... I'm new to django, I'm working on opening a support ticket, I've been struggling with this problem for two days.... Is it possible to assign a value to the field defined in model.py by view.py? My problem is having two model classes, two forms with one-to-many relationship, which are rendered on the same page and must be saved when clicking a button only My models: class Ticket(models.Model): objects = None user_id = models.ForeignKey(User, null=False, blank=False, on_delete=models.DO_NOTHING) created_at = models.DateTimeField('Created at', auto_now_add=True) class MessageTicket(models.Model): objects = None ticket_id = models.ForeignKey(Ticket, null=False, blank=True, on_delete=models.DO_NOTHING) status = models.CharField(default=TicketStatus.TO_DO) content = models.TextField(null=True, default='') The point here is that 'ticket_id' in the 'MessageTicket' class should receive the 'id' of the last 'Ticket' saved, but as both are saved at the same time I'm not able to pull the last 'id' of the 'ticket'. My view, where saved in the database: As I said above I went through some forums and tried some things (in second 'IF'), I didn't leave them here to keep the code … -
Login System from .net Framework c# and need to connect it with rest API django python
I have a database created by someone using C# .Netframework, and now I need to create API using django and connect this API to the same database. But I can't program the login part because I don't know how to compare PasswordHash. As I read, .netframework stores the salt and hash together as PasswordHash PasswordHash= salt + hash( salt + pass) I need help to know which part is salt and which is the hash. Example of PasswordHash from database AQAAAAEAACcQAAAAEDFUVYGRfWBcYsa6qzyOdvc0a96dIVdaDpMJEU9OojIf1KCsdZrTa2Dem5yLnuAU6A== -
Override translation file django
I'm actually coding a web app with django and just started to use django allauth to go a bit quicker in the creation of my user interface. I've successfully changed the design of the templates by adding the templates from their github repo to my project. But I wanted to do the same with the translation because I want my app to be in french. So I did the same : I added the "locale" folder to my project and edited some things in the .po files but no change happened. Does someone know what to do, like what more is needed to override the ancient traductions ? Thanks in advance. -
'tuple' object has no attribute '_meta' while implementing serializer
I am implementing serializers for my models. But I am getting this error while accessing the api endpoint saying "'tuple' object has no attribute '_meta'". Here are my models and serializers Models class WorkflowStep(models.Model): name = models.CharField(max_length=200) workflow = models.ForeignKey('WorkflowType', null=True, blank=True, related_name='workflow', on_delete=models.SET_NULL) allowed_statuses = models.ManyToManyField("WorkflowStepStatus", null=True, blank=True, related_name='status') active_status = models.ForeignKey('WorkflowStepStatus', null=True, blank=True, related_name='active_status', on_delete=models.SET_NULL) default_status = models.ForeignKey('WorkflowStepStatus', null=True, blank=True, related_name='default_status', on_delete=models.SET_NULL) should_recheck = models.BooleanField(null=True, blank=True) step_type = models.ForeignKey("WorkflowStepType", on_delete=models.SET_NULL, null=True, blank=True, related_name='step_type') trigger_on_new_version = models.BooleanField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.name + "_" + self.workflow.name class Prerequisite(models.Model): workflow_step = models.ForeignKey("WorkflowStep", null=True, blank=True, on_delete=models.CASCADE, related_name='workflow_step') pre_requisite_step = models.ForeignKey('WorkflowStep', null=True, blank=True, on_delete=models.SET_NULL, related_name='pre_requisite_step') pre_requisite_step_status = models.ManyToManyField("WorkflowStepStatus", null=True, blank=True, related_name='pre_requisite_step_status') id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.workflow_step.name + "_pre_req_" + self.workflow_step.workflow.name Serializers class WorkflowStepSerializer(serializers.ModelSerializer): workflow = WorkflowTypeSerializer(many=False) allowed_statuses = WorkflowStepStatusSerializer(many=True) active_status = WorkflowStepStatusSerializer(many=False) step_type = WorkflowStepTypeSerializer(many=False) prerequisite = serializers.SerializerMethodField() class Meta: model = WorkflowStep fields = '__all__' def get_prerequisite(self, obj): pre_requisites = obj.workflow_step.all() serializer = PrerequisiteSerializer(pre_requisites, many=True) return serializer.data class PrerequisiteSerializer(serializers.ModelSerializer): workflow_step = WorkflowStepSerializer(many=True) pre_requisite_step = WorkflowStepSerializer(many=True) pre_requisite_step_status = WorkflowStepStatusSerializer(many=True) class Meta: model = Prerequisite, fields = "__all__" Error AttributeError at /api/workflowsteps/ 'tuple' object has no attribute '_meta' Request Method: GET Request … -
select2 ajax not show list of option, shows only the first option - django
I'm trying to make my drop down list into a ajax response via select2(version 4.0.7), but it only shows the first option, and select it automatically! i want to be able to which one i want to select note : i tried alot of answers in stackoverflow, but none of them worked here is my view @login_required def return_ajax_guests(request): if request.is_ajax(): term = request.GET.get('term') all_guests = Vistor.objects.all().filter(full_name__icontains=term) return JsonResponse(list(all_guests.values('full_name','city__name','dob')),safe=False) and here is my templates $(document).ready(function () { $('#guestinfo-0').select2({ ajax: { url: '{% url "return_ajax_guests" %}', dataType: 'json', processResults: function (data) { console.log(data) return { results: $.map(data, function (item) { $('#guestinfo').append("<option value='"+item.full_name+"' selected>"+item.full_name+"</option>") $('#guestinfo').trigger('change'); return {full_name: item.full_name, city: item.city__name}; }) }; } }, minimumInputLength: 1 }); }); <div class="col-span-5 groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "info" %}</label> <select name="guestinfo-0" id="guestinfo-0" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white"> </select> </div> is there a way to achieve that please? thank you in advance .. -
GCP, Django problem connection refused when trying to connect to the server
My django project runns normally on localhost and on heroku also, but when I deployed it to google cloud platform I am getting this error: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/<connection_name>/.s.PGSQL.5432"? The connection to the database in settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'database_name', 'USER': 'postgres', 'PASSWORD': "password", # production 'HOST': '/cloudsql/connection_name', 'PORT': '5432', } Additionally, my app.yaml looks like runtime: python37 handlers: - url: /static static_dir: static/ - url: /.* script: auto env_variables: DJANGO_SETTINGS_MODULE: fes_app.settings requirements.txt looks like this plus sqlparse==0.4.2 toml==0.10.2 uritemplate==4.1.1 urllib3==1.25.11 whitenoise==5.2.0 twilio==6.9.0 I have tried using the binary version of psycopg, also gave a role client sql to the service account in the cloud. **NOTE : ** I am using an app engine standard environment -
Django url dispetcher route by id
this is my views.py class UserAPI(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated,] serializer_class = UserSerializer def get_object(self): return self.request.user and this is my url.py path('V1/api/users/', UserAPI.as_view(), name='user'), when i enter id,mail,username and go to localhost/v1/api/users/1 want to open user's which id is 1. what is best solutions ? -
AttributeError at /profile/create 'ProfileCreate' object has no attribute 'errors'
I am working on a social media project and getting this error while creating any profile. Please help me through this. Below is code mentioned. view.py from multiprocessing import context from pickle import FALSE from django.shortcuts import render,redirect from django.views import View from .form import CreateUserForm, ProfileForm from .models import CustomUser, Profile from django.contrib import messages from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView, UpdateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView # Create your views here. def index(request): context = {} return render(request,'index.html',context) def registration(request): userform = CreateUserForm(request.POST) if request.method=='POST': if userform.is_valid(): userform.save(commit='FALSE') else: messages.error(request,'An Error Occured!!') Users = CustomUser.objects.all() context = {'User': Users, 'form': CreateUserForm } return render (request,'registration.html',context) def log_in(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username,password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request,'Username or Password is incorrect') context = {} return render(request,'login.html',context) @login_required def log_out(request): logout(request) messages.info(request, "Logged out successfully!") return redirect('index') @login_required def home(request): return render(request,'home.html') class ProfileCreate(CreateView): def get_queryset(self): return Profile.objects.all() fields = [ 'image', 'first_name', 'last_name' ] template_name = 'profile.html' success_url = "/home" def form_valid(self, form): print(form.cleaned_data) ProfileForm.save(self) return super().form_valid(ProfileForm) class ProfileDetailView(DetailView): model = Profile template_name = "profileview.html" … -
django choicefield Select a valid choice
I'm trying to submit my modelform with ajax loaded info of my other models. For the ChoiceField of my modelform I got this error; Select a valid choice. 69 is not one of the available choices. the request.POST seems well. I got all my fields properly. As my remind_object field is CharField already, I should be able to save ['69'] to there but I can't figure out why I got this error ? *** request.POST: <QueryDict: {'csrfmiddlewaretoken': ['dTtWIUKCOytmYVsbGf7StxMmd4ywPd0gzvvraAgrqiLuiUfLv3xo2TD1lv9Xpcxs'], 'topic': ['dsfdsfs'], 'remind_date': ['2022-02-22 13:45:59'], 'reminder_object_type': ['Client'], 'remind_object': ['69'], 'detail': ['<p>fdgfdgfd</p>\r\n'], 'submit_reminder_create_form': ['']}> models.py class Reminder(models.Model): user_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reminder_user') # user.reminder_user topic = models.CharField(max_length=100, blank=True, null=True) remind_date = models.DateTimeField(blank=True, null=True) reminder_object_type = models.CharField(max_length=100, blank=True, null=True) # Client # Contact # Action remind_object = models.CharField(max_length=999, blank=True, null=True) detail = RichTextField(max_length=999999,blank=True, null=True) reminder_status = models.CharField(max_length=100, default="Active", blank=True, null=True) slug = models.SlugField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.topic) def save(self, *args, **kwargs): self.slug = slugify(str(self.topic) + "-" + str(self.user_owner) + "-" + str(get_random_code())) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('reminder-detailview', kwargs={'slug': self.slug}) forms.py class ReminderModelForm(forms.ModelForm): class Meta: model = models.Reminder fields = ('reminder_object_type', 'topic', 'remind_date', 'remind_object', 'detail') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['reminder_object_type'] = forms.ChoiceField(required=True, label="", widget=forms.RadioSelect(attrs={'class': … -
Django 3.1 Field Level Permission
I have a User Form with 20+ Fields and 5 different user roles accessing the same form. Based on the Role, I need to set Field Level Permissions for the form. e.g User belonging to User Group 1 can create/edit/view all fields User belonging to User Group 2 can edit/view Fields 5, 6 and 7 only User belonging to User Group 3 can edit all fields but 9 and 10, view all Fields except 15 and 16. User belonging to User Group 4 can only view all fields but 9 and 11. So on and So forth. Any help with the same will be appreciated Thank you.