Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Status Code Djanto Rest Framework (6xx)
How can I create a Custom Status Code in DRF, type: Status: 601 Message: Custom Message Is there any way to do it without rewriting the Framework file? -
Display data from Django database
I am trying to display data from mysql database. I have already uploaded data to database using django admin: enter image description here This is my models.py: from django.db import models # Create your models here. class Newsform(models.Model): headline = models.CharField(max_length=50) description = models.CharField(max_length=100, default='') content = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='news_image', blank=True) views.py: from django.shortcuts import render from blog.models import Newsform def first(request): return render(request, 'blog/index.html') def show_content_from_database(request): headline_news=Newsform.objects.all() context = { 'headline_news': headline_news } return render(request, 'blog/index.html', context) index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{ headline_news.headline }}</h1> <img src="{{ headline_news.image }}"> </body> </html> I have blank page as a result. What's wrong? -
how to use select option tags as an input in html using Django for backend
I have a simple form. This form consist of two inputs. Those inputs are post_city, and Category. Each one of them is a list. each list has a preselected choice, I want to use these selected items as an input for the form. It seems easy, but unfortunately, I could not figure it out. any body has an idea?. Note: I want to keep dropdown items, so the user can change the preselected choice to another, and using javascript the search will updated dynamically. Here is the html form for one select option: <form id="h_form" method="GET" action="{% url 'search' %}"> <span> <li class=""> <select id="post_city" form="h_form" class="" onchange="this.form.submit()" > {% for city in cities %} <option value="{{city.city_name}}"> {{city.city_name}} </option> {% endfor %} </select> </li> </span> -
Django (django_tables2) ValueError: Expected table or queryset, not str + for loop issue
I have a Django project that is heavily influenced by Mozilla's Django tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website). I have modified the books to samples, and each of these samples is affiliated with a researcher/pi (aka author). I created a separate model called Variant which is a a foreignkey for the Sample model. As this field will allow multiple variants for each sample, when looking at a detail view of a sample, I would like to display the variants (specific to an individual sample) as a rendered table. I have not been successful in achieving this and I think I am just not quite getting the view nomenclature correct (as well as the language in the html file). My questions are at the end of this post. Here is my code. samples/models.py class Variant(models.Model): gene = models.CharField('Gene', max_length=100, blank=True, default='') variant = models.CharField('Variant', max_length=50, blank=True, default='') call = models.CharField('Call', max_length=100, blank=True, default='') position = models.IntegerField('Position', blank=True, null=True) def __str__(self): return f'{self.gene}, {self.position}, {self.variant}, {self.call}' class Sample(models.Model): sample_name = models.CharField('Sample', max_length=16) pi = models.ForeignKey(PI, on_delete=models.SET_NULL, null=True) sample_variant = models.ForeignKey(Variant, on_delete=models.SET_NULL, null=True) . . . def __str__(self): return self.sample_name def get_absolute_url(self): return reverse('sample-detail', args=[str(self.id)]) tables.py class SampleTable(tables.Table): sample_name = tables.LinkColumn('sample-detail', args=[A('pk')]) pi = tables.LinkColumn('sample-detail', args=[A('pk')]) class β¦ -
What are read_only, read-write fields and serializers in django rest framework?
When writing a serializer in DRF for example like the below: class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') what does read_only attribute do here? and there is something as read_only serializer, what is that? -
Get Value of Foreign Key in Django-rest Serializer
I am trying to get value of foreign key , but i am only getting id, my code below Model: class DocumentType(models.Model): """Model for type of documents type system is indexing""" title = models.CharField(max_length=255, null=False) def __str__(self): return "{}".format(self.title) class DocumentsCount(models.Model): """Model for type of documents count system is indexing""" document_type = models.ForeignKey(DocumentType, on_delete=models.CASCADE, related_name='doc_title') count = models.IntegerField(default=0) def __str__(self): return "{}".format(self.document_type) Serializer class DocumentCountsSerializer(serializers.ModelSerializer): title = serializers.ReadOnlyField(source="DocumentType.title") class Meta: model = DocumentsCount fields = "__all__" Out put I am getting from API { "id": 5, "count": 2, "document_type": 3 } document_type should be title , but i am getting ID this is query queryset = DocumentsCount.objects.select_related('document_type') I am not sure what did I did wrong, I am in fact getting ID and Title when u print queryset and run in sqlite -
Adding Google Directions Service and Display as parameters in a function call inside a JavaScript String
I'm trying to add a button with an onclick function to a google maps marker's infoWindow. Said function triggers a request to the Directions Service to obtain and display the route between the user position and the selected marker. It takes directionsService, directionsDisplay and the lat/lng of the marker as parameters. At first I was doing something like this: ...+'<button onclick="calculateAndDisplayRoute( {'+directionsService+','+directionsDisplay+','+venue_position+')">Ir!</button>'+... But because of string concatenation directionsService and directionsDisplay are casted to string, always resulting in an uncaught syntax error when triggering the function. I also tried defining a format function, like this: String.prototype.format = function () { var i = 0, args = arguments; return this.replace(/{}/g, function () { return typeof args[i] != 'undefined' ? args[i++] : ''; }); }; And then: ...+'<button onclick="calculateAndDisplayRoute( {}, {},'+venue_position+')">Ir!</button>'.format(directionsService, directionsDisplay)+... But that didn't work either, both variables appear as empty in the function. So basically I don't know how to add both parameters to the string without them being casted to String. I'm fairly new to JavaScript so I might be overlooking something obvious. Here's the code of the full template (I'm working with Django): https://pastebin.com/8rhTGPXA Thanks in advance. -
Caching a QuerySet in Python while still using filter()
Here is a simplified version of my problem: I have the model Person and I need all items of that object in my views.py serveral times (on each request of that page once). My view is hence evaluating Person.objects.all() many times, which is why I want to cache this value. But I can not cache the page via @cache_page(timeout) I tried: core.cache from django.core.cache import cache cached_persons = Person.objects.all() cache.set('key', cached_persons) The problem with this is, that cached_persons is not evaluated - which defeats the purpose of caching. If I try to evaluate it via: from django.core.cache import cache cached_persons = list(Person.objects.all()) cache.set('key', cached_persons) I can not use the values normally: cached_persons = cache.get('key') cached_persons.filter(name="Jon Doe") >>> AttributeError: 'list' object has no attribute 'filter' I've read in the docs that using the following method would evaluate the query: from django.core.cache import cache cached_persons = Person.objects.all() [entry for entry in cached_persons] cache.set('key', cached_persons) But it seems, that the evaluation is only done for this one request, not for the many requests, which is probably why the django-debug-toolbar revealed no difference and I got no real timing benefit. cached_property Using the @cached_property-decorator did not help me as well. [models.py] class Person(models.Model): ... β¦ -
update a QuerySet with a Form or ModelForm
I'm trying to update all the values of a queryset with a for, I found this method : queryset = Query.objects.filter(version=XXX) field1 = ModelForm.cleaned['field1'] ... fieldN = ModelForm.cleaned['fieldN'] queryset.update(['field1'=field1, ... , 'fieldN'=fieldN]) but I fell like it's not a very clean method, is there a more efficient one ? -
Django rest framework - API view complains about NoneType response
I am using a ModelViewSet to create objects from parameters received in a POST request. The serialiser looks like this: class FooSerializer(ModelSerializer): class Meta: model = Foo fields = '__all__' I want to intercept the request, and perform a check on it (against a method of the model, if it matters) before allowing the creation to continue. In vanilla django forms, I would override the form_valid method, do the check, and then call super().form_valid(...). I am trying to do the same here: class BookingView(ModelViewSet): queryset = DirectBooking.objects.all() serializer_class = DirectBookingSerializer def create(self, request): print(request.data) #Perform check here super().create(request) This works, in the sense that it creates an object in the DB, but the trace shows an error: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` This seems strange, as I would expect the super().save to return the appropriate response. I am aware that I will need to return a response myself if the check fails (probably a 400), but I would still like to understand why it is failing here. -
Updating puppet manifests files via django web application
I'm looking for some advice because I have no idea how to approach this subject. In general I want to create web application using python Django Web Framework from which I will be able to update Puppet MANIFESTS on Puppet-Master server. Is exists any REST API delivered by PuppetLabs which will be a good for this problem? Any other solution i.e. python package for this specific problem? Or maybe the best option is to done this by uploading and appending files via SSH? -
How can I save my formwizard before the final step?
I'm playing around with formwizard and I have got it working pretty well. I am trying to allow my users to SAVE a particular form in its entirety during any step of the formwizard. I can't seem to find any examples of this anywhere. Is there anyway to call the WizardView's Done method before finishing all the form steps? Any help would be much appreciated! -
Accessing form elements in django views
this is my html form : <form method="post" name="crossDayForm" action='{% url 'crossDayGolden' %}'> Query : <input type="text" name="query" required> <input type="date" name="date1" required> <input type="date" name="date2" required> <input type=submit value="Go" > </form> I want to know how to get query,date1,date2 in my views? -
Which authorization grant type should I use?
In my application, I have many companies accounts. I'm using django-oauth-toolkit and I gonna to add access to my API by request from a specific company. I have a few endpoints like: GET /api/users/ - return all company users GET /api/documents/ - return all documents owned by users from given company I wonder which authorization grant type should I use: Client type: Confidential Authorization grant type options: client credentials authorization code resource owner password-based implicit Can anyone tell me which one type is the best in my case and why? -
How to access counter dict value from template language in django
I coded a view that renders a list of objects that have status avaiable : status='a' and i want to display next to the object name the count of avaiable instances my View.py : from collections import Counter def Borrow(request): """View for books marked as Avaiable""" avaiable_list = BookInstance.objects.filter(status__exact='a') title_list = [instance.book.title for instance in avaiable_list] counter = Counter(title_list) print(counter) display_list = {instance.book for instance in avaiable_list} context = { 'avaiable_list': avaiable_list, 'title_list': title_list, 'counter': counter, 'display_list': display_list } return render(request, 'catalog/borrow_list.html', context=context) Basically it is rendering non repeating list of objects(display_list) and the counter counts all the titles that are avaiable. My question is how i can access proper value from counter in template : {% extends "base_generic.html" %} {% block content %} <h1>Book List avaiable for borrowing.</h1> {% if display_list %} <ul> {% for book in display_list %} <li> <a href="{{ book.get_absolute_url }}">{{ book.title }}</a> ({{book.author}}) (Number of copies avaiable : {{counter[book]}} ) </li> {% endfor %} {% if user.is_staff %} <div> <a href="{% url 'book_create' %}" class='btn btn-dark'>ADD NEW BOOK</a> </div> {% endif %} </ul> {% else %} <p>There are no books avaiable for borrowing.</p> {% endif %} {% endblock %} {{counter[book]}} is returning error : TemplateSyntaxError β¦ -
Django cannot autoreload my app code as a subpackage of my project code
When I put the app code inside directory where my project code lives, the builtin server of django cannot reload the app code as I modified it. The directory structure is: . βββ db.sqlite3 βββ manage.py βββ paperinfo βββ info β βββ admin.py β βββ apps.py βββ __init__.py where paperinfo is the project and info is the app. The server also reported this error: [2018-10-18 10:20:22,394 pyinotify ERROR] The pathname '<some path>/paperinfo/paperinfo/info/models.py' of this watch <Watch wd=135 path=<some path>/paperinfo/paperinfo/info/models.py mask=4038 proc_fun=None auto_add=False exclude_filter=<function WatchManager.<lambda> at 0x7f48a69d66a8> dir=False > has probably changed and couldn't be updated, so it cannot be trusted anymore. To fix this error move directories/files only between watched parents directories, in this case e.g. put a watch on '<some path>/paperinfo/paperinfo/info'. Performing system checks... The log sounds like asking me to move files or add some watches, but I'd like to keep the directory structure unchanged and don't know how to add watches. In the tutorial of the document of django, they ask you to put code one level up and that fixes. But I don't want to do that. I am looking for some settings to tweak this. -
Wkhtmltopdf - different sizes on development and production server
I use wkhtmltopdf (in fact django-wkhtmltopdf) to generate PDF. I have to use xvfb because we need to run it on production server Ubuntu 16.04 too. The problem is that for example tables have different sizes on production and on development server and the text color is different too. On both servers it runs this way: settings.py WKHTMLTOPDF_CMD=xvfb-run --server-args="-screen 0, 1024x768x24" /usr/local/bin/wkhtmltopdf --zoom 1.04 development Ubuntu 18.04 production Ubuntu 16.04 Do you know what is wrong or how to debug this? -
A Model with more than One Serializer using Django ORM?
Using Django - Sample Model : Class sample(models.Model): field1 = models.IntegerField(null=True, blank=True) field2 = models.IntegerField(null=True, blank=True) field3 = models.IntegerField(null=True, blank=True) field4 = models.IntegerField(null=True, blank=True) class Serializer1(ModelSerializer): class Meta: model = models.sample fields = ('id','field1','field2') class Serializer2(ModelSerializer): class Meta: model = models.sample fields = ('id','field3','field4') How can we achieve deserialzing of model objects with more than one way ? -
get current user for 'created_by' field in model class
I'm currently working on a Django app, and I'm trying to set the current user as default on a model, but it doesn't work. created_by = models.ForeignKey(User, default=request.user, null=True, blank=True, on_delete=models.DO_NOTHING, related_name='created_by') I tried to override the save() method but it doesn't work either, anyone has any experience on this matter ? Thanks a lot in advance for your help -
Django inactivity timer
Django 1.11.8 I have to logout users that close the browser (or tab) without waiting the expire time session (there is one limit for number of the users online). I can't solve with SESSION_EXPIRE_AT_BROWSER_CLOSE = True ,it doesn't delete the sesssion. My idea is to add an inactivity timer on the server side for each user session, but I didn't find solutions or some examples about it. Do you have suggestions how to implement this with django server? Would be one a good idea? -
Python overriding operators with lists
I'm new to python and found some object lists while using djnago queries like querysetObj = [obj1,obj2] queryset=[obj1,obj3,obj4] for obj in querysetObj: queryset|=obj queryset=[obj1,obj2,obj3,obj4]#it acts like a set compare objects and add none repeated objects only I want to know how to do the same design with other objects "my own classes", is this related to operators overloading like c++ and if so , how to do this? -
How to pass variable in url to Django List View
I have a Django generic List View that I want to filter based on the value entered into the URL. For example, when someone enters mysite.com/defaults/41 I want the view to filter all of the values matching 41. I have come accross a few ways of doing this with function based views, but not class based Django views. I have tried: views.py class DefaultsListView(LoginRequiredMixin,ListView): model = models.DefaultDMLSProcessParams template_name = 'defaults_list.html' login_url = 'login' def get_queryset(self): return models.DefaultDMLSProcessParams.objects.filter(device=self.kwargs[device]) urls.py path('<int:device>', DefaultsListView.as_view(), name='Default_Listview'), -
Django ,How to show image on the board in templates?
I want to use like this I'm making a bulltein board like the image. I can show image in detail page. But i can't show image bulletin board list(index page). How do I add images to the bulletin board list? toy/models.py class NewBornProduct(models.Model): type = models.ForeignKey(Type,on_delete=models.PROTECT) name = models.CharField(,max_length=30) content = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) price = models.IntegerField(null=False) class NewBornProductImage(models.Model): product = models.ForeignKey(NewBornProduct,on_delete=models.CASCADE) image = models.ImageField(upload_to="newborn/%Y/%m/%d") def delete(self, using=None, keep_parents=False): self.image.delete() return models.Model.delete(self, using=using, keep_parents=keep_parents) toy/views.py def newborn(request): obj = NewBornProduct.objects.all() return render(request,'toy/newborn.html',{'obj':obj}) toy/newborn.html {% for post in obj %} <tr> <th>{{post.id}}</th> <th> i want to show image here!</th> <-------- Here! <th> <a href="{% url 'toy:newborndetail' post.id %}">{{post.name}}</a> </th> <th>{{post.price}}</th> <th>{{post.amount}}</th> <th>{{post.pub_date}}</th> </tr> {% endfor %} I do not know how to call the image because the other is fine Do you have any ideas? -
Django-admin: AdminDateWidget shows icons twice
I've created a new custom page inside Django-admin. I use there Django-admin's datepicker. Datepicker works fine but it renders calendar icon and "today" href twice: Do you how to fix it without using additional JS or CSS? FORM class RequestAuditReportForm(forms.Form): date_from = forms.DateField(widget=AdminDateWidget()) date_to = forms.DateField(widget=AdminDateWidget()) VIEW class RequestAdminReportView(FormView): template_name = "main/reports/audit.html" form_class = RequestAuditReportForm def get_context_data(self, **kwargs): context = super().get_context_data() context.update({'opts': AuditOrder._meta, 'is_popup': False, 'has_permission': True}) return context TEMPLATE {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_list %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static "admin/css/changelists.css" %}"> {% if cl.formset %} <link rel="stylesheet" type="text/css" href="{% static "admin/css/forms.css" %}"> {% endif %} {% if cl.formset or action_form %} <script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script> {% endif %} {{ media.css }} {% if not actions_on_top and not actions_on_bottom %} <style> #changelist table thead th:first-child { width: inherit } </style> {% endif %} {% endblock %} {% block extrahead %} strong text {{ block.super }} {{ media.js }} <script type="text/javascript" src="/admin/jsi18n/"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script> {# <script type="text/javascript" src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>#} <link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/> <link rel="stylesheet" type="text/css" href="{% β¦ -
Group the django object according to the foreign key
I want to group the model object according to the foreign key with a query or without any iteration. example: Let, I have a model student: class student(modela.Model): id=models.AutoField(primary_key=True) parentId=models.ForeignKey() name=models.charField() age=models.IntegerField() Here I want to create the group the student object with respect to the parentId using a query or any optimized way.