Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework : Filtering against Table Field value
I'm improving my Django Web App with Django Rest API part and I have a question according to filtering against table field value. I have my serializer class like this : class IndividuResearchSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'id', 'NumeroIdentification', 'Nom', 'Prenom', 'VilleNaissance', ] My views.py file with this class : class IndividuResearchAPIView(ListAPIView) : permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) serializer_class = IndividuResearchSerializer def get_queryset(self): queryset = Individu.objects.all() NIU = self.request.query_params.get('NumeroIdentification') queryset = queryset.filter(NumeroIdentification=NIU) return queryset And my pythonic file which let to simulate connexion from another software based to API Rest : import requests mytoken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IkFkbWluIiwiZXhwIjoxNTE5NzMxOTAxLCJlbWFpbCI6InZhbGVudGluQGRhdGFzeXN0ZW1zLmZyIiwib3JpZ19pYXQiOjE1MTk3MjgzMDF9.493NzJ4OUEzTKu5bZsZ9UafMwQZHz9pESMsYgfd0RLc" url = 'http://localhost:8000/Api/Identification/search/' NIU = "I-19312-00001-305563-2" response = requests.get(url, NIU = NIU, headers={'Authorization': 'JWT {}'.format(mytoken)}) print(response.text) I would like to enter a NIU value into my request in order to filter my table and return the object according to this NIU. For example, in my database I have this object : I would like to return this object thanks to my API but I don't know if my function get_queryset is well-writen and How I can write my API request. Into my urls.py file, I have : url(r'^search/$', IndividuResearchAPIView.as_view() , name="Research"), So I am not making a … -
Unable to login a custom user using CBV in django
While trying my luck with Class Based views in Django, I am unable to get a custom user logged in. Here is my view: class Loginview(FormView): form_class = LoginForm template_name = 'login.html' def get(self, request, *args, **kwargs): return render(request, 'login.html', {'form': LoginForm}) def form_valid(self, form): return redirect('dashboard') def form_invalid(self, form): return render(self.request, 'login.html', {'form': form}) My form: class LoginForm(ModelForm): class Meta: model = Company fields = ['email', 'password'] My model: class Company(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=50) address = models.CharField(max_length=50) phone = models.CharField(max_length=50) date_joined = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=50, unique=True) is_staff = models.BooleanField(default=True) email_confirmed = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = UserManager() FYI this is a custom model and has a separate user Manager. Whenever I submit the login template with the email and password fields, it returns me a form error saying that email and password do not match while they should be matching. -
how to convert evtx log file into cef log file using python script
List item i want to convert evtx log file in windows to convert in to .cef format using python script with the help of wmi so please suggest some answers for this problem -
LginRequiredMixin doesnt work in Django
i used LoginRequiredMixin restrict access only to logged in user. but still i am able to access that page. what mistake am i making here. VIEWS.PY class AddSupportUserView(LoginRequiredMixin,View): def get(self, request): form_class = AddSupportUserForm return render(request, 'add_support_user.html', { 'form': form_class, }) def post(self, request): form_class = AddSupportUserForm username = request.POST.get('username') email = request.POST.get('email') try: user_obj = User.objects.get(username=username) return render(request, 'add_support_user.html', {'errors': 'User already exits', 'form': form_class}) except User.DoesNotExist: user_obj = User.objects.create_user(username=username, email=email, is_staff=True, is_superuser=False) user_obj.set_password(email) user_obj.save() group_obj = Group.objects.get(name='support_group') user_obj.groups.add(group_obj) return HttpResponseRedirect('/admin/auth/user/') -
django dictionary for loop not printing anything
There are already a lot of questions+answers regarding for loops in django, but none of the solutions work for me, so there must be something fundamentally wrong. I have a dictionary in python/json (tried both) that I want to loop through and print. Doing the following print a new line for each character {% for item in data.dict %} <p>{{item}}</p> {% endfor %} so something like this get's printed { ' N o d e ' : The following code straight up prints nothing {% for key, values in data.dict.items %} <p>{{key}}</p> {% endfor %} Data is the name of my registered model and object is one of its variables. In my Views.py I have something similar to this: Data.objects.create( dict=theDictIAmPassing }.save -
AJAX django get request
Can u help me, please! I need to render a new content, when i click on button without refresh page. Now I am using jQuery cookie plugin, save button id into cookie, then read in view that value and render page. But it does not look friendly :c My JS: function initBrandSelector() { $('.tab button').click(function(){ var brand = $(this).val(); if (brand) { $.cookie('current_brand', brand, {'path': '/', 'expires': 365}); } else { $.removeCookie('current_brand', {'path': '/'}); } location.reload(true); return true; }); } $(document).ready(function(){ var brand = $.cookie('current_brand'); if (brand) { $('.tab button[value=' + brand + ']').addClass("active"); } initBrandSelector(); }); My view: def smartphones_list(request): current_brand = get_current_brand(request) if current_brand: smartphones = Smartphone.objects.filter(brand=current_brand) else: smartphones = Smartphone.objects.all() context = paginate(smartphones, 6, request, {}, var_name='smartphones') return render(request, 'main/smartphones_list.html', context) -
Integrity error when trying to save many-to-many field data
I have a Course model and a StudentData model. In order to enroll students to courses, I added a many-to-many field to the Course model. I can list the students with a checkbox, but problem is, when I press the Enroll button, to add those students to the course, I get the following error: http://dpaste.com/3E1XR4P #views.py if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): form.save() redirect('classroom') else: form = CourseForm() #forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ('student', ) widgets = { 'student': forms.CheckboxSelectMultiple } #models.py class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "Doctoral Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) slug = models.SlugField(max_length=140, unique=False, default=None, null=True, blank=True) class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default=None) name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, verbose_name="Course Teacher", related_name='%(class)s_course_teacher') teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True, verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher') slug = models.SlugField(max_length=150, unique=True) student = models.ManyToManyField('StudentData', default=None) class StudentData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) enrolled = models.BooleanField(default=False) #enroll.html <form action="" … -
502 Bad Gateway. Django Google App Engine
I deployed my django project in GAE and I get the 502 Bad Gateway error on all pages except the main one. The previous version was working, but is not working since I added API calls for storage (storages.backends.gcloud.GoogleCloudStorage). I added environment variable GOOGLE_APPLICATION_CREDENTIALS in both settings.py and app.yaml. Log shows this error: [error] 32#32: *111 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: , request: "GET /accounts/login/ HTTP/1.1", upstream: "http://xxx.xxx.xxx.xxx:8080/accounts/login/", host: "xxxx.appspot.com", referrer: "https://xxxx.appspot.com/" All is working in local, so that message is all I have. I tried things from google groups and other stackoverflow questions but it's not working. Thank you. -
Casting result from Database Function not working
I'm using the following to get the ISO Week Date: class DateWeek(Func): """ Return the ISO8601 Week Number """ def as_mysql(self, compiler, connection): self.function = 'WEEK' self.output_field = IntegerField() self.template = 'CONVERT(%(function)s(%(expressions)s, 3), UNSIGNED INTEGER)' return super().as_sql(compiler, connection) Which works fine: MyObj.annotate(wk=DateWeek('date')).values('wk') <QuerySet [{'wk': 1}, {'wk': 21}]> ...until I want to do something like: MyObj.annotate(wk=DateWeek('date')).filter(wk__gt=20) When I try and do this I get a dateparse error as Django is trying to calculate the filter assuming that wk is a date of some kind. I've set the output_field to IntegerField, is there anything else I should be doing? -
Channels 2 - When two users are on the same websocket connection, consumer is run twice
Based on the Channels 2 example, I've implemented a one-to-one chat with message persistence. I'm having an issue with chat_message() being run twice(message being broadcast/saved twice) whenever two users are sharing the same channel(live-chatting with each other). When they aren't on the same websocket connection, the messages will work as normal(send once). What's wrong with my configuration? This is the entire consumer--the saving happens in the very last function--chat_message(). It is called in send_room() itself called in receive_json() : class ChatConsumer(AsyncJsonWebsocketConsumer): ##### WebSocket event handlers async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ # Are they logged in? if self.scope["user"].is_anonymous: # Reject the connection await self.close() else: # Accept the connection await self.accept() # Store which rooms the user has joined on this connection self.rooms = set() async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass it as the first argument. """ # Messages will have a "command" key we can switch on command = content.get("command", None) recipient = content.get("recipient", None) sender = self.scope["user"] try: if command == "join": # Make them join the room await self.join_room(content["room"]) previous_message_list = await … -
dajngo text in form is not translating
I have the following code in my forms.py: def validate(self, request): try: id_exists(request, self["user"].data) except: self.add_error('user', ugettext_lazy("id is not available")) the problem is when my 'user' filed is not validated in my validate function, the error is displayed in English, however other texts in my whole project are translating. using ugettext_lazy nor ugettext solved the problem. Is there anything I am missing? tnx -
Django: failed: Error during WebSocket handshake
I'm getting below error WebSocket connection to 'ws://localhost/ws/testNoti?subscribe-broadcast&publish-broadcast&echo' failed: Error during WebSocket handshake: Unexpected response code: 500 Websocket connection is broken! supervisor conf file [unix_http_server] username = ubuntu password = password [program:uwsgi] command=/home/laptop30/bxd-life/venv/bin/uwsgi --ini /home/laptop30/bxd-life/bxd/bxd.ini autostart=true user=ubuntu autorestart=true stderr_logfile = /home/laptop30/bxd-life/logs/err.log stdout_logfile = /home/laptop30/bxd-life/logs/out.log stopsignal=INT [program:uwsgi_ws] command = /home/laptop30/bxd-life/venv/bin/uwsgi --http :8080 --gevent 1000 --http-websockets --workers=2 --master --module bxd.wsgi_websockets #directory=/home/laptop30/bxd-life/bxd autostart=true autorestart=true starttries=5 user=ubuntu environment=DJANGO_SETTINGS_MODULE='bxd.settings' nginx conf file upstream app_server { server localhost:8000; } upstream web_socket_server { server localhost:8080 fail_timeout=0; } server { listen 80; server_name _; location /static/ { alias /home/laptop30/bxd-life/bxd/static/; expires 30d; } location /ws/ { proxy_pass http://web_socket_server; proxy_http_version 1.1; #proxy_redirect ws://$server_name; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } } wsgi_websockets.py import os import gevent.socket import redis.connection redis.connection.socket = gevent.socket os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bxd.settings") from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer() The above is working fine with ./manage.py runserver but not with nginx! Any help would be very much appreciated. -
Django: Prevent users from editing other accounts
I have created a simple API for editing user profile. class EditProfile(generics.UpdateAPIView): serializer_class = UserSerializer queryset = get_user_model().objects.all() permission_classes = (IsAuthenticated,) How can I prevent the user from editing other user's profile? -
DjangoRestFramework URLS with Django2.0
I'm trying to set up DjangoRestFramework with a Django2.0 project which means url(r'^something/' ... has been replaced with path(something/ ... I'm trying to work out how to set my rest_framework patterns. This is what I have: router = routers.DefaultRouter() router.register(r'regulations', api.RegulationViewSet) router.register(r'languages', api.LanguageViewSet) urlpatterns = [ ... path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ... ] If I got to http://127.0.0.1:8000/regulations I simply get Page not found (404) How should I set up my urlpatterns? -
How do I deserialize list of multiple objects in django rest framework?
I am developing a rest API that gets requests composed of multiple objects and saves them to the database. Then, another array of objects is returned as the response. All objects are of only one model. class Ratings(models.Model): id = models.AutoField(primary_key = True) userId = models.IntegerField() movieId = models.IntegerField() rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) timestamp = models.DateTimeField(auto_now = True) class RatingsSerializer(serializers.ModelSerializer): class Meta: model = Ratings fields = ('userId','movieId','rating') class RecommendationGenerator(generics.ListCreateAPIView): queryset = Ratings.objects.filter(id__in=(1,2))#all() serializer_class= RatingsSerializer def post(self, request, format='json'): serializer= RatingsSerializer(data = request.data, many = True) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN) When I test it in Postman with the JSON: [{ "userId": 13, "movieId": 1765, "rating": 5 }, { "userId": 13, "movieId": 1733, "rating": 3 }, { "userId": 13, "movieId": 1713, "rating": 2 }, { "userId": 13, "movieId": 963, "rating": 2 } ] The result is []. But for { "userId": 13, "movieId": 1765, "rating": 5 } The result is { "userId": 13, "movieId": 1765, "rating": 5 } How do I deserialize this data? What am I doing wrong here? -
Django: Overriding 'objects' of superclass without changing the code in superclass
I have 2 classes defined like: class Parent(models.Model) def foo: pass And the child class: class Child(Parent): def foo: print('abc') Now I want to override the 'objects' of class Parent. Normally it will go like this: class Parent(): objects = Child() But I can't modify class Parent because it's a third party library. Is there any workaround for this problem? -
must we render serialized data to json before sending response? DRF
The answer to this question is confusing me. Multiple Models in Django Rest Framework? the answer is to a question of sending multipule models in a response. I have the same use case. the author of the answer has this: def get(self, request, format=None, **kwargs): cart = get_cart(request) cart_serializer = CartSerializer(cart) another_serializer = AnotherSerializer(another_object) return Response({ 'cart': cart_serializer.data, 'another': another_serializer.data, 'yet_another_field': 'yet another value', }) but I am keeping with the documentation. http://www.django-rest-framework.org/api-guide/serializers/#serializing-objects EXAMPLE FROM DOCS serializer = CommentSerializer(comment) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} from rest_framework.renderers import JSONRenderer json = JSONRenderer().render(serializer.data) json # b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}' so which one is it? Do I JSON or not JSON. This is what I currently have. def get(self, request, format=None): searchcityqueryset = SearchCity.objects.all() neighborhoodqueryset = SearchNeighborhood.objects.all() serializedsearchcity = SearchCitySerializer(searchcityqueryset) serializedsearchneighborhood = SearchNeighborhoodSerializer(neighborhoodqueryset) jsonsearchcity = JSONRenderer().render(serializedsearchcity.data) jsonsearchneighborhood = JSONRenderer().render(serializedsearchneighborhood.data) return Response({ 'searchcity': jsonsearchcity, 'searchneighborhood': jsonsearchneighborhood, }) -
Why does testing uploaded media files during testing gives 404 with django webtest?
I have the following TestCase that adds an uploaded file to the model: from django_webtest import WebTest class LeaveDocumentPermissionTests(WebTest): '''Tests for supporting doc permissions ''' def setUp(self): # User uploads a supporting doc self.supporting_doc_leave_request = LeaveRequest.objects.create( user=self.user1, start_date='2017-12-10', end_date='2017-12-21', supporting_doc=SimpleUploadedFile( name='my-sick-note.pdf', content=open(TEST_PDF_PATH, 'rb').read(), content_type='applicaiton/pdf' ) ) def test_uploading_user_can_access(self): '''Ensure user that uploaded the file can view and download it''' file_url = self.supporting_doc_leave_request.supporting_doc.url response = self.app.get( file_url, user=self.user1, ) self.assertEqual(response.status_code, 200) The response I get is: webtest.app.AppError: Bad response: 404 Not Found (not 200 OK or 3xx redirect for http://testserver/media/uploads/leave/user_22/2017-12-10-my-sick-note_EZSplOs.pdf) b'<h1>Not Found</h1><p>The requested URL /media/uploads/leave/user_22/2017-12-10-my-sick-note_EZSplOs.pdf was not found on this server.</p>' So the uploaded file seems to not exist. Why is the file not being uploaded to the server or served? Whoops I think the test server is not serving the media url. I have the following in urls.py: if settings.DEBUG: urlpatterns + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) So when the tests run settings.DEBUG is False so that url is not there. -
Django LDAP E-Mail as Username
I am trying to login as a LDAP-user with an e-mail adress. I used the following code: settings.py AUTH_LDAP_SERVER_URI = "ldap://192.168.12.123" AUTH_LDAP_BIND_DN = "User" AUTH_LDAP_BIND_PASSWORD = "Password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_ONELEVEL, "(uid=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_E_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, ldap.SCOPE_ONELEVEL, "(mail=%(user)s)") AUTH_LDAP_E_USER_ATTR_MAP = AUTH_LDAP_USER_ATTR_MAP AUTH_LDAP_E_ALWAYS_UPDATE_USER = AUTH_LDAP_ALWAYS_UPDATE_USER AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', #'django.contrib.auth.backends.ModelBackend', 'accounts.backends.LDAPEmailBackend', ) backends.py from django_auth_ldap.backend import LDAPBackend, _LDAPUser class LDAPEmailBackend(LDAPBackend): settings_prefix = "AUTH_LDAP_E_" def get_or_create_user(self, email, ldap_user): model = self.get_user_model() username_field = getattr(model, 'USERNAME_FIELD', 'username') kwargs = { username_field + '__iexact': ldap_user.attrs['uid'][0], 'defaults': { username_field: ldap_user.attrs['uid'][0].lower(), 'email': email } } return model.objects.get_or_create(**kwargs) The console gives me this: search_s('DC=sbvg,DC=ch', 1, '(uid=%(user)s)') returned 0 objects: Authentication failed for ipa@sbvg.ch: failed to map the username to a DN. Caught LDAPError while authenticating ipa@sbvg.ch: SERVER_DOWN({'desc': u"Can't contact LDAP server"},) If you have any idea,,do not hesitate to post it. Any help is much appreciated. Thanks in advance. -
axios POST not working, but working in postman
In a Django rests framework + Reactjs virtual environment: I have an axios post call as follows: var data = JSON.stringify({diagnosis: diagnosis, frequency: frequency}); axios.post('/by/frequency/'+id, data, { headers: { 'Content-Type': 'application/json', } }); which gives me the following error: POST http://localhost:8000/by/frequency/86 403 (Forbidden) my json console.log output: {"diagnosis":"strep throat","frequency":3} However, when I do a post request in postman, it succeed as seen in the screenshot below: I've been working on this for several hours and can't figure out why. -
How to use django on two databases
I have a legacy Django project with a legacy database. That project uses django.contrib.auth.User as the user model. Now I need to write a new Django project and that app has to get access to the legacy database. The problem is that my new Django project also needs a User object. So how do I route django.contrib.auth.user models into the correct database? Another possible way to do this: is it possible to "bootstrap" a Django app for use inside another project? So if I have a legacy Django app with legacy settings.py, and I want to use the Django model functionality inside a new Django project with new settings.py (and it has its own apps), is there a way to do this? -
How do I convert a CSS file into JSON object?
I am trying to make a style editor using python Django. I need to convert a CSS file to JSON and vice-versa. Is there any Plugin or some thing in Django.? I also need to upload this file to git, How do I do that with Python? -
How to create Prefetch queryset based on parent queryset in django
Here is the scenario, a project model which contains multiple bids. `Class Project(models.Model): user = models.ForeignKey() Class Bid(models.Model): project = models.ForeignKey(Project, related_name='bids')` When we are querying projects, we want to prefetch bids for projects. Project.objects.filter(whatever condition).prefetch_related( Prefetch('bids', queryset=Bid.objects.all()) ) Here we only want to fetch the bids that belongs to the filtered projects, but not all the bids, how can we specify that? I am expecting something like queryset=Bid.objects.filter(project=project?)... Thanks. -
Type Error in get_wsgi_application() in Django 2.x with python3
I am migrating a web application from Django 1.9 to 2.0.2. The code is import os import sys path = '/mypath' if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Myapplication.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() However, if I try to execute this, I get an error: File "/home/.../wsgi.py", line 29, in <module> application = get_wsgi_application() File "/home/.../virtual/lagerthree/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/.../lagerthree/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 140, in __init__ self.load_middleware() File "/home/.../virtual/lagerthree/lib/python3.5/site-packages/django/core/handlers/base.py", line 39, in load_middleware mw_instance = middleware(handler) TypeError: object() takes no parameters According to StackExchange and other sites, the cause of this error is the deprecation of certain things from 1.x to 2.x and the solution is the MiddlewareMixin which should be used like this: class FOOMiddleware(MiddlewareMixin): ... But I don't have any classes and also, the get_wsgi_application() function should still work, as far as I know. How should I solve this? -
Django Python : adding custom permissions to specific users
Models.py class Meta: permissions = ( ("can_add_data","can add a new data"), ) This is the custom permission I've created in Models.py and I've also created these users. Users in Django Admin ie., http://localhost:8000/admin click the hyperlink to view image How do I give permission to specific users so that I can use @permission_required('myapp.can_add_data') in views.py and also where do I write the snippet? ( in which file ) I'm a beginner at this so if there are any mistakes please let me know.