Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to merge query results
I have an ArrayField with choices and i'm trying to filter the choices: PAYMENT_CASH = '0' PAYMENT_CARD = '1' PAYMENT_BANK = '2' PAYMENT_ONLINE = '3' PAYMENT = ( (PAYMENT_CASH, _('Cash')), (PAYMENT_CARD, _('Card')), (PAYMENT_BANK, _('Bank')), (PAYMENT_ONLINE, _('Online')), ) options = ArrayField(models.CharField(max_length=1, choices=PAYMENT, default='0'), size=4) When i use Location.objects.filter(city__id='683506').values_list('options', flat=True) it returns me <QuerySet [['0'], ['0', '1', '2', '3'], ['0', '1', '2'], ['0', '1'], ['0', '1', '2', '3']]> I wish to get all the options that are used. How can i merge the query or make them into a list and merge them? This is what i wish to get ['0', '1', '2', '3'] -
StreamBlock instance throws exception "AttributeError: 'str' object has no attribute 'block'"
I am using the example project provided by Wagtail. The StreamField gets as argument A DemoStreamBlock class DemoStreamBlock(StreamBlock): h2 = CharBlock(icon="title", classname="title") h3 = CharBlock(icon="title", classname="title") h4 = CharBlock(icon="title", classname="title") intro = RichTextBlock(icon="pilcrow") paragraph = RichTextBlock(icon="pilcrow") aligned_image = ImageBlock(label="Aligned image", icon="image") pullquote = PullQuoteBlock() aligned_html = AlignedHTMLBlock(icon="code", label='Raw HTML') document = DocumentChooserBlock(icon="doc-full-inverse") Then in the Page class I'm instantiating a variable e.g. class BlogPost(Page): blog_text = StreamField(DemoStreamBlock()) content_panels = Page.content_panels + [ StreamFieldPanel('blog_text') ] The first time I run the migrations Django doesn't want me to put a default value because of the non-nullable field that I am adding. However, if I want to add another StreamField field I am prompted to add a default value: class BlogPost(Page): blog_text = StreamField(DemoStreamBlock()) blog_short_text = StreamField(DemoStreamBlock()) content_panels = Page.content_panels + [ StreamFieldPanel('blog_text'), StreamFieldPanel('blog_short_text'), ] You are trying to add a non-nullable field 'blog_short_text' to blogpost without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a > null value for this column) 2) Quit, and let me add a default in models.py I am choosing 1 and then enter … -
Ubuntu service Upstart or SystemD, Django development server as Service
I've been working around with Python & Django Framework for a while with Ubuntu 16.01. Since I used Django with Q system (Celery) and some others Enhancement Apps. When I try to run all the apps each time, I need to run development server "{python manage.py runserver}", then running Celery Worker "{celery -A filename worker -l info}". Each time I working, it takes me minutes to enter the directory and start it up. I surf around and come up with the idea of setup it as service. Example, service name: "pyd". I just need to run "{sudo pyd start}" -> then Django Development Server and Celery will start, and if I run "{sudo pyd stop}" -> then Django & Celery will stop. I try to search around, and things start to confuse me between "Upstart" and "Systemd". Could any one suggest, me how to make both Django and Celery as Service run in Ubuntu ? between "Upstart" & "Systemd" which one is better ?? Source code to indicate sample is appreciated. Thank -
Nested serializer with custom queryset
I am trying to display the custom query values to the nested serializer . But its not displaying serializer.py class TueRangeSerializer(serializers.ModelSerializer): class Meta: model = SubnetRange fields = ('type', 'id', 'begin', 'end') class TueSubnetSerializer(serializers.ModelSerializer): range = TueRangeSerializer(required=False,read_only=False,many=True) class Meta: model = Subnet fields = ('name','base_address','bits','range') def create(self,validated_data): print(validated_data) And in the api file api.py class SubnetList(APIView): def get(self, request, format=None): query = 'SELECT ss.id ,ssr.id, ssp.id , ' \ ' ss.name as name, ss.bits as bits, ssr.begin as begin FROM subnets_subnet ss' \ ' inner join subnets_subnetphysical ssp on ssp.subnet_id = ss.id' \ ' inner join subnets_subnetrange ssr on ssr.subnet_physical_id = ssp.id' subnets = Subnet.objects.raw(query) serializer = TueSubnetSerializer(subnets,many=True) return Response(serializer.data) SQL query is correct. But on the response of the serializer its displaying only the data from subnets table Result [ { "name": "First subnet", "base_address": "192.100.30.0", "bits": 24 }, { "name": "Second subnet", "base_address": "192.100.30.0", "bits": 24 } ] Its not displaying the range output -
unable to access django website from URL but accessible from IP address
I have installed django on Amazon lightsail, I can access my website through the static server IP address. My domain is hosted on Godaddy. I change the Name Server in GoDaddy. But still when I try to access my website through domain name it shows me Nignx welcome page. Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. In my django settings.py I have given only the IP address ALLOWED_HOSTS = ['YOUR_AMAZON_LIGHTSAIL_IP'] And in Nginx file, I also added only the IP address. server { listen 80; server_name YOUR_AMAZON_LIGHTSAIL_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/django_project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/django_project/django_project.sock; } } I am using Gunicorn and Nginx on my hosting server. -
Django deadline alert
I am building a management application for a company. One of the things the application can do is start new projects. The model here for is: ` class Project(models.Model): employees = models.ManyToManyField(settings.AUTH_USER_MODEL) division = models.ForeignKey(Division) client = models.ForeignKey(Company) description = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) deadline = models.DateField(blank=True) active = models.BooleanField(default=True) ` As you can see in the model a employee can set a deadline for their project. I need to able to send the user notifications if they are close to their deadline. For example, if the deadline is in two days, the user will get a notification like "Your deadline for projectname is over two days". So basically what I need is a deadline timer. What is the logic for this? I don't really know where to start with this? -
NameError: name 'base' is not defined(haystack search)
I wanted to include full text search in my django application. I am using whoosh-haystack for this.When I include whoosh and haystack in my installed apps,and execute the command ./manage.py, I am getting an import error. Can anyone sort this out. settings.py INSTALLED_APPS = { 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', 'whoosh', 'haystack', } when I make migration in my model the error which I got is: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python \Python36\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Samad Talukder\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\Samad Talukder\Desktop\django-env\search\search\settings.py", line 80, in <module> 'PATH': os.path.join(base(), 'whoosh_index') NameError: name 'base' is not defined my haystack connection: HAYSTACK_CONNECTIONS = { … -
How to record the operation logs that influenced by update methods with django-auditlog?
Recently, i have been dedicated to accomplishing the log logging function in the background. However, there exists a problem that i failed to figure out. Concretely, when it comes to record soft delete, as we all kown, the moment the field 'is_delete' transforms from False to True, the interface that including save methods can record relevant change, but this situation is not holding true for update methods. What i want to konw is that how to solve this problem without creating some corrlative tables. In terms of code, for example, if the current operation is 'save', model.is_delete=True,model.save() that is to say, After model.is_delete equals to constant 'True' and the save method of model is invoked, a new record will be inserted into the table called auditlog_logentry. Nevertheless, if update methods are conducted,i.e., model.update(is_delete=True), no records will be recorded in auditlog_logentry. I will be very appreciated if you can give me some hints or solutions. Looking forward to making progress together with you. Thanks a lot. -
Connection errors due to webpage navigation
I am having some trouble with connection errors in my Django app when a user navigates to different page before AJAX call is finished. So, when the client-side sends several AJAX calls for save/load/retrieve data etc., and when a user navigates to a different page - say when an AJAX call was just made from the client side to save the content, the content is saved and the functionally everything is fine, but I keep getting this error: Exception happened during processing of request from ('127.0.0.1', 50646) Traceback (most recent call last): File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\socket.py", line 594, in write return self._sock.send(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_error super(ServerHandler, self).handle_error() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "D:\Applications\WinPython-64bit-3.5.3.1Qt5\python-3.5.3.amd64\lib\wsgiref\handlers.py", … -
Trying to add a django app to heroku
So,i've synced a django app from github to heroku,and i was trying to deploy from their web interface,but in the log it says Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed I understand that you can use heroku CLI to disable collectstatic,but i couldn't find a way to sync my github/heroku app with heroku CLI,any inputs would be helpful -
Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'
I am using windows 10 command line for a django project using python34 however, I am facing difficulties with SQL. I have already installed mysqlclient using pip install mysqlclient==1.3.5 and located the file to make sure I was not delusional. I then ran python manage.py migrate to migrate the tables to the SQL database (I am using phpmyadmin). However when the command returned with... File "C:\Users\user\env\lib\site-packages\django\db\backends\mysql\base.py", line 30, in <module> 'Did you install mysqlclient or MySQL-python?' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? I am aware that questions like these already exist, but not one solution seems to have made any impact on attempts. Thank you in advance. -
Trying to override an Oscar Model
I want to override an oscar partner model to OnetoOne but I'm receiving a conflict error. Conflicting "partner_users" models in application "partner": <class 'oscar.apps.partner.models.Partner_users'> and <class 'myapp.partner.models.Partner_users'>. I overwrite whatever I forked, why does it still take oscar's model? I've also included in settings.py under INSTALLED_APP=+ get_core_apps(['myapp.partner']) Not sure what else I missed? myapp/myoscar/partner/models.py from django.contrib.auth import get_user_model from django.db import models from oscar.apps.partner.abstract_models import AbstractPartner User = get_user_model() class Partner(AbstractPartner): user = models.OneToOneField(User, related_name='partner_user') from oscar.apps.partner.models import * -
CSRF verification failed. Request aborted - Shopping cart configuration
I'm trying to enable Payment module for courses and when I'm clicking checkout, I'm getting "CSRF verification failed. Request aborted." . I've tried adding my domain to "Home › Cors_Csrf › X domain proxy configurations › XDomainProxyConfiguration()" in Django admin panel. Even modified lms.env.json to add "ENABLE_CROSS_DOMAIN_CSRF_COOKIE": true, " ... still facing the issue. Can anyone please help. Google group message link : https://groups.google.com/d/msg/edx-code/4VnLJG-raPE/llF1PDG9AQAJ -
How to create a download button for image/filefield in Django
Download option is Working fine. But whenever i am hitting the file download link download option appears but after i download the file it's no longer the same file that i have uploaded. rather it becomes 9 bytes small file and can't be opened. views.py def download_file(request, path): response = HttpResponse('image/png') response['Content- Type']='image/png' response['Content-Disposition'] = "attachment; filename="+path response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path)) return response urls.py url(r'^get\/(?P<path>.*)$', download_file), index.html <a href="get/{{file_name}}">Download File</a> -
matplotlib legend at the bottom of the plot
Im trying to replicate a chart the was done in AmCharts but so far Im confused in the way to make the legend be outside and at the bottom of the plot right now im using this django view to render the plot def my_view(request) import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas colors = ["#FF9800", "#00E676", "#03A9F4", "#1A237E", "#AD1457", "#F44336", "#1DE9B6", "#01579B", "#CFD8DC", "#90A4AE", "#263238", "#B71C1C", "#FFEB3B"] data=('serv1','Aplicaiones','serv3','serv4','servi5','serv1','serv2','serv3','serv4','servi5',) datos=[99.3,99,23,100,99.3,99,23,100,99.3,99] figure=plt.Figure() pos=np.arange(len(datos)) ax = figure.add_subplot(111) b=ax.bar(pos, datos,color=colors) ax.legend(b,data,loc='upper center', bbox_to_anchor=(0,-.05, 1,0), ncol=5,mode="expand") ax.axis('off') # response = HttpResponse(content_type='image/png') figure.bbox_inches='tight' canvas = FigureCanvas(figure) canvas.print_png(response) return response the parameter bbox_to_anchor looks like the way to go, but chart has a limit and the label ends too close to the bars, my goal is to put the label (1 for each bar) leave space for axis description what I want https://d26dzxoao6i3hh.cloudfront.net/items/2U113d3m0O3Z0o053L3F/Captura%20de%20pantalla%202017-10-23%20a%20la(s)%2023.45.00.png?v=16e23ee7 right now this is what I got https://d26dzxoao6i3hh.cloudfront.net/items/0l0v2P2N3h1M15022V43/Captura%20de%20pantalla%202017-10-23%20a%20la(s)%2023.47.05.png?v=a36b97c9 -
Distance query for arbitary points with GeoDjango not working as expected - distance calculation seem off
I'm building a world-map and want users to be able to look-up locations and have them be sorted by distance from anywhere in the world. I'm using GeoDjango to calculate distances, however the distances returned seemed wrong so I checked them against geopy's calculations. The distances differ significantly to the point that if the results are sorted by the DB vs geopy values they would not be in the same order. I'm assuming the geopy values are correct so I'm wondering, is there something wrong with the way I implemented GeoDjango? Is it working as it should? Does this have something to do with trying to calculate distances for the entire world and not just a specific area which could have a srid? views.py pnt = GEOSGeometry('POINT({} {})'.format(latitude, longitude), srid=4326) qs = Place.filter(point__distance_lte=(pnt, D(km=radius*2))).annotate(distance=Distance('point', pnt)).order_by('distance') settings.py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'USER': '', 'NAME': 'places', 'HOST': '127.0.0.1', 'PORT': '5432', } } models.py: from django.contrib.gis.db import models from geopy.distance import vincenty class Place(models.Model): latitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True) longitude = models.DecimalField(max_digits=10, decimal_places=6, null=True, blank=True) point = models.PointField(null=True, geography=True) def distance_from_target(self, target_lat, target_lon): if not target_lat or not target_lon: return None instance_point = (self.latitude, self.longitude) target_point = (target_lat, target_lon) … -
Implement a 'trending' algorithm to sort a queryset of Posts
I have a Post model for user posts, and also a PostScore model to track the score of that Post in order to sort the queryset by trending, similar to reddit's 'hot': class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) How would I go about sorting these posts? Would I make a custom method under in PostScore: @property def trending(self): score = self.upvotes - self.downvotes time = self.post.date print('TIME:', time) return score or would I sort it in my views?: posts = Post.objects.all().filter(entered_category=category).annotate( score_diff=F('score__upvotes') - F('score__downvotes'))\ .order_by('score_diff') -
Django 1.11 CreateView pass URL parameters
I am using Django 1.11 and I'm struggling to understand how I can pass URL parameters to a ModelForm using CreateView Class. I have 4 parameters in the URL (start_date, end_date, start_time, end_time) that i'm trying to pass to their relevant fields in the form. I'd really appreciate if anyone can point me in the right direction to figuring out how to solve this! The URL is created with the following function in my html file: window.location.assign("/calendar/create?start_date="+start.format("YYYY-MM-DD")+"&end_date="+end.format("YYYY-MM-DD")+"start_time="+start.format("h:mm A")+"&end_time="+end.format("h:mm A")); This opens from urls.py: url(r'^calendar/create',views.CalendarCreate.as_view(),name='calendar_create'), from views.py: class CalendarCreate(CreateView): model = Event form_class = EventForm from forms.py: class EventForm(ModelForm): class Meta: model = Event So far so good, my event_form.html opens with the form: form and an example URL generated is: http://127.0.0.1:8000/calendar/create?start_date=2017-10-25&end_date=2017-10-25start_time=4:00%20PM&end_time=5:00%20PM This is where I am stuck. From spending a number of days here in stackoverflow, googling, and trying numerous things I believe the solution involves get_form_kwargs or get_context_data or form_valid in views.py but it is possible I have just confused myself trying to work this out. Any help to get me on the right track will be greatly appreciated! -
Why isn't my javascript calculator working with the base.html?
So awhile ago I made a javascript calculator and now I'm re-using it in another project. The problem is, it doesn't even show up on the page anymore. This is the code for the calc.html file. {% extends 'base.html' %} {% block body %} <div class="text-center"> <h1>Calculator</h1> </div> <div id="JSCalc"> <form name="calculator"> <input type="text" name="answer"/> <br /> <input type="button" value=" 7" onclick="calculator.answer.value += '7'"/> <input type="button" value=" 8" onclick="calculator.answer.value += '8'"/> <input type="button" value=" 9" onclick="calculator.answer.value += '9'"/> <input type="button" value=" *" onclick="calculator.answer.value += '*'"/> <br /> <input type="button" value=" 4" onclick="calculator.answer.value += '4'"/> <input type="button" value=" 5" onclick="calculator.answer.value += '5'"/> <input type="button" value=" 6" onclick="calculator.answer.value += '6'"/> <input type="button" value=" -" onclick="calculator.answer.value += '-'"/> <br /> <input type="button" value=" 1" onclick="calculator.answer.value += '1'"/> <input type="button" value=" 2" onclick="calculator.answer.value += '2'"/> <input type="button" value=" 3" onclick="calculator.answer.value += '3'"/> <input type="button" value=" +" onclick="calculator.answer.value += '+'"/> <br /> <input type="button" value=" 0" onclick="calculator.answer.value += '0'"/> <input type="button" value=" C" onclick="calculator.answer.value = ''"/> <input type="button" value=" =" onclick="calculator.answer.value = eval(calculator.answer.value)"/> <input type="button" value=" /" onclick="calculator.answer.value += '/'"/> <br /> </form> </div> {% endblock %} And this is the base.html file it's extending from. Note that this wasn't written by me, I'm just … -
What is the proper way to login via email for custom user model?
I don't need to let users login using usernames, only email. So I have custom user model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) accepted = models.BooleanField('status', default=False) is_staff = models.BooleanField( 'staff status', default=False, help_text='Designates whether the user can log into this site.', ) is_active = models.BooleanField( 'active', default=True, help_text='Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email Custom manager: class MyUserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) And I am using auth_views.login method to render login template. In template I have two input fields named email and password. But when I submit form I got a validation error that says the username field is required. I figured … -
Django SelectDateWidget inline select (bootstrap?)
I'm using SelectDateWidget in a form in django for a birthday field. It display three selects for day, month and year. The problem is they don't display inline, but stacked vertically. I'm using a tag for each field, in this case {{ form.birthdate }} How do I display them inline? Thanks in advace. -
How to deploy django in a2hosting
I am trying to set up my django application in a2hosting, I was doing some research and It seems that i need to use wsgi but I am not able to do it. My questions are the following: Where do i need to put all my files, should be stay in the www folder? When I run the server "manage.py runserver" in order to access to the site do i need to use www.domain.com:port? Can someone give any idea to deploy, i am loosing my mind trying to deploy my site. Thanks in advance. -
Summary of data for different users using Serializer in Django
In our app, we have a back-end that runs on the Django Rest Framework. Up to this point what we have been doing is gather data for specific users, which is easy to implement using serializers. @api_view(['GET']) def user_stats(request, format=None): if request.method == 'GET': serializer = StatsSerializer(request.user, context={'request': request}) return Response(serializer.data) In this case, the StatsSerializer is a custom serializers which returns JSON like this: { "id": 2, "first_name": "John", "last_name": "Legend", "profile_photo": "http://localhost:8000/media/profile_photos/john_legend.jpg", "notification_count": 3 } The serializer contains a SerializerMethodField for handling notification_count: def get_notifications(self, obj): return obj.notifications.filter(status=Notification.UNREAD).count() The serializer's model is a simple User Model in this case (request.user). And this goes on for all our end-points (although with different models). However, for a different endpoint we would like to give an overview of data for a list of users and receive a response like this. { "notification_count" : 48, "todo_count" : 72 ... and some more } I think I can get this data in the View with filter and aggregate. However, that is just for one user and thus can I use a User model as the model for the serializer. I would like to do this for a list of users. notificationCount = Notification.objects.filter(user=request.user). … -
access /admin functionality and features for some user groups
My english is not perfect thus the title is confusing. I don't know how to really put what i want to say. Anyway, I have a django 1.11 application that is running well. Wrote admin.py for some apps and a bunch of admin forms overridden. But client said he wants a different way of doing things (instead of admin carrying out the task, everyone registered on the app can). I already have a dashboard for those users and he wants the admin forms to be in that dashboard as opposed to the /admin default dashboard. I failed to find such a thing in the documentation, I think. But basically, I want some forms to be avalibale, as they are, in the client dashboard? Is that possible? -
django-ouath-toolkit with social-auth
I'm trying to setup social-auth (python-social-auth) to talk to another Django project with django-oauth-toolkit. I want Django project A to login using OAuth2 from Django project B. Django project A uses social-auth and project B uses django-oauth-toolkit as the OAuth2 provider. Project A can successfully login to other OAuth2 providers such as Google, but I get the following error when trying to login using my custom made backend: AuthStateMissing at /sso/complete/custom-backend/ Session value state missing. This is how the custom backend has been implemented in Project A: class CustomBackend(BaseOAuth2): name = 'custom-backend' EXTRA_DATA = [ ('profile', 'org') ] def authorization_url(self): return "%s/oauth2/authorize" % self.setting("URL") def access_token_url(self): return "%s/oauth2/token" % self.setting("URL") def user_data(self, access_token, *args, **kwargs): resp = requests.get("%s/me/" % self.setting("URL"), headers={ 'Authorization': "Bearer %s" % access_token }) if resp.status_code != 200: raise Exception("Error while getting user details from auth source.") data = resp.json() return { 'username': data['email'], 'first_name': data['first_name'], 'last_name': data['last_name'], 'user_id': data['id'], 'email': data['email'] } There is a setting called SOCIAL_AUTH_CUSTOM_BACKEND_URL which is equal to the base URL of project B (http://localhost:8001 for testing). The URL when Project B redirects to Project A (when the error is raised) is: http://localhost:8000/sso/complete/custom-backend/?redirect_state=6kg4S1eitCMqTTzFGrm9uerG37UNkUPl&code=e64by72AkD2unMVVsGZCz0V2byuUyu&state=6kg4S1eitCMqTTzFGrm9uerG37UNkUPl I thought the issue might be because django-oauth-toolkit doesn't …