Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Prefetch returns list instead of QuerySet
According to the docs, Prefetch is used to control the operation of prefetch_related which is supposed to return a QuerySet of related objects. class Order(models.Model): ... class Route(models.Model): stops = models.ManyToManyField( Order, blank=True, through='RouteStop', related_name='routes') ... class RouteStop(CreatedUpdatedMixin): route = models.ForeignKey(Route, related_name='%(class)s_route') order = models.ForeignKey(Order, related_name='%(class)s_order') stop = models.IntegerField(blank=True, null=True) from django.db.models.query import QuerySet queryset = RouteStop.objects.select_related('order').filter( order__status__range=[1, 2]) routes = Route.objects.all().prefetch_related( Prefetch('routestop_route', queryset=queryset, to_attr='route_stops')) isinstance(routes[0].route_stops, QuerySet) >>> False The related objects above are in a list. Just wondering why that is and if there's a work around to get a queryset? For example if you wanted to dynamically create a series of inline formsets for each route the BaseInlineFormset class tries to call .filter() on the queryset which doesn't work because it's been passed a list. def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) routes = ... # see above context['routes'] = [] for route in routes: context['routes'] += [{ 'route': route, 'formset': RouteStopFormSet(instance=route, queryset=route.route_stops) }] return context Edit: prefetch_related does return a queryset as it's supposed to but what I mean is it possible to get the related objects as a queryset as well? -
Django: 'file is not a zipfile' error after migration when using manage.py
Possibly screwed up when running makemigrations to make a change to my database, and now I can't go back. Any time manage.py is run, I get the following error: ... File "/Users/Ryan/projects18/scoutingEnv/lib/python2.7/site-packages/openpyxl/reader/excel.py", line 175, in load_workbook archive = _validate_archive(filename) File "/Users/Ryan/projects18/scoutingEnv/lib/python2.7/site-packages/openpyxl/reader/excel.py", line 125, in _validate_archive archive = ZipFile(f, 'r', ZIP_DEFLATED) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 770, in __init__ self._RealGetContents() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/zipfile.py", line 811, in _RealGetContents raise BadZipfile, "File is not a zip file" zipfile.BadZipfile: File is not a zip file I would simply revert to the last migration, as that was the last thing I did before the error occurred, but I get the error anytime I use manage.py now. I found a similar question here but no solution was posted. Anyone know what I can do to solve this? Thanks. -
Model with more than one ForeignKey, ForeignKey can be more than one for one Model
So to make the above possible I have found out that I have to have ManytoMany Field that is not a problem. That field is in the form as follows: widgets = { 'scan': forms.CheckboxSelectMultiple(), 'test': forms.CheckboxSelectMultiple() } In the view I have this then: from = Form(request.POST) if doc_aide_from.is_valid(): inst = from.save(commit=False) inst.something = something inst.save() Now what do I do, to save the test or scan from the form? I tried : inst.test.add(form.cleaned_data['test']) But that doesn't work for test or scan. The Model looks like this: class DocAide(models.Model): id = models.AutoField(primary_key=True) scan = models.ForeignKey(Scan, on_delete=models.CASCADE, blank=True, null=True) .... Please help I wasn't able find anything in the Internet about this Thanks! -
Added new field to model // Admin does not reflect this
I am using Django 2.1, and I modified one of my models (added one more field). I did the migrations, everything went well. I can see (in my database) that the field has been added. Now if I open the admin interface, go to the modified table / entity, it does now show the newly added field. What am I missing? This question has been asked in 2011 on SO here, but there is no answer that would solve my problem. -
Extend django-import-export's import form to specify fixed value for each imported row
I am using django-import-export 1.0.1 with admin integration in Django 2.1.1. I have two models from django.db import models class Sector(models.Model): code = models.CharField(max_length=30, primary_key=True) class Location(models.Model): code = models.CharField(max_length=30, primary_key=True) sector = ForeignKey(Sector, on_delete=models.CASCADE, related_name='locations') and they can be imported/exported just fine using model resources from import_export import resources from import_export.fields import Field from import_export.widgets import ForeignKeyWidget class SectorResource(resources.ModelResource): code = Field(attribute='code', column_name='Sector') class Meta: model = Sector import_id_fields = ('code',) class LocationResource(resources.ModelResource): code = Field(attribute='code', column_name='Location') sector = Field(attribute='sector', column_name='Sector', widget=ForeignKeyWidget(Sector, 'code')) class Meta: model = Location import_id_fields = ('code',) and import/export actions can be integrated into the admin by from django.contrib import admin from import_export.admin import ImportExportModelAdmin class SectorAdmin(ImportExportModelAdmin): resource_class = SectorResource class LocationAdmin(ImportExportModelAdmin): resource_class = LocationResource admin.site.register(Sector, SectorAdmin) admin.site.register(Location, LocationAdmin) For Reasons™, I would like to change this set-up so that a spreadsheet of Locations which does not contain a Sector column can be imported; the value of sector (for each imported row) should be taken from an extra field on the ImportForm in the admin. Such a field can indeed be added by overriding import_action on the ModelAdmin as described in Extending the admin import form for django import_export. The next step, to use this … -
Django views.static in urls?
I'm trying to setup Sphinx with Django. Sphinx generates the html files, and links between them based on file/directory structure. Since Sphinx only generates static files, I have to setup my urls with django.views.static urls.py from django.contrib import admin from django.conf import settings from django.urls import path from django.views import static urlpatterns = [ path('admin/', admin.site.urls), path('', static.serve, {'document_root': settings.DOCS_ROOT, 'path': 'index.html'}, name='index'), path('(<path>.html)', static.serve, {'document_root': settings.DOCS_ROOT}, name='static.file.serve'), ] This serves the index.html just fine, but returns 404 on other templates. -
Showing iframe element in Django admin view
I have been trying to add a simple view to Django's admin site, like so # collection_management/admin.py class MyAdminSite(admin.AdminSite): ... def plasmid_map_view(self, request): return render(request, 'admin/collection_management/plasmid_map.html') ... It uses a template, which contains an iframe element that loads an external url # templates/admin/collection_management/plasmid_map.html ... {% block content %}<div id="content-main"> <iframe style="height: 80vh; width: 100%; resize: both; overflow: auto; border:None;" src="https://designer.genomecompiler.com/plasmid_iframe?file_url=http://s3.amazonaws.com/gcc_production/plasmid_viewer/OG34_OG34_pSF-OXB19.gb"> </iframe> </div> {% endblock %} ... When I try to load the page, I get a strange behaviour whereby Django prepends the "root" url of my site (example.net:8443) to the address that should be opened inside the iframe, which obviously does not exist https://example.net:8443/collection_management/plasmid_map/%E2%80%8Bhttps:/designer.genomecompiler.com/plasmid_iframe?file_url=http://s3.amazonaws.com/gcc_production/plasmid_viewer/OG34_OG34_pSF-OXB19.gb%E2%80%8B How can I prevent Django from doing that? -
Django How to get id of model into view and send it through url?
I read the documentation of poll app i am trying to make a url with driver id send in url . i tried ways but not worked for me . kindly tell me the easy solution i am beginner in development in django. Views.py def rentacar_list(request, page_number=1): print(Template) menu_config_list = MenuItemRentacarList.objects.all()[0] menu_config = MenuItemRentacarList.objects.get(id=menu_config_list.id) all_cars = Car.objects.all().order_by('-id') if menu_config.menu_item_rentacar_list_show_unavailable == 0: all_cars = all_cars.exclude(car_available=0) else: all_cars = all_cars cars_page = Paginator(all_cars, menu_config.menu_item_rentacar_list_pagination) args['cars'] = cars_page.page(page_number) template = Template.objects.get(template_default__exact=1) args['main_menu'] = MenuMenu.objects.get(id__exact=template.template_main_menu_id) args['menu_items'] = MenuItem.objects.filter( menu_item_menu=args['main_menu'], menu_item_published=1, ) template_page = template.template_alias + str("/rentacar/rentacar_cars_list.html") args['current_menu_item'] = menu_config.menu_item_rentacar_list_menu_item all_modules = Module.objects.filter( module_show_option__exact='all', module_published=1 ) selected_modules = Module.objects.filter( module_show_option__exact='selected', module_published=1, module_menu_item=args['current_menu_item'] ) excluded_modules = Module.objects.filter( module_show_option__exact='except', module_published=1, ).exclude( module_menu_item=args['current_menu_item'] ) args['modules'] = list(chain(all_modules, selected_modules, excluded_modules)) return render(request, template_page, args) Urls.py url(r'^rentacar/list/(\d+)/$', extension_views.rentacar_list), how do i pass django id into the url . -
Django Model Foreign Key Database Column Order
I use Django 2.1, PostgreSQL 10.5 and Django migration tool. As can be seen in this post - Django Migration Database Column Order there is no way to define database columns order after first migration. But what about ForeingKey fields? They placed at end of database table even in first migration. In first migration, ForeingKey not contains in CreateModel section with other fields, ForeingKey placed separately with migrations.AddField at the end of file. At that if edit migration manually and move ForeingKey to CreateModel section - all works perfectly with any columns order. So, the question - how save order of ForeingKey field in first migration automaticly (without manually editing migration file, just using manage.py makemigrations)? -
When I use HttpResponseRedirect I get TypeError: quote_from_bytes() expected bytes in Django
When trying to implement a custom get_success_url method in python, Django throws a TypeError: quote_from_bytes()error. For example: class SomeView(generic.CreateView): #... def get_success_url(self): return HttpResponseRedirect(reverse('index')) -
Call Django function with argument in html
im pretty new to django and try to call a django function in html to display how many objects of 'Akte' is in the respective 'Charge' object, but somehow im missing the right way to do it. models.py: class Charge(models.Model): STATI = ( ('O','Offen'), ('G','Geschlossen'), ) "Projektnr = models.CharField(max_length=30)" Containernr = models.CharField(max_length=30) Plombennr = models.CharField(max_length=30) status = models.CharField(max_length=1, choices=STATI) def __str__(self): return self.Containernr class Akte(models.Model): Aktenbarcode = models.CharField(max_length=30) "Eincheckdatum = models.datetime()" user = models.CharField(max_length=30) containerId = models.ForeignKey(Charge,on_delete=models.CASCADE) kundennr = models.CharField(max_length=30) Startdatum = models.DateField(auto_now_add=True) def __str__(self): return self.Aktenbarcode and this is my views.py: def tabelle(request): assert isinstance(request, HttpRequest) charge_list = Charge.objects.all() return render( request, 'app/tabelle.html', { 'charge_list':charge_list, } ) def anzahl(containernr): return {'anzahl': Akte.objects.filter(containerId__Containernr==containernr).count } and here is the html code: {% extends "app/ats.html" %} {% block content %} {% if not user.is_anonymous %} <div style="margin-left:10%;color:white;"><a style="color:white"href="{% url 'home'%}">Home</a> ><a style="color:white"> Tabellenübersicht</a></div> <div> <table> <tr> <th>Containernummer</th> <th>Status</th> <th>Anzahl Akten</th> <th>Plombennummer</th> <th></th> </tr> {%for Charge in charge_list%} <tr> <td>{{Charge.Containernr}}</td> <td>{{Charge.status}}</td> <td>{% anzahl Charge.Containernr %}</td> <td>{{Charge.Plombennr}}</td> </tr> {% endfor %} </table> </div> {% endif %} {% endblock %} when i try it i always get this error: TemplateSyntaxError at /tabelle Invalid block tag on line 19: 'anzahl(Charge.Containernr)', expected 'empty' or 'endfor'. Did you … -
Find the field that connects a model to a "through" model
Lets say I have models defined as: # The class that I will have the instance of. class A(models.Model): somefieldA = models.TextField() m2mfield = models.ManyToManyField(B, through='AandB') def __unicode__(self): return self.somefieldA # The model that participates in the m2m field. class B(models.Model): somefieldB = models.TextField() def __unicode__(self): return self.somefieldB # Model that stores the extra information # about the m2m rel. class AandB(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) field1 = models.DecimalField() field2 = models.TextField() field3 = models.DateField() My requirement is to iterate through all the objects in the model AandB. I know that I can do that through (details here): # I have the instance of model A for field in instance._meta.get_fields(include_hidden=True): if field.many_to_one: mgr = getattr(instance, field.get_accessor_name()) for obj in mgr.all(): # Do stuff here. My question is, is there any way I can get the field name through which AandB model is linked to model A? (Which in this case would be m2mfield). -
Cannot login using email in django
I am trying to login using email instead of username in django, but it is not working. I am not getting any error also. I also looked up solution for solutions in stackoverflow and other blogs/post also but not getting the output. Can you please review my code where I am wrong/ modification needed. Any suggestions or changes are welcome. Here is my code: models.py from django.db import models from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email,password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, … -
Select2 and django_filters not querying foreign keys
I'm using django_filters for an advanced search and select2Widget to display the options of a foreign key field. The proper values load but whenever I submit the form I get an error message: Select a valid choice. That choice is not one of the available choices. The error might seem pretty obvious but I can't find out how to solve it. Any suggestions? filters.py class MyFilter(django_filters.FilterSet): b = django_filters.ModelChoiceFilter( queryset=ModelA.objects.values_list('b__name', flat=True) widget=Select2Widget() ) class Meta: model = A fields = ('b',) models.py class ModelA(models.Model): b = models.ForeignKey('ModelB', on_delete=models.CASCADE) class ModelB(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name -
Django Returns Not Found on Production Server
I'm trying to deploy my code on digitalocean vps server and I checked everything million times but I still have the same problem. When I try to access admin page it works but I cannot access any other page.I am not running django code local it's running on a public ip. Can anyone help me with it ? Here is my main urls. py file: from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls'), name='rest_framework'), path('posts/', include('posts.urls')), path('dictionary/', include('dictionary.urls')), ] -
Django rest framework cache list method response based on query_params
I am using django rest framework to model api views. I have and API ModelViewSet class which has two action methods: list() and retrieve() retrieve() method example: @method_decorator(never_cache) def retrieve(self, request, *args, **kwargs): ... return Response(some_data) list() method example: @method_decorator(cache_page(settings.PAIR_CACHE_LIFETIME)) def list(self, request, *args, **kwargs): ... return Response(some_data) When the GET request is sent to /en/api/v1/pair - it call list method which is decorated to cache response. When the GET request is sent to /en/api/v1/pair/ - it calls retrieve method which is decorated to never_cache. I am adding the feature to return random pair, when GET request is sent to /en/api/v1/pair/?name=random. But as it calls list method, the return is cached for some time and return the same response for a while. What would be the way NOT to cache response in list() method, when /en/api/v1/pair/?name=random endpoint is called, but it should cache whatever else is called in list method. Thank you! -
using sum() to find the aggregated price in a list of items
i have a list of items "display_list" which contains products, these products have a field called "proprice" in them which is the price of product in the list. If i have a display list with 2 apples and a banana for example i want to work out the aggregate price of the 2 apples and bannana, how would i go about doing this? i have currently tried total = sum([(pro.proprice for pro in display_list)]) but this isnt working, would anyone be able to lend a hand? Thanks in advance -
urlpatterns += (static(settings.STATIC_URL,ducoment_root=settings.STATIC_ROOT))
Why we use this urls.py urlpatterns += \ (static(settings.STATIC_URL,ducoment_root=settings.STATIC_ROOT)) some one explain please thanks -
Django; POST request doesn't work when I try to submit invalid data
I found out error message doesn't show up for some forms so I tried to do like this. def add_entry(request): if request.method != 'POST': form = EntryForm(user=request.user) else: form = EntryForm(request.POST, user=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse_lazy('blog:list_entry')) else: print("error happened.") context = { 'form': form, } return render(request, 'blog/add_entry.html', context) and even when I tried to submit invalid data, it didn't output anything. html <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.description.errors }} <label>{{ form.description.label }}</label> {{ form.description|add_class:'form-control' }} </div> <button type="submit" class="btn btn-primary">Post</button> </form> When I submit valid data, the form does work. What am I wrong with this? -
Why does Paho MQTT client initialize two connections?
I am using Django and MQTT client. I want to run MQTT client at the background and the client immediately after the Django app is ready so I have this code: ###mysite/app/apps.py from django.apps import AppConfig class TimetableConfig(AppConfig): name = 'timetable' def ready(self): from mqtt.client import client client.loop_start() ###mysite/mqtt/client import paho.mqtt.client as mqtt #from .tasks import * #The callback for connecting to CloudMQTT broker def on_connect(client, userdata, flags, rc): print("Connecting to CloudMQTT broker: "+ mqtt.connack_string(rc)) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, message): print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos)) topic = message.topic.split('/') room = get_room(topic[0], int(topic[1])) if topic[2] == 'ID': pass if topic[2] == 'lastWill': pass client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set('xxxxxxxx', 'xxxxxxxx') client.connect('xxxxxxxx', xxxxx), The second code is where the client object in apps.py imported from. I dont why there are two MQTT client created when I start development server? -
Django 2.1 How to display all post associated to my logged in user
I have tried to fetch them using my form but it does not display the post {{ object.talksports_set.all }} -
current time on Server (AWS) different from real time
thanks for the help in advance. I have a django/python project and deployed to AWS with elastic beanstalk. But there is an issue with the current time with the deployed version. I get the current time through django model and render it frontend. It's always one day behind, but it works fine on the localhost. I have changed the localtime on the server under /etc/localtime to the desired timezone , but this does not address the issue. Any suggestion will be appreciated! Thanks a lot -
Using pytest parametrize with DRF test
Now I have code like this: from rest_framework.test import APITestCase class MyTestClass(ApiTestCase): fixtures = ['some_fixtures.json', ] @pytest.mark.parametrize('field, reverse_ordering', [ ('id', False), ('id', True)] def test_ordering(self, field, reverse_ordering): # some test function Every time it is failed with that error: ====================================================================== ERROR: test_ordering (my_module.tests.MyTestClass) ---------------------------------------------------------------------- TypeError: test_ordering() missing 2 required positional arguments: 'field' and 'reverse_ordering' How it is possible to use @pytest.mark.parametrize decorator with tests inside of APITestCase from DRF tests class? -
Tests for extended DjangoCMS toolbar
Can you help me how to write unit tests for extended toolbar in DjangoCMS? Here is a reference on how to extend toolbar http://support.divio.com/academy/advanced-how-to-build-a-website-and-blog-with-django-cms/17-adapting-your-application Has anyone had some experience with this? Thanks in advance! -
Is there a way to reflect changes on S3 quickly?
I've been working on Django project. Recently sometimes I have a trouble updating static files on S3. The changes on S3 cannot be reflected quickly. Also the speed of reflecting the changes depends on the browser. It takes more time to reflect the changes on Chrome than Edge for me. Is there a preferable way to prevent this?