Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make HyperlinkedModelSerializer in Django Rest Framework work for foreignkeys?
I am new to Django Rest Framework and am struggling to get my serialisations to work correctly for a foreignkey relationship between two models. I have tried to reduce my setup down to be as simple as possible but I still can't understand how it is supposed to work. I am trying to use HyperlinkedModelSerializer so (from the docs) 'that it uses hyperlinks to represent relationships'. When I try to visit the url for either the list or detail view for {model X} on the test server I get: 'Could not resolve URL for hyperlinked relationship using view name "{model Y}-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.' What am I doing wrong? My models: from django.db import models class Project(models.Model): name = models.CharField(max_length=50) description = models.TextField() class ProjectPhoto(models.Model): project = models.ForeignKey( Project, related_name='photos', on_delete=models.CASCADE ) image = models.ImageField() caption = models.CharField(max_length=100) date_added = models.DateTimeField(auto_now_add=True) My serializers class ProjectSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Project fields = ('name', 'description', 'photos') class ProjectPhotoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ProjectPhoto fields = ('image', 'caption', 'date_added', 'project')) My views: from rest_framework import viewsets from projects.models import Project, ProjectPhoto from projects.serializers import … -
Hide a site using Django's Sites framework
Asking this as best as I can, when it's a problem I don't fully understand (and a situation I didn't/wouldn't create). We are using Django's Sites framework to power our API (among other things, obviously). There is no front-end component to our API, but if a user goes to the URL we get a broken website of some of our standard components (footer, sidebar, etc). We want to keep this from having any front-facing interface. Open to ideas--whether it's to show an error page, or redirect somewhere else, or whatever. Obviously we don't want to break our API. -
download pdf files using wkhtmltopdf in django
I am new to django ,I want to create an action in the admin panel to let the admin be able to download the users files which are stored in the media directory The files are uploaded as pdf I use pdfkit to be able to download them > import pdfkit > > def downloadCV(self, request, queryset): > projectUrl = str(queryset[0].cv)+'' > pdf = pdfkit.from_url(projectUrl, False) > response = HttpResponse(pdf,content_type='application/pdf') > response['Content-Disposition'] = 'attachment; filename="user_cv.pdf"' > return response but I got the following error "wkhtmltopdf reported an error: Loading page (1/2)] 10% Error: Failed loading page file:///... (sometimes it will work just to ignore this error with --ignore-load-errors)) -
Django-Calling python script in HTML
I have a python script written up that returns a list of values from a database. I want to incorporate that script into my django website that I have created. I have an html file right now in my templates folder that has dictionary values hardcoded but how do I replace the dictionary hardcoded material with the script, lets call it values.py <script type="text/javascript"> $(document).ready(function() { var dropDown = [" ", "Run1", "Run2", "Trail1", "Trail2"]; var dropDownID = [" ", "111111", "222222", "333333", "444444", "555555"]; $("#dropDown").select2({ data: dropDown }); $("#dropDown").change(function() { $("#dropdownID").val(dropDownID[$("#dropDown option:selected").index()]); }); }); Now do I just add my values.py into my templatetag folder and then from there do I just fill the var dropDown = [" ", "Run1", "Run2", "Trail1", "Trail2"]; to something like var dropDown = [ {% load tag %} <div id="id_div"> {% value %} </div> ] -
Should we connect to AWS SNS every time we send a push notification?
I am working on DJANGO server, creating a REST service. The purpose of the service is to send a push notification to the phone number mentioned in the request. I am using AWS SNS service for push notifications. I am establishing connection between my server and AWS every time there is a request to the server. My question is, can we establish a connection once the server is up, like opening a port as we do in a chat application? Or I should establish a connection every time? I am using Boto package and below is my code connection = SNSConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY) connection.publish(message=jsonMessage, subject=title, target_arn=endPoint, message_structure=structure) -
Elegant way to deal with redundant words on python class/method naming
Simple question but I'm struggling with it. I want to create a custom object manager to a Django model just like this: class Clearance(models.Model): user = models.OneToOneField(User, verbose_name='usuário') level = models.CharField(choices=PERMISSION_LEVELS, max_length=20, verbose_name='nível') tech_support = TechSupportManager() user_manager = UserManagerManager() OK, the problem is the redundant Manager word. I don't feel like removing the last word and just leave "UserManager" without really saying what that class suppose to do but duplicate the word feels like the wrong thing to do too. Is there any more elegant way to do it? -
Django cannot serialize regex.Regex - What to do?
Apps used: Django 1.10.5 regex 2017.1.17 (https://bitbucket.org/mrabarnett/mrab-regex) I'm using this regex as validator in my model: regex.compile(r'^[a-zA-Z0-9]{2-4}$') I get this Error running manage.py makemigrations: ValueError: Cannot serialize: regex.Regex('^[a-zA-Z0-9]{2-4}$', flags=regex.V0) Now I don't know what I have to do for regex.compile is not just a class (I could subclass). In the Django code I found this: COMPILED_REGEX_TYPE = type(re.compile('')) This is how Django detects regex that are compiled with Python's standard re concerning serialisation. What is the best practice to deal with it? -
Serializers vs. Forms. How can I have both?
Salut friends, I have been working with Django on a project for over a year now, and this project doesn't quite have forms (just a few). The way it is done is without Django Rest Framework, simple crispy forms, which are validated when the POST arrives at the corresponding view. A month ago, I started to work on a different project, much bigger, that in the greatest part relies on forms. This project uses Django Rest Framework, serializers + viewsets, and renders forms through DRF serializers. After attaining a certain understanding of all the validations that can be done with DRF serializers, I started to imagine it'd be a good idea to bring serializers and viewsets to my older project in order to enjoy the better structure offered by DRF. Here is my question: Can (crispy) forms and serializers work well together? Is it better to render my forms with DRF if deciding to stick with DRF? I saw a couple of people who use both, but it is unclear to me at this point. Is there a more standard way to do so, which is used by a majority? Thanks! -
How to migrate database views in Django?
There is already a number of posts to handle this situation, but so far I am not sure which one best fits my case. I have looked into this: https://blog.rescale.com/using-database-views-in-django-orm/ but I do not want to modify a migration file, simply because we do not push these files as part of the git repository. I have looked into How can i hook into django migrations for django 1.8. It looks promising, but I don't think I should hardcode a connection to the database (I have multi-databases) at this point. Was hinted in the comments in #2. https://docs.djangoproject.com/en/1.10/ref/signals/#pre-migrate. It does not look bad and I'm not sure if there are limitations here. I'm looking for advice on which way to go. Thanks -
Django IndexError: pop from empty list
I have been building a website for a local scout group. For some reason this error in Django continues to persist and I cannot understand where it comes from and how to fix it. The error according to the traceback is in my index.html page: <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <meta charset="utf-8" /> <meta name="robots" content="index, follow"> <meta name="keywords" content="3rd, Ringwood, scouts, cubs, beavers, hall hire, hire, hall, hut, third"> <meta name="description" content="3rd Ringwood Scout Group - Beavers, Cubs and Scouts. The hut is also a perfect place to hire for other activities."> <!-- <link rel="dns-prefetch" href="//"> --> <link rel="icon" href="/static/images/favicon.png" type="image/png" /> <link rel="stylesheet" href="/static/css/style.css" charset="utf-8"> <link rel="stylesheet" href="https://ink.global.ssl.fastly.net/3.1.10/css/font-awesome.min.css" /> <title>3rd Ringwood Scouts</title> <script type="text/javascript" src="https://ink.global.ssl.fastly.net/3.1.10/js/holder.js"></script> <script type="text/javascript" src="https://ink.global.ssl.fastly.net/3.1.10/js/ink-all.js"></script> <script src="https://code.jquery.com/jquery.min.js" charset="utf-8"></script> </head> If you need any more information please ask. -Max -
Django cannot import name (model)
I have two files under this app that are messing up. One updates the cache and the other is my models.py file. For some reason I get ImportError: cannot import name 'Cache' Whenever I try to load the server. Moving the Cache definition above the NavigationItem definition worked for one test boot but has failed every time since. navbar/models.py from django.db import models from navbar.generator import update_navigation from datetime import datetime import logging class NavigationItem(models.Model): # The title used in the navar title = models.CharField(max_length=25, blank=False) # The dir it points to dir = models.ForeignKey('library.Dir', blank=True, null=True) # The level above it previous_level = models.ForeignKey('NavigationItem', on_delete=models.SET_NULL, null=True, blank=True) # Is it on the top level top_level = models.BooleanField(default=False) # Shortcut show_all_subdirs = models.BooleanField(default=False) # position on the list position = models.SmallIntegerField(default=15) # last modified: last_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def __repr__(self): return "({}) {}".format(self.pk, self.title) def save(self, *args, **kwargs): super(NavigationItem, self).save(*args, **kwargs) logging.INFO("Saved Navbar at " + datetime.now()) update_navigation() class Cache(models.Model): key = models.CharField(max_length=10, default="key", unique=True) data = models.TextField() timestamp = models.DateTimeField(auto_now=True) navbar/generator.py from navbar.models import Cache, NavigationItem from datetime import datetime import logging def render_navigation(): query = Cache.objects.filter(key="nav") if query.count() > 0: return query[0].data else: return update_navigation() … -
Django Rest Framework not passing 'X_USERNAME' on request - authenticate method param
I'm trying to set a Custom Authentication class on Django Rest Framework, but all client requests return the same error: {"detail":"Authentication credentials were not provided."} So, debugging the Custom class and printing the request.META atributte it has no X_USERNAME key. CustomAuth class: class TecnicoAuthentication(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) on settings.py file: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : ( 'os_hotlink.auth.TecnicoAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } -
How to connect Django Rest Framework with contrib.auth views
I am using DRF with JWT (JSON Web Token) authentication. I want to use django's built-in reset password functionality. So, I have included the urls: url('^', include('django.contrib.auth.urls')), But, of course, under an API, calling https://.../password_reset/ results on a csrf token missing error. I am wondering which aproach should I take to solve this. Should I change the built in reset_password view and remove csrf protection? Is it a better idea to create a DRF endpoint that accepts the email (reset_password view post parameter) and then somehow generate a csrf token and send it to the view with redirect(reverse("reset_password"), email=email) ... but then, redirect will not send a post request to the reset_password view. Maybe saving the email to session? Any advice will help. -
Combine 2 response if models.field is same for two requests
I have Request data model with id, type and language. I am doing the following process. def email_me(requests):` string = "" for request in requests.all(): string = """ ID: %d Type: %s """ % (request.id, request.type) <some code for sending an email> I am running this function into a view where I get the requests Here string will give data for each individual Request database column. What I want to do is if type is same for two string I want to combine them in one email. For example type = customer I want to send data in one email. How can I do that ? -
Django: where to store and how to serve up non-static MP4 video files
I'm building a Django app that will display videos created by surveillance software in a more user-friendly fashion than the software does natively. I have a python script that processes the video filenames and creates a directory structure based on when the videos were created. Then, I want this script to move the files into a location where Django will be able to find them and serve them up. The videos will be added to this location (and eventually removed from this location if they're old enough) on an hourly basis. So it doesn't seem like the static directory is appropriate. Where should I have the script put the video files? What is the syntax to serve those video files up in my template from the recommended location? Thanks! EDIT: I'm just using the development runserver right now, but will eventually have this deployed to a production server. If the answer is different for dev vs production, it would be great to know that too! -
Passing params between angular and django rest framework
My angular factory is as follows: factory("GetUser", ["$resource",function($resource) { return $resource( "api/v1/user/:username", {}, { "query": { method: "GET", headers:{ "Content-Type":"application/json" } } }, { stripTrailingSlashes:false } ); }]); My api urls.py is as follows: from rest_framework.routers import DefaultRouter from .views import UserViewSet router = DefaultRouter() router.register(prefix='user', viewset=UserViewSet) urlpatterns = router.urls My view.py is as follows: class UserViewSet(viewsets.ModelViewSet): queryset = user.objects.all() serializer_class = UserSerializer I am new to python and I was wondering how I can be able to retrieve the parameter written username that I am sending from Angular js. Tutorials I keep getting are showing how to get all the fields using queryset = user.objects.all() as shown in the views.py. How can I change the views.py so it return I object. -
Automatically registering Django model in a separate table
In my Django app I have several models representing different types of content: class Video(models.Model): title = models.CharField(max_length=50) class Playlist(models.Model): videos = models.ManyToManyField(Video) Now I would like to create an easy way of adding like's to instances of the two models, that can be easily set up like in the django-vote app: class Video(models.Model): title = models.CharField(max_length=50) likes = LikeManager() class Playlist(models.Model): videos = models.ManyToManyField(Video) likes = LikeManager() But unlike the django-vote method, which relies on a single table Votes linking all votes to different objects via GenericRelation field, I want to automatically create a separate table for each model, like VideoLikes and PlaylistLikes. This can have significant impact on performance when number of objects of either model becomes very large, or if other likeable models are added in the future. Is there a way of abstracting to this level, or do I have to create an abstract Like model, and then create VideoLike, PlaylistLike inheriting from the abstract Like model? -
Django rest framework url optional path?
I would like to use nested url for some views. /# /toon/{toon_id}/episode/{episode_num} url(r'^toon/(?P<toon_id>[0-9]+)/episode/(?P<episode_num>[0-9]+)', toon_episode.as_view()) I am wondering if I can make episode_num optional rather than have separated url for each case ? -
Django - Read and write from a plain text
I'm trying to read and then write from a plain text in Django. Basically I want to open a file, get an specific word and then change it for whatever else. Here's what I have: def address_L1(): file = open("interfaces.txt","r") content = file.read() file.close() address = re.findall('address\s(.*?)\s',open('interfaces.txt','r').read()) if address: print address[0] else: print 'no Address found!' return address[0] Here I'm opening a file and search for the word next to address, which is 192.168.5.5 and works perfect. def get_interfaces(request): address = str(address_L1()) if 'address' in request.POST: write_template(request)#This is for my writing function return render(request, 'interfaces.html', {'address':address}) Here I'm passing to template what's in address I mean, 192.168.5.5 will be shown in template. <form method="post" action="">{% csrf_token %} <label for="your_name">Address: </label> <input id="your_name" type="text" name="address" value="{{ address }}"> <br> <input type="submit" class="btn btn-success btn-xs" value="Guardar Cambios"> </form> Here is my html were I'm displaying my variable, There's an input Address that will show my 192.168.5.5 or whatever is in address variable. Everything works ok until now. Now I'm trying to write to my plain text. def write_template(request): if request.method == 'POST': get_address = address_L1() change_address_L1 = request.GET.get("address", None)#Doing something with my input field in template filedata= None with open('interfaces.txt', 'r') as … -
TableBlock how to specify table classname
I am stuggling to add a classname to Wagtail StreamField & TableBlock (http://docs.wagtail.io/en/v1.8.1/reference/contrib/table_block.html). Is the way to go to define a filter and use something like: {{ child|className:"table table-bordered" }} where className is custom filter? -
Django multi-database, one model
In my Django project, I would like two databases but only one model. For example, an expert database and an exploit database. The router allows me to write in the exploit database or the expert database according to the users groups and permissions. But how to duplicate the project model (described in model.py) in both bases? -
Images from Model in HTML Django 1.10
I am new to Django (1.10) so please excuse me. I am trying to visualise images from my model Clothes. Trying to create some sort of small webshop to train. My Model: from __future__ import unicode_literals from django.db import models from django.utils import timezone class Clothes(models.Model): user = models.ForeignKey('auth.User') title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to = '/pic_folder/', default = '/pic_folder/None/no-img.jpg') type_clothes = models.CharField(max_length=100) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) class Meta: verbose_name = "Kleding" verbose_name_plural = "Kleding" def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Views.py from django.shortcuts import render from django.utils import timezone from .models import Clothes def clothes_overview(request): clothes= Clothes.objects.filter(published_date__lte=timezone.now()) return render(request, 'Clothes/clothes_overview.html', {'clothes' : clothes}) clothes_overview.html {% load staticfiles %} <html> <head> <title>WebShop</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/clothes.css' %}"> </head> <body> <div> <h1><a href="/">Clothing WebShop</a></h1> </div> {% for cloth in clothes %} <div> <p>published: {{ cloth.published_date }}</p> <h1><a href="">{{ cloth.title }}</a></h1> // DISPLAY IMAGE HERE <p>{{ cloth.text|linebreaksbr }}</p> </div> {% endfor %} </body> </html> I have tried one option which I came across by searching Stack: <img src="{{ cloth.image.url }}"> This helped others but still left my page showing broken images. I looked … -
Django-Postman /messages/ only loads my base.html
I have url(r'^messages/', include('postman.urls', namespace='postman', app_name='postman')), in my urls.py and 'postman', in my INSTALLED_APPS but when I go to 127.0.0.1:8000/messages/inbox all I can see is my base.html contents. This is also the case when I View Page Source. The only change I have made to the postman directory is the first line of the file: postman/base.html: {% extends "myapp/base.html" %}{# CHANGED THIS LINE #} {% load i18n static %}{% load postman_tags %} {% block title %}{% trans "Messaging" %}{% endblock %} {% block extrahead %}{{ block.super }} <link type="text/css" media="all" rel="stylesheet" href="{% static 'postman/css/postman.css' %}" /> {% endblock %} {% block postman_menu %} <ul id="postman_menu">{% postman_unread as unread_count %} <li><a href="{% url 'postman:inbox' %}">&raquo;&nbsp;{% trans "Inbox" %}{% if unread_count %} <strong>({{ unread_count }})</strong>{% endif %}</a></li> <li><a href="{% url 'postman:sent' %}">&raquo;&nbsp;{% trans "Sent Messages" %}</a></li> <li><a href="{% url 'postman:write' %}">&raquo;&nbsp;{% trans "Write" %}</a></li> <li><a href="{% url 'postman:archives' %}">&raquo;&nbsp;{% trans "Archives" %}</a></li> <li><a href="{% url 'postman:trash' %}">&raquo;&nbsp;{% trans "Trash" %}</a></li> </ul> {% endblock %} Have I missed something? -
Testing a poll app using Django test client
I am trying to test a poll app using the Django test client. In this test I create a POST request that mocks a vote on the poll and then checks both the status_code of the response (to check that I have been redirected) and verifies the number of votes has increased. So from what I have read I ended up having this: from django.test import Client from django.test import TestCase from mysite.polls.models import Poll, Choice class PollTest(TestCase): def test_voting(self): client = Client() # Perform a vote on the poll by mocking a POST request. response = client.post('/polls/1/vote/', {'choice': '1',}) # In the vote view we redirect the user, so check the # response status code is 302. self.assertEqual(response.status_code, 302) # Get the choice and check there is now one vote. choice = Choice.objects.get(pk=1) self.assertEqual(choice.votes, 1) The first issue that I had, after running python manage.py test was that I had to change the response status code to 405, when it should be 302, because after choosing the vote and clicking on the vote button, I get redirected to /polls/1/results. Moreover, the vote is actually not being registered, as after changing the response status code, just to see whether atleast … -
Make django code run after page load
So I would like for the python code in the web page to run once a second and update the page if the database has been changed but it only does it on page load due to how django works. function refresh(){ //Clear info boxes {% for TrackedObject in allTrackedObjects %} //Add info to boxes {% endfor %} } window.setInterval(refresh,1000); Is there a way for the call from setInterval to run the python code again as well?