Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set STATIC_URL in Django settings.py for CDN
I want to use static file in my django 2.0.5 template that is located on: https://my_cloud_front_adress.cloudfront.net/staticfiles/picture_small.jpg On Heroku i've set varible: STATIC_URL = https://my_cloud_front_adress.cloudfront.net/staticfiles/ templates/base.html {% load static %} {# this one is NOT working #} <img src="{% static 'picture_small.jpg' %}" alt="my test image"/> {# this one is working #} <img src="https://my_cloud_front_adress.cloudfront.net/staticfiles/picture_small.jpg" alt="my test image"/> How should i set STATIC_URL to make this work in the template: <img src="{% static 'picture_small.jpg' %}" alt="my test image"/> -
Regex package works in shell, but not in React component
I am working on a Django/React app. When I open a python shell in my venv, I can import re and test my regular expressions. However, if I try to put import re at the top of a React component then I get an Unexpected token error and if I require it with require('re') I get Module not found: cannot resolve re. I don't think there is anymore relevant code but happy to post whatever might be helpful. Thanks in advance! -
Could not import ''. The path must be fully qualified
I am working with Django for a few months and built this website just for fun and further improving myself and I can't for the life of me get rid of this error, I have looked for all my code and can't find this import error and for some reason it won't tell where it's going wrong. This is the error. However, the weird thing is that is doesn't always happen on this page, its like they are taking turns in erroring out, for example, I am able to log in without any issues sometimes but on occasion, I get this error and all I have to do is just reload the page and enter my details again. Environment: Request Method: POST Request URL: https://www.enfieldgrammar.tk/account/login/?next=/account/ Django Version: 1.11b1 Python Version: 3.6.0 Installed Applications: ['accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response 178. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/middleware/csrf.py" in process_view 314. return self._reject(request, REASON_BAD_TOKEN) File "/usr/local/lib/python3.6/dist-packages/django/middleware/csrf.py" in _reject 163. return _get_failure_view()(request, reason=reason) File "/usr/local/lib/python3.6/dist-packages/django/middleware/csrf.py" in _get_failure_view 43. return … -
Django won't send password-reset email on remote server, works on local machine
I'm running a Django project on a remote server with nginx and uwsgi. In my local_settings.py I have this: ############### # EMAIL SETUP # ############### ADMIN_EMAIL = "admin@mydomain.com" SUPPORT_EMAIL = "support@mydomain.com" DEFAULT_FROM_EMAIL = SUPPORT_EMAIL SERVER_EMAIL = SUPPORT_EMAIL EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = DEFAULT_FROM_EMAIL EMAIL_HOST_PASSWORD = 'my password here' EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True When I fill out and submit the form in Django's password_reset template, no email gets sent. Instead I see this in uwsgi.log. MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: Password reset on Default From: webmaster@localhost To: my.personal@gmail.com Date: Wed, 16 May 2018 16:55:23 -0000 Message-ID: <20180516165523.3354.76044@rbpb-dev.mydomain.com> Hello, You received this email because a request was made to reset the password. If you requested this, go to the following page and choose a new password: https://127.0.0.1:8000/reset/MQ/4w8-0373d185ce41dcdb0b63/ Your username: my.personal@gmail.com Thank you. ------------------------------------------------------------------------------- When I fillout the form and submit it when running my Django project on my local machine, I actually get an email at the gmail account specified. What's going on here? -
Raise TypeError(repr(o) + " is not JSON serializable") when trying to update the data in div with ajax
I got this Exception for what i understood for passing a dictionary with objects throw json: Internal Server Error: /dashboard/ajax/reload_data/ Traceback (most recent call last): File "/home/micael/Documents/MySite/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/micael/Documents/MySite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/micael/Documents/MySite/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/micael/Documents/djangoDashboard/dashboard/views.py", line 35, in reload_data data = json.dumps([p.__dict__ for p in content]) AttributeError: 'unicode' object has no attribute '__dict__' [16/May/2018 15:43:42] "GET /dashboard/ajax/reload_data/ HTTP/1.1" 500 20661 The ajax view: def reload_data(request): if request.is_ajax(): b = Jobs.objects.order_by('end_time').reverse()[:10] u = Update.objects.values('nome_cliente').distinct() content = {"backup_info": b, "update_info": u} x = Cliente.objects.all() for x in Cliente.objects.all(): now = time.time() minTime = now - 86400 #last_28h n_jobs_last_24h = Jobs.objects.filter(id_cliente_id=x.id_cliente, insert_time__range=(minTime, now)).count() if n_jobs_last_24h < x.n_jobs: #faltam jobs messages.add_message(request, messages.WARNING, 'Cliente %s com menos %s jobs!' % (x.identificador, (x.n_jobs - n_jobs_last_24h))) data = json.dumps(content) return HttpResponse(data, content_type='application/json') else: raise Http404 The template code: <div id ="update"> <div id="dash1div"> <a href=""> <strong>Updates</strong> </a> </div> <ul> {% for update_info in update_info %} <li> <a id = "{{update_info.nome_cliente}}" href="/dashboard/ListUpdate/{{update_info.nome_cliente}}/">{{update_info.nome_cliente}}</a> </li> {% endfor %} </ul> </div> The Ajax Code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> setInterval(function(){ console.log('am i called'); $.ajax({ url: '/dashboard/ajax/reload_data/', success: function (data){ response_json … -
create multiple related object with Django REST Framework
I'm using Djago 2.0 and Django REST Framework I have following model classes for contacts/models.py class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) class ContactPhoneNumber(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE) phone = models.CharField(max_length=100) primary = models.BooleanField(default=False) contacts/views.py class ContactViewSet(viewsets.ModelViewSet): serializer_class = ContactSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission,) def get_queryset(self): return Contact.objects.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user_id=self.request.user) and contacts/serializers.py is defined as class ContactPhoneNumberSerializer(serializers.ModelSerializer): class Meta: model = ContactPhoneNumber fields = ('id', 'phone', 'primary', 'created', 'modified') class ContactSerializer(serializers.HyperlinkedModelSerializer): phone_numbers = ContactPhoneNumberSerializer(source='contactphonenumber_set', many=True) user = serializers.CurrentUserDefault() class Meta: model = Contact fields = ('url', 'id', 'first_name', 'last_name', 'date_of_birth', 'phone_numbers') def create(self, validated_data): phone_numbers = validated_data.pop('contactphonenumber_set') user = validated_data.pop('user_id') instance = Contact.objects.create( user=user, **validated_data ) for phone_data in phone_numbers: ContactPhoneNumber.objects.create(contact=instance, **phone_data) return instance I want to be able to create multiple phone_number instances with new contact object. How can I pass multiple phone_numbers with fields phone, primary along with contact data? -
Axios Response in React Page
I am trying to set the state of my Axios Response data. The REST call works but the state is not being set. this.state = { source: sources['bunnyMovie'], startDate : moment(), endDate: moment(),//endDate : moment() filename: "", storageArea: [], v_bucketName: "", v_creationDate: "", }; componentDidMount() { const self = this; axios.get(`/api/Storage/`) .then(response => { self.setState({storageArea: response.data}); console.log(response); console.log("StorageArea: " + self.storageArea); }); } But the storageArea is null. Incidentally, the type can be array or was NULL before I changed it. Either way it's not working. What am I missing? -
Nginx and Django download *.mp3 file
I have a Django project which downloads files, currently its hosted on Linux VPS with Nginx serving the entire project. I am getting an error when I try to download a file on this URL http://example.net/downloader/VYOjWnS4cMY/myfile.mp3 This is the error that Nginx is logging when I try to download a file. 2018/05/16 17:22:02 [error] 30075#30075: *3 open() "/var/www/html/project_folder/converter/media/myfile.mp3/downloader/VYOjWnS4cMY/myfile.mp3" failed (2: No such file or directory), client: 41.75.172.141, server: 173.212.212.165, request: "GET /downloader/VYOjWnS4cMY/myfile.mp3 HTTP/1.1", host: "www.example.com" And lastly, this is my Django view method which handles download functionality. def download(request, youtube_id, filename): """ Serves the audio file. """ filepath = os.path.join(settings.MEDIA_ROOT, filename) file_exists = os.path.exists(filepath) if settings.DEBUG: with open(filepath, 'rb') as file_data: response = HttpResponse(file_data.read(), content_type='audio/mpeg') response['Content-Disposition'] = 'attachment; filename={}'.format( smart_str(filename)) response['Content-Length'] = os.path.getsize(filepath) return response else: # Have Nginx serve the file in production. response = HttpResponse(content_type='application/force-download') response['Content-Length'] = os.path.getsize(filepath) response['X-Accel-Redirect'] = os.path.join(settings.MEDIA_URL, smart_str(filename)) return response return HttpResponseRedirect(reverse('home')) Thank you in advance -
LiveServerTestCase slow
Approximately 1 time out of 4, when I try to run my functional tests, I've to wait like 20 minutes for my tests to start : python manage.py test Using existing test database for alias 'default'... And this issue is not happening when I run my unit tests. Even when I try to run simple tests like : class FrontTest(LiveServerTestCase): @classmethod def setUpClass(self): super(FrontTest,self).setUpClass() @classmethod def tearDownClass(self): super(FrontTest, self).tearDownClass() def test_stupid(self): print('hello world') Does this problem ever happened to you ? -
Getting error on running manage.py runserver
I am new to django, I got error on executing manage.py eventhough having installed django vivekmehra88@vivekmehra88-HP-Pavilion-TS-15-Notebook-PC:~/PycharmProjects/myProj/django-apps/testsite$ python3 manage.py runserver 127.0.0.1:8000 Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ImportError: No module named 'django' vivekmehra88@vivekmehra88-HP-Pavilion-TS-15-Notebook-PC:~/PycharmProjects/myProj/django-apps/testsite$ django-admin --version 1.8.7 -
Django JWT: Why is the signature returned from authenticate(request) different from the signature in the original request?
Why is the signature in the token returned from authenticate(request) different from the signature in the token of the original request? I trying to get the original token... class JWTAuth(JSONWebTokenAuthentication): """Token based auth using JSON Web Token.""" def authenticate(self, request): user, jwt = super().authenticate(request) or (None, None) The class JWTAuth is included in my 'DEFAULT_AUTHENTICATION_CLASSES' in settings. Any hint is welcome. -
Python Django forms, form is not work with entered data
Im new with Django and Im trying to include my own form My forms.py class MyOwnForm(forms.ModelForm): class Meta: model = Album fields = ['username'] My views.py def testing_Form(request): if not request.user.is_authenticated: return render(request, 'login.html') else: form = MyOwnForm(request.POST or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user username = form.cleaned_data['username'] return render(request, 'form.html', {'form': form}) my form.html <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'form_template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> and the last one form_template.html {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-2" >{{ field.label_tag }}</label> <div class="col-sm-10">{{ field }}</div> </div> {% endfor %} When I open the Form Webpage, I get a empty entry field and the submit button. But when I click this button. The page is reloading and nothing more. what do i have to do that i can work with the entered data? -
Getting Pagedown to preview markdown and mathjax at the same time?
First i got a js script to update a preview div from Pagedown textarea/Pagedown widget from Django-pagedown, with the code below: MathJax.Hub.Config({ tex2jax: { inlineMath: [['$', '$'], ["\\(", "\\)"]] } }); var timeout; $(function () { function makePreview() { input = $('#id_content').val().replace(/</g, "&lt;").replace(/>/g, "&gt;"); $('#id_content_wmd_preview').html(input); MathJax.Hub.Queue(["Typeset", MathJax.Hub, "preview"]); } $('body').keyup(function () { if (timeout) { clearTimeout(timeout); timeout = null; } timeout = setTimeout(makePreview, 400); }); $('body').bind('updated', function () { makePreview() }); }); But the problem is that when this script updates the preview div, it also updates and removes the markdown? If i constantly type then the markdown shows correctly, but not mathjax. If I stop typing the markdown don't show, but mathjax shows correctly? -
Django 1.11 authentication set_unusable_password vs setting password to None
My team has overwritten the authenticate method for users years ago to authenticate against LDAP instead of djangos model backend. this method looks at LDAP for the user. If the user exists with correct username and password, it gets or creates the user (This means that the user doesn't have to exist as a model object in the Django database for someone to log in). The method leaves the newly created password as None. Then sets all the other information. I noticed that they, after validating the user, call the set_unusable_password on the user if they were valid. In a comment, they wrote that it overrides Django's built-in password handling... which obviously that makes sense. But I don't know why they needed to since we've already overwritten the authenticate method. I tested this out by removing the set_unusable_password so that the password is left as None and the validation worked. They were still able to log in with the password that's stored on LDAP. You still could not overwrite the password in the model to be different than that on LDAP and login with that. So basically the set_unusable_password call had no effect other than just creating a password... which … -
Django REST Framework - int() argument must be a string, a bytes-like object or a number, not 'SimpleLazyObject'
I'm using Django 2.0 and Django REST Framework to write REST API. my settings.py contains settings for DRF REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ] } and every request must be signed using any of the DEFAULT_AUTHENTICATION_CLASSES method. In contacts/serializers.py class ContactSerializer(serializers.HyperlinkedModelSerializer): phone_numbers = ContactPhoneNumberSerializer(source='contactphonenumber_set', many=True) class Meta: model = Contact def create(self, validated_data): phone_numbers = validated_data.pop('contactphonenumber_set') emails = validated_data.pop('contactemail_set') instance = Contact.objects.create(**validated_data) for phone_data in phone_numbers: ContactPhoneNumber.objects.create(contact=instance, **phone_data) return instance print(validated_data) gives following data {'first_name': 'Anshuman', 'last_name': 'Upadhyay', 'date_of_birth': datetime.date(2018, 5, 15), 'contactphonenumber_set': [], 'user_id': <SimpleLazyObject: <User: anuj>>} The user_id is SimpleLazyObject thus giving error on save TypeError: int() argument must be a string, a bytes-like object or a number, not 'SimpleLazyObject' The error is on the line instance = Contact.objects.create(**validated_data) How can I pass authenticated user to user field? -
Sending an array from javascript to Django
I have an array of objects in javascript. Arr = [0: {k;v}, 1: {k,v}] etc etc... with a lot of fields in them. I'm having trouble sending them to Django. I've tried doing JSON.stringify and sending it to django and retrieving with both getlist and get. The problem is I get a list with two dictionaries inside but I cannot figure out how to iterate through the list. Current code is sending the array to Django this way: {'data[]': JSON.stringify(arr)} And in Django: req = request.POST.getlist('data[]', None) What I get back when I print the statement is: ['[ { dict of key, value pairs }, { dict of key value pairs }]'] I cannot figure out how to iterate through the list of dictionaries and retrieve the key value pairs and keep them as separate. -
django 1.7 how to add foreign key constraint on django session model?
In Django 1.7 adding a foreign key constraint on Django session gives, django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint') below is my model definition class UserSession(models.Model): user = models.ForeignKey(User,blank=True,null=True,default=None) session = models.ForeignKey('Session') After looking into the database, django_session table doesn't have an id column. I have also tried adding db_column='session_key' (considering session_key is primary key in django_session table) parameter to ForeignKey() function. I am still getting the same error. Any help will be greatly appreciated. -
"Not a valid string." - error when trying save dict to TextField in Django Rest Framework
I have in my models.py: class ApiLog(models.Model): ... incoming_data = models.TextField('incoming data', null=True, blank=True) In serealizers.py class ApiLogSerializer(serializers.ModelSerializer): class Meta: model = ApiLog fields = ('incoming_data',) In views.py: class ApiLogViewSet(APIView): def post(self, request, format=None): serializer = ApiLogSerializer(data=request.data) if serializer.is_valid(): serializer.save() In POST-request I send: data = {..., 'incoming_data':{"key1":"value1","key2":"value2"} } When in view trying serializer.is_valid() I have error: {"incoming_data":["Not a valid string."]} Maybe it's because I try to save dict to TextField? How it's possible to save this dictionary to TextField? -
How to use Feedparser in Django Project
Could anyone direct me on how to include feedparser in my Django project? Essentially I'm building a news aggregator, so there will be 100's of rss feeds to parse through. I understand the basic formatting and whatnot (running loops to display the feeds), but I'm not sure how to implement Feedparser. Where exactly do I import it inside my Django project? And do I just hardcode the urls? Or is there a way to edit them from the admin page? -
Django + background-tasks how to initialize
I have a basic django projects that I use as a front end interface for a (Condor) computing cluster for generating simulations. From the django app the users can start simulations (in Condor). The simulation related meta-data and the simulation state are kept in a DB. I need to add a new feature: notification when (some) simulations are done. Since I want a simple solution (and I already using background tasks) I was thinking to use repeating task that at fixed intervals query Condor about the tasks, updates the DB and if necessary sends notifications. My questions: where is the best place to register (initialize) this task (to be done only once) in my django app how to avoid having duplicated such repeating tasks (if for instance I have to restart the web server, or the background task process) ? -
Paginating nested objects in django restframework
PS : Django 2.0.4 and django-restframework 3.7.7 I am having a Place model to store the details of a place and there is one more model PlacePhoto to store the photos of that place Place model is something like this: class Place(models.Model): name = models.CharField(_('name'), max_length=1024, blank=True, null=True) description = models.TextField(blank=True, null=True) and PlacePhoto model is something like this: class PlacePhoto(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='photos') image = models.ImageField() My Place serializer is something like this: class PlaceSerializer(serializers.ModelSerializer): photos = serializers.SerializerMethodField() class Meta: model = Place fields = ('id', 'name', 'photos', ) def get_photos(self, obj): photos = obj.photos.all() request = self.context.get('request') serializer = PlacePhotoSerializer(photos, many=True, context={'request': request}) paginator = RelationPaginator() paginated_data = paginator.paginate_queryset(serializer.data, request) return paginator.get_paginated_response(paginated_data) class RelationPaginator(pagination.PageNumberPagination): def get_paginated_response(self, data): return { 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'results': data } class PlacePhotoSerializer(serializers.ModelSerializer): class Meta: model = PlacePhoto fields = ('image', ) I am trying to paginate the photos of a place but unfortunately I am not successful in that. The request object being passed to paginator is same as that of place api so the photos absolute_uri is same as that of place api. { "count":6, "next":"http://localhost:8000/api/v1/places/?page=2", "previous":null, "results":[ { "id":1832, "name":"The National", "locality":"New York", "location":{ "latitude":-73.97212481, "longitude":40.756645889989 … -
Remove duplicates from queryset django
I've made this queryset to my django database: material_purchase=Material_Purchase.objects.order_by("material__id","-purchase__date").values("id","material__id","price","purchase__date") That returned me this: <QuerySet [{'id': 8, 'material__id': 1, 'price': Decimal('6.00'), 'purchase__date': datetime.date(2018, 5, 31)}, {'id': 2, 'material__id': 1, 'price': Decimal('5.00'), 'purchase__date': datetime.date(2018, 4, 29)}, {'id': 9, 'material__id': 1, 'price': Decimal('3.00'), 'purchase__date': datetime.date(2017, 12, 1)}, {'id': 7, 'material__id': 2, 'price': Decimal('10.00'), 'purchase__date': datetime.date(2018, 5, 31)}, {'id': 5, 'material__id': 2, 'price': Decimal('20.00'), 'purchase__date': datetime.date(2018, 5, 16)}, {'id': 1, 'material__id': 2, 'price': Decimal('27.00'), 'purchase__date': datetime.date(2018, 4, 29)}, {'id': 10, 'material__id': 2, 'price': Decimal('5.00'), 'purchase__date': datetime.date(2017, 12, 1)}, {'id': 6, 'material__id': 3, 'price': Decimal('6.00'), 'purchase__date': datetime.date(2018, 5, 31)}, {'id': 11, 'material__id': 3, 'price': Decimal('5.00'), 'purchase__date': datetime.date(2017, 12, 1)}]> Now I want to delete all the duplicate objects with same 'material__id', except the first( the most recent one). I've tried to do this first, with .distinct but my database is sqlite3 and that gives me an error. -
Django filter foreign key model in views.py
I have two models, one is called Books and BookInstance, one Book has many BookInstances, class Books(models.Model): ......... def get_absolute_url(self): """ Returns the url to access a detail record for this book. """ return reverse('book-detail', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return '{0}'.format(self.book_name) class BookInstance(models.Model): books = models.ForeignKey('Books',verbose_name="Books", on_delete=models.SET_NULL, null=True) keyrequest = models.OneToOneField('BookRequest', verbose_name='Book requests', on_delete=models.SET_NULL, null=True, blank=True,) LOAN_STATUS = ( ('a', 'Available'), ('o', 'On loan'), ('r', 'Reserved'), ) status = models.CharField(max_length=1, choices=LOAN_STATUS, help_text='Key availability', verbose_name="Key status", blank=True) date_out = models.DateField(null=True, blank=True, verbose_name="Date Issued") due_back = models.DateField(null=True, blank=True, verbose_name="Date to be returned") ...... id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book") I have a class based view in views.py that uses the Book model to show the total number of BookInstances for that book, Here's my views.py: class KeyListView(generic.ListView): model = RoomKey fields = '__all__' template_name = 'catalog/roomkey_list.html' And I have a template that shows the number of all BookInstances for a Book,as shown below: {{ books.bookinstance_set.all.count }} But I would like to filter it out and show the number of available BookInstance of that Book, I tried to use add a Query manager in the BookInstance class but that didn't work , … -
Docker SMTP Server for Django Container SMTP backend
I am looking to have one of my django docker containers setup a smtp backend so I can send input from a contact form to a gmail address as well as possibly send out an email when someone puts in their email to subscribe for updates: https://docs.djangoproject.com/en/1.11/topics/email/#smtp-backend How do I go about setting up the SMTP server? Is it a separate docker container? How do I set it up? -
Node, spawn multiple dependent shell commands
I'm trying to use gulp to activate a virtualenv for python and launch a django server. Although I can launch the server correctly I can't activate the virtualenv beforehand. (this breaks integration with my IDE's gulp tool). Is there a way to make the virtualenv spawn launch first and be part of the child process that launches the server (as the server depends on being in the virtual environment). gulpfile.js gulp.task('runServer', function(cb) { var virtualenv = spawn('source venv/bin/activate') var cmd = spawn('python', ['manage.py', 'runserver'], {stdio: 'inherit'}); cmd.on('close', function(code) { console.log('runServer exited with code ' + code); cb(code); }); });