Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Users are not being authenticated after login
This is my first time working with Django and I'm trying to create a simple login page. I would like the login page to be located at the base URL (index) of the site and then redirect to "assignments/" with "assignments/" and all other pages on the site only being accessible if the user is logged in. When I try to view if the user is authenticated (using "request.user.is_authenticated"), the view handles the user as if he/she is not logged in. views.py from django.contrib.auth import login as dj_login def login(request): return render(request, 'mainapp/login.html') def assignments(request): if request.user.is_authenticated: assignment_list = Assignment.objects.all() context_dict = {'assignments': assignment_list} return render(request, 'mainapp/assignments.html', context_dict) else: return HttpResponse("You must login first") def show_assignment(request, assignment_name_slug): try: context_dict = {} assignment = Assignment.objects.get(slug=assignment_name_slug) context_dict['assignment'] = assignment except Category.DoesNotExist: context_dict['assignment'] = None return render(request, 'mainapp/projectpage.html', context_dict) def user_login(request): information. if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: dj_login(request, user) return HttpResponseRedirect(reverse('assignments')) else: return HttpResponse("Your account is disabled.") else: print("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: return HttpResponse("You must login first") application urls.py urlpatterns = [ url(r'^$', views.assignments, name='assignments'), url(r'^(?P<assignment_name_slug>[\w\-]+)/$', views.show_assignment, name='show_assignment') ] project urls.py urlpatterns … -
NoReverseMatch django Reverse for 'profilepk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P<pk>\\d+)/$']
NoReverseMatch at /home/ this is error m not able to solve this pop on screen account/profile/(?P\d+)/$' is there any error in below code viwes.py,urls.py,models.py Error during template rendering In template C:\Users\shubham\Desktop\app1\account\templates\basic.html, error at line 24 Reverse for 'profilepk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/profile/(?P\d+)/$'] urls.py from django.conf.urls import url from home import views app_name = 'home' urlpatterns = [ url(r'^$', views.home.as_view(), name='home'), url(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.Create, name='create') ] views.py from django.contrib.auth.models import User from django.shortcuts import render, HttpResponse, redirect from django.views.generic import TemplateView from home.forms import RegiForm from home.models import Datastrore, Friendlist class home(TemplateView): template_name = 'home/home.html' def get(self, request): forms = RegiForm() datastore = Datastrore.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friendlist.objects.get(current_user=request.user) friends = friend.user.all() args = {'form': forms, 'post': datastore, 'user': users,'friend': friends} return render(request, self.template_name, args) def post(self, request): froms = RegiForm(request.POST) if froms.is_valid(): post = froms.save(commit=False) post.user = request.user froms.save() text = froms.cleaned_data['post'] args = {'form': froms, 'text': text} return render(request, self.template_name, args) def Create(request, operation, pk): friends = User.objects.get(pk=pk) if operation == 'add': Friendlist.Create_list(request.user, friends) elif operation == 'remove': Friendlist.Remove_list(request.user, friends) return redirect('home:home') models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Datastrore(models.Model): post = models.CharField(max_length=100) user … -
Error Incorrect type. Expected URL string, received dict
I am using volley to post data to django server.This is the format I need to Post the data { "no_people": 9, "entry_time": "2018-01-02T15:00:00Z", "predicated_time": "2018-01-02T16:00:00Z", "status": "W", "foodie": "http://localhost:9500/api/users/99/" } The foodie field consist of URL. When I am sending post request I am getting error as POST /api/restqueue/ - 400 {'content-type': ('Content-Type', 'application/json'), 'allow': ('Allow', 'GET, POST, HEAD, OPTIONS'), 'vary': ('Vary', 'Accept')} b'{"foodie":["Incorrect type. Expected URL string, received dict."]}' [23/Jan/2018 05:15:41] "POST /api/restqueue/ HTTP/1.1" 400 66 How to resolve this and send Post Request? -
how do I get that entire object instead of the foreign key. please see below code and output so you can understand
my question is how do I get that entire object instead of the foreign key. please see below code and output so you can understand my question These are my models.py class Professor(models.Model): professor_id = models.AutoField(primary_key=True, auto_created=True) name = models.CharField(max_length=256) email = models.CharField(max_length=256) mobile = models.CharField(max_length=256) created_at = models.DateTimeField() updated_at = models.DateTimeField() class Preference(models.Model): preference_id = models.AutoField(primary_key=True, auto_created=True) professor = models.ForeignKey('Professor', on_delete=models.CASCADE) rank = models.IntegerField() created_at = models.DateTimeField() updated_at = models.DateTimeField() These are my views.py class CreateListMixin: def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) class PreferenceViewSet(CreateListMixin, viewsets.ModelViewSet): queryset = Preference.objects.all() serializer_class = PreferenceSerializer This is my serializers.py class PreferenceSerializer(serializers.ModelSerializer): class Meta: model = Preference I'm getting the output as [ { "preference_id": 1, "rank": 1, "professor": Eshwar "created_at": "2018-01-13T00:00:00Z", "updated_at": "2018-01-13T00:00:00Z" } ] what to do if I have to get professor details as object: [ { "preference_id": 1, "rank": 1, "professor": { professor_id = 1 name = Eshwar email = .... mobile = .... created_at = ... updated_at = .... } "created_at": "2018-01-13T00:00:00Z", "updated_at": "2018-01-13T00:00:00Z" } ] my question is how do I get that entire object instead of foreign key Any help is appreciated. -
Obtain the display value of a choice Field from a function within the own model
I have a method inside a model class, and I want to get the display value of a choice field in such model, but I get a weird value. This is the code: class Actor(models.Model): PERSON = '0' ROLE = '1' AUTO = '2' TYPE_CHOICES = ( (PERSON, 'Person'), (ROLE, 'Role'), (AUTO, 'Auto'), ) alias = models.CharField(max_length=10, default='', unique=True) name = models.CharField(max_length=255, default='') email = models.EmailField(null=True, blank=True) actor_type = models.CharField(max_length=1, choices=TYPE_CHOICES, default=PERSON) long_description = models.TextField(max_length=long_description_max_length, default='', null=True, blank=True) def get_list_fields(self): list_fields = { 'id' : self.id, 'name' : self.alias, 'description' : self.name, 'extra_fields' : "[{}][{}]".format( self.email, getattr(self, 'get_actor_type_display') ) } return list_fields And this is the result i get: {'id': 1, 'name': 'hugo', 'description': 'Hugo Luis Villalobos Canto', 'extra_fields': '[hugo@utopia-software.net][functools.partial(>, field=)]' } I don't know what that functools.partial(>, field=)stands for, and I don't know how to get the result I want: the display value of the current content of the field. Thanks for your help. -
I cannot get my PIP 9.0.1 to work properly
I'm working with a Hostgator Shared package to install and run my Django projects, I followed all the steps from here http://support.hostgator.com/articles/django-with-fastcgi#shared-reseller (section: Setup Django Using Virtualenv) I get stuck in step 3 (Install Django): ~/mydjango/bin/pip install django I get this output: Exception: Traceback (most recent call last): File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/commands/install.py", line 272, in run with self._build_session(options) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 1050, in <module> _distro = LinuxDistribution() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 594, in __init__ if include_lsb else {} File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/_vendor/distro.py", line 933, in _get_lsb_release_info raise subprocess.CalledProcessError(code, cmd, stdout) CalledProcessError: Command 'lsb_release -a' returned non-zero exit status 3 Traceback (most recent call last): File "/home2/belldentjc/mydjango/bin/pip", line 11, in <module> sys.exit(main()) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home2/belldentjc/mydjango/lib/python2.7/site- packages/pip/download.py", line 93, in user_agent from pip._vendor import … -
How create recursive loop for parsing the json?
I use Nestable2 plugin in my Django project to create tree. When user change the order of tree nodes, plugin return me JSON which I send by Ajax to server. Nestable2 return me JSON: [{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5,"foo":"bar"}]}] In Django view I take this JSON but I want to parse it to list of ids. For example: [1, 2, 3, 4, 5, ...] It seems to me I need to create recursive loop for this task, so I am little bit confused. Can someone say the best way to make this task? views.py: class NodeOrderView(CsrfExemptMixin, JsonRequestResponseMixin, FormView): def post(self, request, *args, **kwargs): print(self.request_json) # JSON return self.render_json_response({'saved': 'ok'}) -
AJAX Success Response Button Not Opening Modal
I'm creating an activity feed of communications, notes, and tasks. Each one has buttons for editing and deleting, which opens up a modal for either changing information or confirming the delete. The modals work fine. Once I load the data after a successful AJAX response, the buttons click (and the call is successfully made to the view) but the modal does not open. I've tried making the buttons "live" and appending the button, but the modal still won't open. This is the origin AJAX -- $(document).ready(function(){ $('.task_completed').click(function() { var id = $(this).attr('id'); var type_id = $('#contactID').attr('value'); $.ajax({ method: "POST", url: "{% url 'communications:task_completed_activity' %}", data: {'id': id, 'type': 'Contact', 'type_id': type_id}, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, success: function(response) { $('.infinite-container').html(response); } }); }); }); This is an example of the modal that's failing to open -- $(document).ready(function(){ $(".task-delete").click(function(){ $("#taskDelete").modal(); }); }); This is the AJAX for the button -- $(document).ready(function(){ $('.task-delete').click(function() { var id = $(this).attr('id'); $.ajax({ method: "POST", url: "{% url 'communications:delete_confirm' %}", data: {'id': id, 'type': 'task'}, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, success: function(response) { document.getElementById("task-object").innerHTML = response.object; document.getElementById("task-description").innerHTML = response.description; $('#task-id').val(response.id); } }); }); }); Let me know if … -
django models retrieving data
i m new to django.this is my model class . how can i retrieve data from depertment and doctor in my template plz write urls and view. from django.db import models class Hospital(models.Model): name=models.CharField(max_length=300) location=models.CharField(max_length=1000) def __str__(self): return self.name class Department(models.Model): hospital=models.ForeignKey(Hospital,on_delete=models.CASCADE) name=models.CharField(max_length=300) def __str__(self): return self.name class Doctor(models.Model): department=models.ForeignKey(Department,on_delete=models.CASCADE) name=models.CharField(max_length=300) designation=models.CharField(max_length=300) qualification=models.CharField(max_length=500) image=models.ImageField(default='default.png',blank=True) address=models.CharField(max_length=550) def __str__(self): return self.name -
How to filter a filed when it is Null or null character string?
How to filter a filed when it is Null or null character string? I can only to check when it is null: DataDictionary.objects.filter(parentlevel__isnull=True) How about Null or null character string? -
Validating a signed cookie set by Django in the browser
Django sets a signed cookie in the client's browser, and I have the following settings for managing cookie sessions: SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_AGE = 86400 SESSION_SAVE_EVERY_REQUEST = False When I set the cookie value in the request headers and use this code to validate the cookie, I get this error message: raise BadSignature('Signature "%s" does not match' % sig) BadSignature: Signature "REDACTED"" does not match This is how I validate the signed cookie from the request payload (taken from the docs here https://docs.djangoproject.com/en/1.11/topics/signing/#using-the-low-level-api): cookie = '"blahhh:1redacted:redactedk"' from django.core.signing import Signer signer = Signer() signer.unsign(cookie) I even stripped out the " at the beginning and end of the cookie value, and that didn't work either. I also included the cookie key like this: session_id="blahhh:1redacted:redactedk". Is my understanding of how signed cookies work wrong? Am I using the API wrong? What is going on here? -
python merge two query sets and addition of matching records
I have a need to merge two querysets together with simalar data. Set 1 (stats) has a list of teams, total points for that team and the division the team is in. Set 2 (spares) has a list of teams that have had a member spare for them which includes the teams and points (no division for this set). What I would like to do is merge the querysets into one and when the teams match, just add the spares points to the team total, keeping the team name and division. The code i am using below will sort of do what i am looking for except it does not include the teams that never had a spare on it. Consider the following data. Stats List Team 1 : 8 Points : Division A Team 2 : 3 Points : Division B Team 3 : 7 Points : Division A Team 4 : 5 Points : Division B Team 5 : 4 Points : Division A Spares List Team 1 : 3 points Team 3 : 6 Points So what I want to do is merge these two lists where the teams match but total their points. In this case … -
Django field validator not working at all
So im trying at add a simple validator that checks against a postcode and returns a validation error if the user inputs non alphanumberics. But after trying i cant seem to get even the most basic validation message to show up. Here is my form i used the example field validation just to try get it to show up but it doesn't class CartAddShippingDetailsForm(forms.Form): first_name = forms.CharField(max_length=100) last_Name = forms.CharField(max_length=100) email = forms.EmailField() address1 = forms.CharField(max_length=100) town = forms.CharField(max_length=100) postcode = forms.CharField() country = LazyTypedChoiceField(choices=countries) additional_note = forms.CharField(max_length=100, required=False) def clean_postcode(self): data = self.cleaned_data['postcode'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!") else: return postcode This my views.py def shipping_details(request): cart = Cart(request) shipping_form = CartAddShippingDetailsForm() if request.method == 'POST': shipping_form = CartAddShippingDetailsForm(request.POST) if shipping_form.is_valid(): return redirect(reverse('test_order')) else: return render(request, 'shippingdetails.html', {'cart': cart, 'shipping_form': shipping_form}) and the html {% extends "base.html" %} {% load static %} {% block title %}Shipping{% endblock %} {% block content %} <form action="{% url 'test_order' %}" method="post"> <div class="colcontainer"> {% csrf_token %} {{ shipping_form }} <input type="submit" name="Submit"> </div> </form> {% endblock %} i have also tried using the validator because i just want to check that the field contains only alphanumeric … -
Django Foreign Key not registering in serializer
I am trying to overwrite the create method in my view. In my Child Serializer Class, I have the parent model as a foreign key. From the view, I am only provided the parent_id. I have to get the parent model instance first. After I get the parent model instance, I want to pass that into the serializer. However in my API view, I'm getting "parent": null. Why is that? Here is what my code looks like: class ChildList(generics.ListCreateAPIView): queryset = Child.objects.all() serializer_class = ChildSerializer def create(self, request, *args, **kwargs): parent_id = request.data.get('parent_id') parent = Parent.objects.get(id=hh_id) serializer = self.get_serializer(data={'parent':parent}) if serializer.is_valid(): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ChildSerializer(serializers.ModelSerializer): class Meta: model = HandHistoryObject fields = ('parent',) -
Django admin userlinks is not showing up
I extended base_site.html template and it's working correctly. {% extends "admin/base.html" %} {% load i18n %} {% block title %} {% trans 'Test Admin' %} {% endblock %} {% block userlinks %} {{ block.super }} {% endblock %} {% block nav-global %}{% endblock %} And now I've created a template for my submit form which looks like this. {% extends "admin/base_site.html" %} {% load i18n static %} {% block userlinks %} {{ block.super }} {% endblock %} But no userlinks is showing up. -
What is the correct way to organize Django apps when serving data to multiple graphs?
I am currently working on a site that displays warehousing information, but am having trouble wrapping my head around Django's app concept when it applies to serving data for multiple pages of graphs. I currently have 3 apps: Authentication - handles registration pages and user profiles Notifications - manages alerts to the users when there are changes in the data Warehousing - all of the other data is served from here onto the templates The "warehousing" app has grown way too large, since it provides data for the rest of the site (4 different templates), each of which has several graphs and also includes a map of warehouse locations and a log of warehousing equipment. I understand that each Django app is supposed to have a single focus, but what is the proper way to structure them when dealing with an application like this where a majority of the site is pages of interactive graphs? -
Can I add an "url file with namespace" inside of an url file from an AppHook?
Having a CMS with many apps (nested apps): /Dashboard (app hook) ----url.py ----cms_apps.py ----/Product --------/SomeCustomManagement -----------url.py -------url.py /MainSiteCMS In my main site I have a page that use "Dashboard" as AppHook, it works fine. "Dashboard.cms_apps": from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool class DashboardApp(CMSApp): name = "My Store" urls = ["dashboard.urls"] app_name = "store" apphook_pool.register(StoreApp) And inside "dashboard.urls": from django.conf.urls import url, include from .product import views as product_view urlpatterns = [ url(r'^$', product_view.home, name="producthome"), ] And everything works fine. But if I want to add in "dashboar.urls" url from another apps (a lot of apps): from django.conf.urls import url, include from .product.urls import urlpatterns as product_urls urlpatterns = [ url(r'^', include(product_urls, namespace="product")) ] and "product.urls": from .SomeCustomManagement.urls import urlpattern as scm_urls urlpatterns = [ url(r'^$', views.home, name="store-home"), url(r'^Management/', include(scm_urls, namespace="products")) ] ... I generate a link with: "store:products:managementlink", I tested the whole scenario outside of the CMS and works fine, but when I tried to combine all with the CMS, it gives me the following error: Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: 'products' is not a registered namespace inside 'store' Note: The code above is not my real code, I can't paste my real code and … -
Possible to have a simple auth that does not use the Django user model?
I want to override the BaseAuthentication class and just add a very simple check for username and password. Their will only be one user/pass in plain text that can be kept in a .txt file. This is just a POC and I am not at all worried about security vulnerabilities that come along with this. I guess the first question I have is can I create auth that does NOT use the User object in Django, I essentially just want to raise an error if user/pass does NOT match, otherwise continue (if that makes sense). from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) How I want to use it (example): # auth required only for POST requests permission_classes = (IsAuthenticatedOrReadOnly,) def get(self, request, format=None): variable_names = JobExecutionEnvSet.objects.all()[:8000] serializer = JobExecutionEnvSetSerializer(variable_names, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = JobExecutionEnvSetSerializer(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Returning values of a 'ReturnList' without the key in DjangoRestFramework
So I have this Serializers class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('name', 'thumbnail', 'source_url', 'duration') class SingleCategorySerializer(serializers.ModelSerializer): movies = MovieSerializer(many=True, read_only=True) class Meta: model = MoviesCategories fields = ('movies',) The Movie model has a relationship with the movies categories as follows category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING) Now when I try this serializer = SingleCategorySerializer(movie_category, many=True), the result of serializer.data is [ { "movies": [ { "name": "Guardians of the Galaxy", "thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:30:09" }, { "name": "Star Wars II", "thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:32:26" } ] } ] I only want the values of the movies to be returned. Like this [ { "name": "Guardians of the Galaxy", "thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:30:09" }, { "name": "Star Wars II", "thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:32:26" } ] Any help will be appreciated. -
How to speed up page loading time for images fetched from third party servers and external urls?
At the moment, we have built a simple Django application that simply fetches images from ImgUr APIs using the following endpoint: https://api.imgur.com/endpoints/gallery#gallery-search Then, it forwards the result to front-end for rendering which is simply HTML templates with jQuery. However, images loading on the client side in the browser is very slow. How to speed it up? -
What is the proper way to keep one-off data?
I've got online shop on Django, where I want to keep some information like address or mobile phone of manager, but this information should be simply-edited by admin of the site. So, I couldn't leave it just as text in template or variable in code, because now I need to create some forms for editing this information. I don't sure what to do: create model Info in my database with all fields which I want to keep or create couple of models for each. Or maybe there is a better solution? -
Why is this Popen call returning a "io.UnsupportedOperation: fileno" error in Django 2.0?
I recently upgraded my project to Django 2.0, and an error started cropping up. First off, I use django_gulp to start a gulp process whenever I start the django runserver. I'm using the runserver_plus branch of the django_gulp project. Here's the relevant code snippet from the django_gulp project, where it makes the subprocess.Popen call. This call was functioning correctly in Django 1.11.x. from __future__ import print_function import atexit import os import psutil import subprocess import sys import traceback from signal import SIGTERM from concurrent.futures import ThreadPoolExecutor from django.core.management.base import CommandError from django.conf import settings from django_extensions.management.commands.runserver_plus import Command \ as DjangoExtensionsRunserverCommand from env_tools import load_env class Command(DjangoExtensionsRunserverCommand): """ Subclass the RunserverCommand from Staticfiles to set up our gulp environment. """ def __init__(self, *args, **kwargs): self.cleanup_closing = False self.gulp_process = None super(Command, self).__init__(*args, **kwargs) @staticmethod def gulp_exited_cb(future): if future.exception(): print(traceback.format_exc()) children = psutil.Process().children(recursive=True) for child in children: print('>>> Killing pid {}'.format(child.pid)) child.send_signal(SIGTERM) print('>>> Exiting') # It would be nice to be able to raise a CommandError or use # sys.kill here but neither of those stop the runserver instance # since we're in a thread. This method is used in django as well. os._exit(1) def handle(self, *args, **options): try: env = … -
Django expire cache every N'th HTTP request
I have a Django view which needs can be cached, however it needs to be recycled every 100th time when the view is called by the HTTP request. I cannot use the interval based caching here since the number will keep changing upon traffic. How would I implement this? Are there other nice methods around except maintaining a counter (in db) ? -
How do I make a Django model instance to relate to another model instance
I want to have the amount under Rent to increment on the amount under Accounts. When a user types in the amount in Rent it should deduct or add in the amount in Account and should reset if paid or stay the same when not paid. class Account(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=250) number = models.PositiveIntegerField(help_text="Account number", unique=True, blank=True, null=False) currency = models.CharField(max_length=3, choices=ALLOWED_CURRENCIES) creation_date = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=MONEY_MAX_DIGITS, decimal_places=MONEY_DECIMAL_PLACES, help_text="Latest" "balance", default=0, blank=False, null=True) class Rent(models.Model): source = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account holder.") amount = models.DecimalField(max_digits=MONEY_MAX_DIGITS, decimal_places=MONEY_DECIMAL_PLACES) date = models.DateTimeField(auto_now_add=True) -
How to upload private files to s3 using boto3 and serializer
I am using S3Boto3Storage to manage private file uploads to s3: // storage_backend.py class PrivateFileStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_FILE_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False I have a model that is using FileStorage: // models.py class PrivateFileModel(models.Model): file = models.FileField(storage=PrivateFileStorage()) I have my default storage set to PrivateFileStorage under my settings: // settings.py DEFAULT_FILE_STORAGE = 'myapp.storage_backend.PrivateFileStorage' And then I have my serializers: // serializers.py class PrivateFileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PrivateFileModel fields = ('url', 'file') I am able to save the private file directly to the model. However, when I try to save using PrivateFileSerializer, I am getting this error: botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found How do I fix this?