Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to patch multiple objects for a common resource
I have a common resource which I can use to fetch all the api. I want to use the same(or create new one) to patch all the data. Note, I can create new one too, it just needs to work. How to do that ? class AllResource(NamespacedModelResource): user = fields.ForeignKey(UserResource, 'user', null=True, blank=True) related1 = fields.ToManyField( RelatedResource1, 'some1_set', full=True, null=True, blank=True) related2 = fields.ToManyField( RelatedResource2, 'some2_set', full=True, null=True, blank=True) related3 = fields.ToManyField( RelatedResource3, 'some3_set', full=True, null=True, blank=True) class Meta: queryset = Some.objects.all() resource_name = 'all' authentication = ApiKeyAuthentication() authorization = SomeAuthorization() detail_uri_name = 'guid' -
Django template tags- run once and use that value
I have a loop in a template: {% for item in replies %} .... {% include '...show_content.html' with poall=item.limited_content_chunks %} In the model I have a function/property which computes something I want to compute once. Problem is this gets called every time there is a page refresh. Whats the most effective way of solving this problem? I could create dictionary of pre-computed chunks for each reply in replies and send it as a context object, or I could... def limited_content_chunks(self, percentage=None): if not self.content and self.po_file: # do crazy stuff which could might lead to a nuclear war .... return ' '.join(chunks) -
Django UserCreationForm Error: ModelForm has no model class specified
I'm trying to create a page for is_staff folks can create users. The code is below. views.py @login_required def create_new_user(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('jobs:new-user')) else: form = CreateUserForm() return render(request, 'jobs/create_user.html', {'form': form}) forms.py from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CreateUserForm(UserCreationForm): class Meta: model: User fields = ['username', 'password1', 'password2'] error output This is the error I get when I try to access the account creation page. Traceback: File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/jobs/views.py" in create_new_user 124. form = CreateUserForm() File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/contrib/auth/forms.py" in __init__ 96. super(UserCreationForm, self).__init__(*args, **kwargs) File "/Users/joshsullivan/github/sm8_portal/env/lib/python3.6/site-packages/django/forms/models.py" in __init__ 275. raise ValueError('ModelForm has no model class specified.') Exception Type: ValueError at /create_user/ Exception Value: ModelForm has no model class specified. Any ideas? As always, THANK YOU. -
Django media urls not working
Looked over many questions but could not find a solution for my problem. I've set everything up, but still not able to access the media through its designated url. In my urls.py I have: urlpatterns = [ #site urls ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The above returns the following pattern: ^media\/(?P<path>.*)$ image.imagefield returns the following url: img/img.jpg I used <img src="{{ MEDIA_ROOT }}/{{ item.image }}"> to get the full media url, which returns: http://example.com/img/img.jpg It says Page not found (404) when I try to access the above url. My settings parameters looks like this: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' What seems to be the issue here? Any direction would be appreciated. Thanks, -
django rest api save two django models at a time through a single rest api call
I am building an django rest api for saving/managing customer data for my project. I have two models. Customer for storing basic customer details and CustomerDetails for storing a bunch of customer details. I want to write a single api to create/update data for both the models. How can I do this? models.py class Customer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=256) """some more fields to go""" # Create your models here. class CustomerDetails(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) customer = models.ForeignKey(Customer, db_index=True, on_delete=models.CASCADE, related_name='customer_details', default=0) spouse_name = models.CharField(max_length=256) interests = models.CharField(max_length=256) """many more fields to go""" views.py import pprint from .models import Customer, CustomerDetails from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope from rest_framework import permissions, viewsets from .serializers import CustomerSerializer, CustomerDetailsSerializer from django.contrib import admin from rest_framework import generics admin.autodiscover() # Create your views here. # ViewSets define the view behavior. class CustomerViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = Customer.objects.all() serializer_class = CustomerSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) class CustomerCreateAPIView(generics.CreateAPIView): model = Customer serializer_class = CustomerSerializer serializers.py from rest_framework import serializers from models import Customer, CustomerDetails class CustomerDetailsSerializer(serializers.ModelSerializer): class Meta: model = CustomerDetails fields = ('spouse_name',) class CustomerSerializer(serializers.ModelSerializer): customer_details = CustomerDetailsSerializer() class Meta: model = … -
Mysql gone away (Error 2006) in background processes on webserver
I am running a website on django 1.10, python3.4, mysqlclient, mysql5.5. I have multiple management command running in the background for various tasks (like mail sending, updating tables) at different times. Recently, I have started seeing many Mysql gone away (Error 2006). I tried to change the connection_timeout to be greater than max_connection age. That solved a small share of problem in which Error 2006 stopped to occur for a running function in most of the case but other cases are as it is and frequently seeing Error 2006. In some cases, I tried using django.db.connection.close() before running a function or putting it in try - except loop. In those places, this error are not occuring anymore but then I cannot put this try-except loop in every function. What is the root cause of this repeated error Mysql gone away? What are the different solution and what is the best solution so that I do not have to change much of my codes? Other Variables: We upgraded from django 1.7 to 1.10 and updated the mysqlclient package recently and the problem surfaced after that probably. Just around the update, the traffic on our site also increased multiple times. Can that … -
Mask URL for a Django + Ember Application
Background: I have a web-app running on my server with Django (for the backend) and Ember (for the frontend). I recently bought a domain (for example... newdomain.com) on godaddy and I am trying to mask and forward this domain name to the current URL my Django app is running on (for example... olddomain.com/app). Old URL: olddomain.com/app New URL: newdomain.com Goal: Mask olddomain.com/app with newdomain.com Issue: I put the domain name setting on godaddy as "Forward with masking" and whenever I go to newdomain.com it only forwards my URL to olddomain.com/app and never masks it. I contacted the godaddy customer service and they said it must be my server disallowing masking. Attempts to fix it: So I tried changing my apache settings at /etc/httpd/conf/httpd.conf with some suggestions online. I tried adding: <VirtualHost *:80> ServerName newdomain.com ProxyPass "/*" "http://olddomain.com/app" ProxyPassReverse "/*" "http://olddomain.com/app" </VirtualHost> But it still only forwards the URL and not mask at all. I also tried adding this to the same file and it still has the same issue as previously: RewriteEngine On RewriteCond %{HTTP_HOST} ^(.*)\.newdomain.com RewriteRule /(.*) https://olddomain.com/app [P] I also restart apache every time I do a change. Just in case if you need it, this is my … -
I get rid of class in CSS and my paragraph element wont work...WHY?
Im using Django web framework for my first project, trying to adjust my fonts. However, after various trial and error I was able to get a new font to render on my page. The problem is that when I get ride of my .font class, the p { } element no longer works for whatever reason and the font remains unchanged. I can't get my font to change any other way... I have NO idea why this is happening, driving me crazy... <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title>Test</title> <meta charset="utf-8" /> <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> <link rel="stylesheet" href="{% static 'personal/css/custom2.css' %}" type = "text/css"/> <link href="https://fonts.googleapis.com/css?family=Sansita" rel="stylesheet"> </head> <!-- header table, no text displayed --> <Br> <Br> <table align='center' width='75%' border= '0px'> <tr> <td bgcolor='transparent'> </td> </tr> s </table> <!-- main body --> <body background = "{% static 'personal/img/background.jpg' %}"> <table align='center' width='75%' border='1px'> <tr> <td bgcolor='white'> <div class="body" style="min-height:95%; "> <div class="row"> <div class="col-sm-2"> <br> <center> <img src="{% static 'personal/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face"> </center> </div> <div class="col-sm-10"> <br> <p>test paragraph</p> </div> </div> <!-- navigation bar --> <nav class="navbar navbar-inverse" > <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#"></a> </div> <ul … -
Remove duplicate in a query based on a specific field
I would like to remove duplicates from a query based on a field. I don't want to get only the values but also the objects. The ORM needs to make a choice depending on which row will be removed and which one will be kept. Let's use this example : name - date - value chris - 1/1/2012 - 12 youssef - 1/02/2015 - 13 trump - 1/8/2017 - 12 chris - 1/12/2018 - 21 trump - 1/03/2019 - 29 The output would be : name - date - value trump - 1/03/2019 - 29 chris - 1/12/2018 - 21 youssef - 1/02/2015 - 13 Basically, i want to remove the duplicates based on date order, something like (it doesn't work) : Table.objects.order_by('-date').distinct('name').order_by('-value') Can the ORM handle this query ? Or should it write a function ? -
Django Translations
I have a project with django translation, I put the tag {% trans %} around the text that I need to translate and run python manage.py makemessages but output: CommandError: Type 'manage.py help makemessages' for usage information. When a run python manage.py compilemessages works fine... I researched what could be and installed: -brew install gettext -brew link gettext --force but doesn't work. Any help? -
API monitoring tool
I wish to monitor all the APIs that I created on one of my docker containers.. That Docker container is using Django REST framework for its services.. and I am running it on Azure.. I want to monitor my API by means of if it is working or if there is too much requests it will throw an alert.. what is its request per second something like that.. We are using sysdig for monitoring our containers but I don't think it has the capability to monitor all our APIs of our Django Rest Framework -
Dajngo python, trying to send Httpresponse before to send email
I'm trying to make a contact form with python django, at this time it works perfectly, the issue is that I have to wait up to the email message already sends to get the Httpresponse. Is there any way to send the Httpresponse first and then send the email message? send_mail( 'Subject here', data['comentarios'], 'myemail@gmail.com', ['myemail@gmail.com'], fail_silently=False, ) return HttpResponse('bien') #es menor a 7 digitos Thank you ! -
How to set the default of a JSONField to empty list in Django and django-jsonfield?
Question What is the best way to set a JSONField to have the default value of a new list in django? Context There is a model where one of the fields is a list of items. In the case where there are no items set, the model should have an empty list. Current solution from django.models import Model class MyModel(Model): the_list_field = JSONField(default=[]) Is this the best way to do it? Should it be switched to use list instead? Thanks! -
Efficient way to filter a hierarchical structure in Django?
fellow djangoers. I have a simple hierarchical model, 3 turtles high. Let's say Artist, Album, Song. What would be an efficient way to filter the resulting tree in my view? I'm currently doing something like: for current_artist in Artist.objects.filter(album__song__genre='funkadelic mariachi').distinct(): yield current_artist for current_album in Album.objects.filter(song__genre='funkadelic mariachi').distinct(): yield current_album for current_song in Song.objects.filter(genre='funkadelic mariachi'): yield current_song yield 'End of album' yield 'End of artist' But I'm pretty certain there must be a much more efficient way than querying all the way to the leaves in every level, unless distinct() and Django's optimisations provide some magical cache from the other side of the rainbow. Perhaps creating a whole tree (v.g. with every artist and album, not checking for leaves), and then pruning the leafless branches? Or should I be looking at select_related()? For extra points, some actual test/benchmark/write-up would be welcome. Danke! -
Adding Q Lookup to Wagtail CMS Snippets
I am building out a restaurant website and using Wagtail CMS Snippets for the owner to manage menu items. The list of menu items are getting rather long and I was wondering if there is any way to add a search input field to the Snippets admin window? Below is an annotated screenshot for visual reference. Thank you. -
How to display an update that is pushed from the server to the webpage without a refresh?
I am using Django 1.10 as the backend. I have a webpage that will be displayed on a giant monitor. This webpage will show nothing except for 1 giant number. I have a RFID device that once detects a RFID tag, will send a http request to my Django server. When that happens, I want the number from the RFID tag to be displayed on the webpage mentioned earlier. I have read briefly about socket.io but I want to as much as possible keep within the Django universe. I have read briefly about Django Channels as well. My questions are: use Django Channels? if so, how do i do that with my use case above? -
django-1.10 still contains deprecated and removed features
I am trying to run an existing django app. The app has been built in django-1.10. I set up a new virtualenv and installed the requirements and everything. However, I get errors like the following: from django.utils import importlib ImportError: cannot import name importlib Now, the above is from the following source - .virtualenvs/crowd/lib/python2.7/site-packages/account/conf.py When I manually fix the conf.py file, I still keep getting errors to fix either deprecated or removed features from older django versions. Any idea as to how to fix this? I thought the purpose of working in virtualenvs was to avoid such errors. Any suggestions would be much appreciated. Thanks in advance! -
How can I enable foreign-key checks in pytest using sqllite
I have a django project with tests that run when I call py.test, but I've noticed recently that it isn't checking foreign key constraints. How can I get it to check foreign key constraints? Apparently, foreign key constraints weren't even possible until sqlite 3, but I don't really know what version I'm running, because I don't have a cli for sqlite, but it's just being included automatically by django? (I'm using django 1.9.10), but sqlite 3 came out in 2009, so that's not the issue right? Perhaps it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command., but I don't know how to make my tests do that? -
SQLite3 with Django, how scaleable is it?
I'm fairly new to Django and programming and trying to build my first web app which will require me to have extensive use to database. Since I'm starting my project, I'm wondering how good or scaleable is default Django database i.e. SQLite3? Do I really need to learn other databases like Postgress etc in order to have my project scaleable? I know its too early for me and most probably sqlite3 will serve my purpose but generally speaking can we scale Django default databases? -
Avoid repetition between Django ModelForm and Django Model
I'm interested is there a way to avoid repetition between Django ModelForm and Django Model. E.g. I have this simplest Model: class Category(models.Model): name = models.CharField(max_length=128) and corresponding ModelForm to it class Category(models.Model): name = models.CharField(max_length=128) class Meta: model = Category fields = ('name',) As we can see there is repetition between these entities. This code max_length=128 - does it violate "Don't repeat yourself" principle? And if it violates, how can we avoid this duplication of code? -
How to update multiple FileField at the same time in Django forms?
I have two forms in a template, so I want to update multiple imagefields that have a foreign key to Unidad model. When I click in the update button I just receive the data from the firts form but the second form in this case are multiple FileFields don't receive nothing. My Archivos model: class Archivos(models.Model): id_archivo = models.AutoField(primary_key=True) id_unidad = models.ForeignKey(Unidad, on_delete=models.CASCADE) nombre_archivo = models.CharField(max_length=255, blank=True) imagen = models.FileField(null=True, blank=True) def __str__(self): return '{}'.format(self.imagen) My view: class uniUpdate(UpdateView): model = Unidad second_model = Archivos template_name = 'back/Modulo_unidades/partial_unidad_form.html' form_class = UnidadForm second_form_class = imgForm success_url = reverse_lazy('BackEnd:unidades') def get_context_data(self, **kwargs): context = super(uniUpdate, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) solicitud = self.model.objects.get(id_unidad=pk) persona = self.second_model.objects.filter(id_unidad=solicitud.id_unidad) print(persona); if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = self.second_form_class(instance = persona) context['id'] = pk return context When I use: persona = self.second_model.objects.filter(id_unidad=solicitud.id_unidad) I have this error: 'QuerySet' object has no attribute '_meta' In this line : context['form2'] = self.second_form_class(instance = persona) The problem is that I have eleven images that are associate to only one Unidad, so I don't know how can I update multiples FileField in the same time. Please help. -
Django -Nested forloops django to create a table from csv
i imported a csv and i want to create a table from that. The csv is parsed and update_or_create function help to actualice the database. the quantities of csv's columns is variable also the rows. Then, (i think) i am forced to do two classic forloops for parse it. The problem is that not working or i am doing something wrong. the first forloops reads the headers and the second go inside each object. but i don´t know how to call the attribute of each object <table > {% for h in archivo.fieldnames %} // headers are "isbn" and "stock" {% for x in objeto_nuevo %} <tr> <td>{{h}}</td> //render "isbn", ok. <td>{{{{x}}.{{h}}}}</td> // i want object1.isbn but dont render. </tr> {% endfor %} {% endfor %} </table> thanks in advance -
Using context variables inside text inside template tag in django
I want to do something like this in my template. {% include "blogs/blogXYZ.html" %} The XYZ part should be variable. ie how can I pass a context variable to this position. For example if I am reading 1st blog, I should be able to include blog1.html. If I am reading 2nd blog, I should be able to include blog2.html and so on. Is it possible in django? -
With the python debugger, is there a way to create a set of breakpoints before calling `pdb.runcall()`?
With the python debugger, is there a way to create a set of breakpoints before calling pdb.runcall()? I took a look through the documentation and didn't see any way to create additional breakpoints or provide a .pdbrc config directly to the instance. I have this: def debug_jobs_from_lists(username, json_string, skip=None): import pdb import rlcompleter from django.core.urlresolvers import reverse from django.test.client import RequestFactory from django.contrib.auth.models import User from batsapi.multi import multi if skip is None: skip = [] rf = RequestFactory() request = rf.post( reverse('jobs-api'), data=json_string, content_type='application/json') request.user = User.objects.get(username=username) pdb_instance = pdb.Pdb(skip=['django.*'] + skip) pdb_instance.complete = rlcompleter.Completer(locals()).complete # Add breakpoint here to break in an underlying function pdb_instance.runcall(multi, request) -
Django atomically limit check and increment counter for multiple tables
I have 2 models/tables Cluster and Node, and possibly more, each having a "volume_limit" and "volume_count" field/column in it. I want to atomically check the counter against the limit in its own table and increment the counter. To atomically check and increment for just Cluster, I would do the following updated = Cluster.objects.filter(id=cluster_id, volume_count__lt==F('volume_limit')).update(volume_count = F('volume_count')+1) if not updated: raise Validation('limit reached ......') If I wanted to increment both Node and Cluster, I would add the following, which would undo the cluster increment, if I cant increment the node counter. Like below updated = Node.objects.filter(id=node_id, volume_count__lt==F('volume_limit')).update(volume_count = F('volume_count')+1) if not updated: Cluster.objects.filter(id=cluser_id).update(volume_count = F('volume_count')-1) raise Validation('limit reached ......') I am wondering if there is way to do both of this atomically? Basically I want to do the following in query/update operation create a query for Cluster and Node objects, and possible more objects, that all have "volume_count" and "volume_limit", that need to be simultaneously checked/incremented. Check that the query translates to exactly one object for each query. i.e. the counts are within limit for each object/table. That is if I am checking Cluster and node, then the query should tranlsated to only 2 object, Do a volume_count=F('volume_count')+1 for all the …