Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sort paginator list django template
I need to display a very long list in a table in django templates. since it takes really long to show all the results, I'm using paginator and that way I see the results in no-time. The problem now is that I need to sort this table (by clicking on a columns) in the client side but I could not find any way to to it fast - I either sort each page of the table and it's not a good enough or sort the entire table by using DataTable and it takes forever. any ideas to sort quickly? -
Django+Gunicorn incorrect logs timestamp
In my Django settings I have utc+3 configured time so the expectations were to get all logs in utc+3, but turned out, that actually they are pretty messy: [2017-08-08 10:29:22 +0000] [1] [INFO] Starting gunicorn 19.7.1 [2017-08-08 10:29:22 +0000] [1] [DEBUG] Arbiter booted [2017-08-08 10:29:22 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 [2017-08-08 10:29:22 +0000] [1] [INFO] Using worker: sync [2017-08-08 10:29:22 +0000] [7] [INFO] Booting worker with pid: 7 [2017-08-08 10:29:23 +0000] [1] [DEBUG] 1 worker [2017-08-08 13:29:26 +0300] [7] [INFO] [dashboard.views:9] Displaying menu Settings: TIME_ZONE = 'Europe/Moscow' USE_TZ = True Maybe you can provide some hints/information how to configure or debug it? For a moment I thought that this is a gunicorn's problem, but it uses Django settings soo I have no idea what's wrong :/ -
When using django shell it runs in python 2.7.11 instead of 3.6.2
When i run "py manage.py shell" in powershell it runs the shell as expected however it runs it in python 2.7.11 while i need it to run with 3.6.2 Is there any way to get it to run in python 3.6 instead of 2.7? -
link files between django projects in git
We have multiple projects on our team's account on gitlab.com. We want to use some files from one project in another but as links. The reason is that we want the updates to propagate. If we just copied the code once and the original file was updated, the updates will not be reflected in the file in the other project. So, is there a way to add a a link to a file in project B to a project A? So, I can use it as a package in my project and at the same time keep it updated. -
Django allauth saving custom user profile fields with signup form
I am a beginner in Django. I am using Django 1.10 with an allauth package to create a user registration. There are a couple of extra fields (phone_number and organization) which I have included in signup form apart from the first name, last name, email, password. Creating a new user (forms.py) from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Field from ajax_select.fields import AutoCompleteSelectField, AutoCompleteField from phonenumber_field.formfields import PhoneNumberField from . import models class SignUpForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +91)")) organisation = forms.CharField(max_length=50) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() user.profile.phone_number = self.cleaned_data['phone_number'] user.profile.organisation = self.cleaned_data['organisation'] user.profile.save() class UserProfileForm(forms.ModelForm): class Meta: model = models.UserProfile fields = ("company", "job_title", "website", "about_text", "location") first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) location = AutoCompleteSelectField("city", required=False) job_title = AutoCompleteField("job_title") company = AutoCompleteField("company") UserProfileForm works when the user is logged in and update the profile form(which contains job_title, company etc) In models.py I have from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from easy_thumbnails.fields import ThumbnailerImageField … -
how to check session time out in all page using Python
I need one help. I have some pages and all linked from a menu. I need to implement session time out for all page using Python I am explaining my code below. def loginsave(request): """This function helps to login the user """ if request.method == 'POST': password = request.POST.get('pass') uname = request.POST.get('uname') per = User.objects.all().filter( Q(password__icontains=password) & Q(uname__icontains=uname)).count() if per > 0: user = User.objects.filter( Q(password__icontains=password) & Q(uname__icontains=uname)) for use in user: uid = use.id user_name = use.uname request.session['id'] = uid request.session['sess'] = dict(dt=str(datetime.now()), value='session') return render(request, 'bookingservice/home.html', {'count': per, 'username': user_name}) else: return render(request, 'bookingservice/login.html', {}) This is my login function where I am setting the time. I have my menu page and given below. base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <header> <h1>Car clinic</h1> {% if count > 0 %} <b>Hi, {{ username }}</b> <a href="{% url 'home' %}">Home</a> <a href="{% url 'booking' %}">Add Booking</a> <a href="{% url 'personal' %}">Add Personal Info</a> <a href="{% url 'view_service' %}">View Booking service</a> <a href="{% url 'view_personal' %}">View Personal Info</a> <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} … -
How to redirect to a view from another view in Django using GET?
I am trying to make 2 different apps one that takes the URL and another one that receives it and finds the logo of a specific website. Every single entry needs to be saved in the database. The problem is that I receive just a blank page with the error: method not allowed (get) I tried working on it but I am fairly new to Django and I can't seem to find the solution. The URL view function takes to URL, for example, "http://exemple.com/some-text-here/" and transforms it into "http://exemple.com": class UrlExtractorView(View): def get(self, request): the_form = URLForm() context = { "title": "Enter website", "form": the_form } return render(request, "website.html", context) def post(self, request): url_form = URLForm(request.POST) if url_form.is_valid(): url = url_form.cleaned_data.get('url') cleaning_url = clean_url(url) website_working = check_website(cleaning_url) true_tld = tld_of_url(cleaning_url) tld = TLD.objects.filter(name=true_tld).first() if not tld: tld = TLD(name=true_tld) tld.save() obj = URL.objects.get_or_create(url=cleaning_url, tld_id=tld, status=website_working) return redirect('logo') The Logo finder function takes URL and assigns it to logo URL(l_url): class FindLogoView(View): def post(self, request): form = FindLogoForm(request.POST) template = None context = None if form.is_valid(): website = URL.objects.latest('created') url = website.objects.get('url') get_logo_url = get_logo(url) created, obj = FindLogo.objects.get_or_create(l_url=url, original_url=get_logo_url) obj.save() context = { "object": obj, "created": created, } if created: … -
Django rest_framework serialization issue
while giving the command python manage.py migrateor makemigrations this below error occurs . i have one db table in my models and i want them migrate through this command...here i mentioned last few lines of error messages in load_disk "Migration %s in app %s has no Migration class" % (migration_name, app_config.label) django.db.migrations.exceptions.BadMigrationError: Migration serializers in app snippets has no Migration class in models i am referring the table which is already there. -
Custom Filter in Django admin
I have a model as follows class Person: name = models.CharField() city = models.CharField() phone = models.CharField() I want to create a filter in the admin page, the filter should be based on phone, that is valid phone(having 10 digits) invalid phone Thanks -
Django REST Framework image upload
I have model Product: class Product(models.Model): ... image = models.ImageField( upload_to=lambda instance, filename: 'images/{0}/{1}'.format(instance.id, filename), max_length=254, blank=True, null=True ) ... Then I have serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( ... 'image', ... ) And then I have views: class ProductViewSet(BaseViewSet, viewsets.ModelViewSet): serializer_class = ProductSerializer() filter_class = ProductFilter How I can upload image with Postman? What is the best practices to upload image to model? Thank you. -
Django - 'ContactForm' object has no attribute 'get'
I get the follow error no matter what way I do achieve my forms. This happens when I go to the URL of my form. forms.py class ContactForm(forms.ModelForm): class Meta: model = ContactUs fields = ('name', 'email', 'phone', 'message') models.py class ContactUs(models.Model): name = models.CharField(max_length=50, blank=True) email = models.EmailField() phone = models.CharField(max_length=15, blank=True) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: verbose_name_plural = "Contact Us" views.py def contact(request): if request.method == "POST": form = ContactForm(request.POST or None) errors = None if form.is_valid(): ContactUs.objects.create( name = form.cleaned_data.get('name'), email = form.cleaned_data.get('email'), phone = form.cleaned_data.get('phone'), message = form.cleaned_data.get('message'), created_at = form.cleaned_data.get('created_at') ) return HttpResponseRedirect("/s/") if form.errors: errors = form.errors template_name = 'contact_us.html' context = {"form": form, "errors": errors} return render(request, template_name, context) urls.py url(r'^contacts/$', views.ContactForm, name='contact_form'), html <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-warning">Submit</button> </form> Thanks in advance! -
django rest permissions allow both IsAdmin and custom permission
I have a views.py as below, from webapi.permissions import IsOwner class MemberDetail(generics.RetrieveUpdateDestroyAPIView): queryset = members.objects.all() serializer_class = MemberSerializer permission_classes = (permissions.IsAdminUser,IsOwner) And the following is custom permission to check if the user is ower of object in webapi.permissions, class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user Now the issue is it is check if he is a admin user and gives permissions to update / delete, But if the owner is the user it should actually give permission to edit he data but in this case it is failing. On seeing the question "Django Rest Framework won't let me have more than one permission" I tried as below also still it did not work when I use Or, class MemberDetail(generics.RetrieveUpdateDestroyAPIView): queryset = members.objects.all() serializer_class = MemberSerializer permission_classes = (Or(permissions.IsAdminUser,IsOwner)) If I use Or it is failing with error during run time as "'Condition' object is not iterable" -
Django and apache2 (no virtualenv): ImportError: No module named 'django'
I'm trying to port over a small Django site from one server to another. On the new server, I have the following installed: Ubuntu 16.04.3 LTS Python 3.5.2 apache 2.4.18 mod_wsgi 4.5.17 (built from source with Python 3.5) django 1.11.4 (installed using pip3 **without** a virtualenv) At the bottom of my apache2.conf file, I added the following lines # Django settings LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so WSGIPythonPath /home/user/ProductionServer Where /home/user/ProductionServer is the root directory of my django site. In sites-enabled/000-default.conf, I have the following: <VirtualHost *:2799> ServerName myserver.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIScriptAlias / /home/user/ProductionServer/my_app/wsgi.py Alias /static /home/user/ProductionServer/static <Directory /home/user/ProductionServer/my_app> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/user/ProductionServer/static> Require all granted </Directory> </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet I can run the site fine using the manage.py runserver command. When I come to run it through apache, however, I got the following error message in the apache2.error file: [Tue Aug 08 10:53:39.291771 2017] [mpm_event:notice] [pid 1892:tid 139862763386752] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.5.17 Python/3.5 configured -- resuming normal operations [Tue Aug 08 10:53:39.291903 2017] [core:notice] [pid 1892:tid 139862763386752] AH00094: Command line: '/usr/sbin/apache2' [Tue Aug 08 10:53:49.966143 2017] [wsgi:error] [pid 1893:tid 139862665881344] [client 85.97.123.183:56389] mod_wsgi (pid=1893): … -
django: how to relate a multi valued field in a model to another model of same kind
I have two models that I am working with. First one is a education model in which one user can enter multiple educational qualifications instances: class Education(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) degree_name = models.CharField(max_length=150,null=True,blank=True) institute_name = models.CharField(max_length=150, null=True, blank=True) date_start = models.CharField(null=True,blank=True,max_length=25) date_end = models.CharField(null=True,blank=True,max_length=25) description = models.TextField(null=True,blank=True,max_length=1000) Second Model is the 'User info' model in which one user can have maximum one instance: class Userinfo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) user_info = models.ForeignKey(User_info,related_name='user_info',on_delete=models.CASCADE,null=True) education = models.ForeignKey(Education,related_name='edu',on_delete=models.CASCADE,null=True) profile_pic = models.FileField(null=True,blank=True) dob = models.CharField(max_length=25,null=True,blank=True) nationality = models.CharField(max_length=100, null=True, blank=True) headline = models.CharField(max_length=160, null=True,blank=True) summary = models.TextField(max_length=1000, null=True, blank=True) current_salary = models.FloatField(null=True,blank=True) japanese_level = models.CharField(max_length=50, null=True, blank=True) english_level = models.CharField(max_length=50, null=True, blank=True) career_level = models.CharField(max_length=50,null=True,blank=True) availability = models.CharField(max_length=50, null=True, blank=True) expected_salary = models.FloatField(null=True, blank=True) job_role = models.CharField(max_length=50,null=True) When I use any query to get any instance of 'User info' like: Userinfo.objects.filter(user=request.user).all() I am unable to get multiple education instance stored in my education models. Am I not suppose to relate the education field in User Info with foreignkey ? Thanks and sorry in advance. -
Djangi Gunicorn no module named error
My project directory structure looks like following: My wsgi file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = get_wsgi_application() and my manage.py file: import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise 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?" ) raise execute_from_command_line(sys.argv) in my settings .py I have: WSGI_APPLICATION = 'config.wsgi.application' I added my project path to python with following: export PYTHONPATH=/home/ec2-user/amm_inovision_backend:$PYTHONPATH and I am trying to run gunicorn command where my manage.py file is as: gunicorn amm_inovision_backend.config.wsgi:application But it throws me error no module named amm_inovision_backend.config.wsgi If I run instead gunicorn config.wsgi:application it throws no module named amm_inovision_backend.config.settings What am I doing wrong? Note: in the screenshot it is amm_ino_backend but actually it is amm_inovision_backend in the production -
Questions about the security of the django website
That I'll deploy a django project on the public network.And I have set the password error five times to lock each other's IP. But when someone use the X-Forwarded-For to make fake IP address,It will become useless.So,guys,do you have good methods? -
How to use count method to show how many records are in the db
I have a question with count() method. I have the class Kategorie in my models.py from django.db import models from django.utils import timezone class Kategorie(models.Model): glowna = models.CharField(max_length=150, verbose_name='Kategoria') class Meta: verbose_name='Kategoria' verbose_name_plural='Kategorie' def __str__(self): return self.glowna class Witryna(models.Model): nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony') adres_www = models.CharField(max_length=70, verbose_name='Adres www') slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url') email = models.CharField(max_length=100, verbose_name='Adres e-mail') text = models.TextField(max_length=3000, verbose_name='Opis strony') kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria') data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji') class Meta: verbose_name='Strona www' verbose_name_plural = 'Strony www' def publikacja(self): self.data_publikacji=timezone.now() self.save() def __str__(self): return self.nazwa And I made definition in views.py def widok_kategorii(request): kategorie = Kategorie.objects.all() wpisy_kat = Kategorie.objects.count() return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie, 'wpisy_kat': wpisy_kat}) the view in html file showing me the number of all Kategories but I want to have a result for example how many websites are in the for example category Business? I have to use count() with some arguments it filters? -
Adding validators to fields in Django models.py
I am using django.core.validators inside my models.py but I keep getting syntax error. The piece of code involved is the following: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class StepStart(models.Model): motor_type_choices = ( ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ) temp_start = models.IntegerField( default=30 validators=[MaxValueValidator(90), MinValueValidator(10)] ) level_start = models.IntegerField( default=30 validators=[MaxValueValidator(150), MinValueValidator(10)] ) The error is a syntax error on the line of default=30. I've checked on other posts here and the validation method I used seems okay. Can someone point out the error please? Thanks. -
How to use data retrieved a form in Django (for a calculator app)
I'm new to Django. Even after reading, watching, and following many tutorials and guides, things still aren't coming together for me and I need help. I'm making a very simple calculator app in preparation for a much more complicated calculator app that I will be refactoring/porting from a Python shell. The basic idea for the simply calculator is this: I have 4 pages on 1 app. They contain an add, subtract, multiply, and divide function respectively. I have a working side menu (using bootstrap and some copied code) to navigate between the pages. Each page has a form on it with two charfields and a submit button, and should return the result of the operation associated with the page. Right now I'm just focusing on the 'add' page since the others will just be a matter of copying. Currently, I think I have a working form for getting two inputs, but I have no idea how to then get those two inputs as variables I can add to get the result. Here's my code so far: views.py from __future__ import unicode_literals from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from .forms import AddForm @csrf_exempt def web_adder(request): … -
Django annotate function and F() objects
I need your help: I need to calculate sth in "annotate" part of query in django ORM: I have tried two approaches but non of them has not had the expected results Model class Observation(models.Model): residual = models.FloatField(null=False, verbose_name="Residual [mm]") agl = models.FloatField(null=False, verbose_name="Agl [deg]") b = models.FloatField(null=False, verbose_name="B [deg]") (1 approach) Using math library and making computation in annotate function on F objects import math as m query1 = Observation.objects.filter(**filterargs).exclude(**filterargsExclude) .annotate(slope_egl=RegrSlope('residual',m.degrees(m.acos(m.cos(m.radians(F('b')))*m.cos(m.radians(F('agl'))))))) This aprroach brings the Type Error a float is required (2 approach) Using extra select to make additional column and and trying to execute annotate function with alias of this column query2 = Observation.objects.filter(**filterargs).exclude(**filterargsExclude) .extra(select={'egl':"degrees(acos(cos(radians(b))*cos(radians(agl))))"}) .annotate(slope_egl=RegrSlope('residual','egl'))))) This aprroach brings the Field Error Cannot resolve keyword 'egl' into field I will be very grateful for your help :) -
TypeError in AppStats
Appstats throw TypeError exception and caused server crash in appstats/formatting.py. It seems to sort a dictionary with None as a key. Turn off appstats and then it works fine. Here is the call stack, File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 1107, in _memcache_get_tasklet rpc=rpc) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/memcache/__init__.py", line 616, in get_multi_async user_key) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/memcache/__init__.py", line 384, in _make_async_call rpc.make_call(method, request, response, get_result_hook, user_data) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 528, in make_call self.__service, method, request, response, self.__rpc) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 206, in Call function(service, call, request, response, rpc) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/appstats/recording.py", line 1441, in pre_call_hook recorder_proxy.record_rpc_request(service, call, request, response, rpc) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/appstats/recording.py", line 566, in record_rpc_request self.get_call_stack(trace) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/appstats/recording.py", line 879, in get_call_stack if not self.get_frame_summary(frame, trace): File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/appstats/recording.py", line 937, in get_frame_summary x.set_value(format_value(value)) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/appstats/recording.py", line 995, in format_value return formatting._format_value(val, config.MAX_REPR, config.MAX_DEPTH) File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/ext/appstats/formatting.py", line 265, in _format_value series = sorted(val) TypeError: can't compare datetime.date to NoneType Here is the context, GAE standard environment with Django. It crashes while several async calls. Is it a bug? -
Django 1.11 context processor error: TypeError: context must be a dict rather than RequestContext'
I cannot for the life of me figure out why I'm encountering a problem with Django 1.11 and RenderContext. I really need help here. Here is the code I've been playing with from the official documentation for 1.11: from django.http import HttpResponse from django.template import RequestContext, Template from django.template import loader def ip_address_processor(request): return {'ip_address': request.META['REMOTE_ADDR']} def view_2(request): template = loader.get_template('template2.html') ctx = RequestContext(request, { 'title': 'Your IP Address', }, [ip_address_processor]) return HttpResponse(template.render(ctx)) And my simple template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Test {{ title }}: {{ ip_address }} </body> </html> This ALWAYS results in the following error: Internal Server Error: /view2/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\null\PycharmProjects\project1\project1\views.py", line 48, in view_2 return template.render(c) File "C:\Python27\lib\site-packages\django\template\backends\django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\Python27\lib\site-packages\django\template\context.py", line 287, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than RequestContext. [07/Aug/2017 23:52:49] "GET /view2/ HTTP/1.1" 500 72701 Which is just odd to me … -
"digitalocean" droplet password changing broke the website
I have changed the password of the digitalocean droplet then after that the website is not working at all and the api's for the mobile application is not working either. The website and the apis aren't made by me but by different side,and they built using python-django. Please i need your help to recover everything as i believe it's a problem with the reset password process i have done. here is the website : http://educationwallets.com/ -
Python / Django Compare Specific Column in two Lists
Im re-asking this question as I failed to provide a real outline of what I want to do. Old Question I have a CSV list that I need to import daily and compare some columns to what I have stored in my Django Model. [order_code],[cost_price],[quantity](there are more details, not none that I need to compare). I only want to update the Django obj if the [cost_price], and/or [quantity] has changed. I can already do this by turning my csv in to a list and then working down that list and compare it against the obj, in the model. How ever this take far to much time when daily I want to check 120k records. I understand that there are some better way to do this, by filtering my results from the Models and dropping out the current items from that supplier in to a list, and then compare the two list in memory instead of calling the Model for every line. I guess at the end I want to create 3 lists, 1) Items needing updates(existing products that need [cost_price],[quantity] updated). 2) Items that need created (new products). 3) Items that did not exist in the updated csv, as I … -
Django rest IsAdminUser not applied
I have following in my views.py , from webapi.models import members from rest_framework import permissions from webapi.serializers import MemberSerializer from rest_framework import generics class MemberList(generics.ListAPIView): queryset = members.objects.all() serializer_class = MemberSerializer permission_class = (permissions.IsAuthenticated,) class MemberCreate(generics.CreateAPIView): queryset = members.objects.all() serializer_class = MemberSerializer permission_class = (permissions.IsAdminUser,) def perform_create(self, serializer): serializer.save(owner=self.request.user) In the above IsAuthenticated is working fine fine, but when i use "permissions.IsAdminUser" for MemberCreate class it is allowing not admin user also to create items. As per the question "Django rest_framework IsAdminUser not behaving" I even tried to add the following in settings.py but still override is not happening, REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } No matter If Add or don't add the REST_FRAMEWORK in settings.py IsAdminUser permissions is not working.