Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Serve Files From External Storage Directly
I have a Django project built on Google Cloud Platform. We are using Django's auth system, and most (nearly all) users do not have credentials set up in the GCP project, so all file auth needs to be based on Django and not GCP. Our backend configuration for file storage is very basic, and files are successfully uploaded to GCS as expected: DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'my-bucket' The generated URLs for files are of the form (again, as expected): https://storage.googleapis.com/my-bucket/my-document.txt The problem is this bucket cannot be made publicly readable as files have access controls based on rules set up in Django's permission system that are different per user. How can I have Django serve the file instead of the file being served by GCS? One thought that comes to mind is to have views that load files from GCS and pass them through to the requesting client, but I suspect this will not handle large files well as I need to either load the entire file into local memory (bad) or load the file in chunks and write them out to the response stream in those chunks, but don't know if this can be done in Django. -
Django Settings variable *sometimes* getting reset and unsure why
I have a dict defined in my Django settings.py to act as a sort of...fake, temporary cache of data for all of my users. However, it has come to my attention that it is not behaving the way I would like and is resetting back to it's default value seemingly at random. settings.py # initialize with a fake key:value for ease in logging STORE_DATA = {'hello': 'goodbye'} views.py def get_data(name): from apiclient.discovery import build search_q = name service = build('youtube', 'v3', developerKey='<key-here>') results = service.search().list( part='snippet', channelId='<channel-here>', type='video', q=search_q, ).execute() settings.STORE_DATA[name] = results['items'] result = settings.STORE_DATA[name] return result page.videos = [] if page.name in settings.STORE_DATA: page.videos = settings.STORE_DATA[page.name] else: page.videos = get_data(page.name) This is the only code that references this global variable. It's just simply storing the results of a youtube api call so we don't have to make a query every time someone visits the page. However - sometimes this works, sometimes it doesn't. Sometimes the key:value pairs stored in the dict get reset back to it's initial state. Here is a little print out from my log - cache before the call - [u'hello'] "page1" - 2018-08-22 23:23:47 cache after the call - [u'page1', u'hello'] cache before the … -
Django testing - spoofing an Ajax POST request method with Client() to pass request.is_ajax() validation
Not sure if this is possible, but I have the following validation check for an Ajax POST request in my views.py: if request.is_ajax() and request.method == 'POST': # Do some amazing stuff here... context['is_ajax'] = True Now, running a few tests in the shell: from django.test import Client >>> c = Client() >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'}) >>> response.context['is_ajax'] >>> undefined So my question is, is there a way with the test Client to spoof an Ajax request...passing the is_ajax() validation check on the request POST object, is this done by adding something to headers? I think the header should be HTTP_X_REQUESTED_WITH='XMLHttpRequest' - how would this be passed in to the c.post() method? -
Django - Forms - assign custom attributes to forms in forms.py
The question title might be a little misleading, but I couldn't think of a better title. If you've got better title, please edit the title. I have following set of models.py and forms.py` # models.py class BHA_Component(models.Model): field_1 = models.CharField(max_length=100) field_2 = models.CharField(max_length=100) field_3 = models.CharField(max_length=100) # forms.py class BHA_Component_Form(forms.ModelForm): class Meta(): fields = '__all__' I want to create custom attributes for each field, so that I can identify what kind of field it is on the Front-End, and assign a class for each field type. Something like this: Some fields are just plain blank, some are grey, some are purple, and some have check boxes. These are done by manually giving each field a particular HTML class on the Front-End. However, I want to give each field some attributes on the Back-End, and have those attributes identified on the Front-End. So, something like this: {% for field in bha_component_form %} {% if field.custom_attribute == 'option_1' %} {{ field|add_class:"has_checkbox"}} {% else if field.custom_attribute == 'option_2' %} {{ field|add_class:"blue_background"}} {% else %} {{ field|add_class:"plain"}} {% endif %} {% endfor %} How can I do this? -
How to pass raw xml into django sitemaps?
OVERVIEW: Hi, I'm trying to do the above. I'm using the sitemap framework with a custom template to put all my links in the xml file. It works fine up to a point. All the objects from the database and the static views show up perfectly. But for seo reasons, I want to add some raw xml for some images that are in the static folder. And because they're static, they're not saved into the database, so I can't get them and any special search term values there. My assumption is that I have a file pathing problem with my picture_seo variable. Here's an example of what I have so far, and an Idea of what I want done: URLS.PY from django.contrib.sitemaps import views as sitemap_views from django.views.decorators.cache import cache_page from .sitemaps import HighPrioritySitemap, LowPrioritySitemap # picture_seo = 'picture_seo.html' # not working when I uncomment it sitemaps = { 'high_priority': HighPrioritySitemap, 'low_priority': LowPrioritySitemap, # 'picture_seo': picture_seo # I want this passed in too but can't figure out how } urlpatterns = [ path('sitemap.xml', cache_page(60*720)(sitemap_views.index), {'sitemaps': sitemaps}), path('custom-sitemap-<section>.xml', cache_page(60*720)(sitemap_views.sitemap), {'sitemaps': sitemaps, 'template_name': 'sitemap_test.html' }, name='django.contrib.sitemaps.views.sitemap'), ] DIRECTORY STRUCTURE: ... manage.py some-templates/ picture_seo.html # was told to make an html file for … -
Patch method doesn't work with Django REST Framework
I'm trying to enable partial update in Django web app. The model I want to update includes ImageField. PATCH method works when I update the ImageField, but it doesn't work when I don't update the ImageField. Error message says 'NoneType' object has no attribute 'items' How can I fix it? Model: class Work(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=120) made_date = models.DateField(default=datetime.date.today, null=True, blank=True) note = models.TextField(max_length=2000, null=True, blank=True) image = models.ImageField(upload_to='work_pic', default='default_image.png') Serializer: class WorkSerializer(serializers.ModelSerializer): owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Work fields = '__all__' def create(self, validated_data): return Work.objects.create(**validated_data) ViewSet: class WorkViewSet(viewsets.ModelViewSet): queryset = Work.objects.all() serializer_class = WorkSerializer def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) Method to send request (Vue.js): updateWork: function() { let formData = new FormData(); //Initial value of currentWork.image is text (path to the original image in the media folder). //When user upload new image, the file is set to currentWork.image. So condition is match to the if statement bellow. if (this.currentWork.image instanceof File) { formData.append("image", this.currentWork.image); } formData.append("title", this.currentWork.title); formData.append("made_date", this.currentWork.made_date); formData.append("note", this.currentWork.note); this.loading = true; axios.patch(`/api/work/${this.currentWork.id}/`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then((response) => { this.loading = false; }) .catch((err) => { … -
Django form not rendered by auth_views.LoginView
I have a problem that is that Django is not rendering one of the fields of my Login form. I'm using the auth_views.LoginView view for user authentication, and even if I put my template, one of the fields does not appear in my html. Url.py: from django.urls import path, re_path from django.contrib.auth import views as auth_views from Turnos import views urlpatterns = [ path('', views.home, name='home'), with views.login view it works perfectly #path('login/', views.login, name='login'), with auth_views.LoginView.as_view(template_name='login.html') doesn't render the email field path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), ] views.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import login as auth_login from Turnos.forms import loginForm def login(request): if request.method == 'POST': form = loginForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) return redirect('nuevoTurno.html') else: form = loginForm() return render(request, 'login.html', {'form': form}) forms.py: from django import forms from django.contrib.auth.models import User class loginForm(forms.ModelForm): email = forms.EmailField(required=True, widget=forms.EmailInput()) password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['email', 'password'] Html: <form action="/login/" method="post" novalidate> {% csrf_token %} <div class="form-group"> <label for="{{ form.email.label }}" class="">Email</label> {% render_field form.email class+="form_control form-control-lg" placeholder="Email" %} </div> <div class="form-group"> <label for="{{ form.password.label }}" class="">Password</label> {% render_field form.password placeholder="Password" class+="form_control form-control-lg" %} </div> <div class="form-group"> … -
Jinja2 inside jinja2
I have the following code: <img src="{% static 'imatges/{{i.sideid.sidepic}}' %}"/> But it doesn't load the picture... If i change the {{i.sideid.sidepic}} to the picture name "republic.png" it works tho. So, yeah, {{i.sideid.sidepic}} is actually the exact same name ("republic.png"), because i do a print in django views and shows it in my cmd, the exact same name "republic.png" . I guess it has a specific way to add that {{i.sideid.sidepic}} inside the jinja {% %} . Thanks all! -
Mixer.blend() module cannot properly create an instance that is referencing custom User object with UUID as PK
I am trying to run tests of my models using pytest. I am having trouble with using mixer on a SQLite3 in ":memory:" database. I have a model named Category that has a foreign key attribute called "created_by" which references my custom User model. When assigning the referenced model of User to the category variable in mixer.blend() I get an exception that says that the User instance is not that of a UUID. See my test below: import pytest from mixer.backend.django import mixer from apps.API import models pytestmark = pytest.mark.django_db class TestCategory(): def test_model(self): category = mixer.blend(models.Category) assert category.pk == 1, 'Should create a Category instance' This is very strange as this worked previously (about a week ago). Why can mixer not coerce the UUID from the primary key of my User object? If anyone has any ideas I am all ears. Below I define my models and show a few stack traces. Hopefully, we can find some insight. Here is the stack trace in pytest: self = <django.db.models.fields.UUIDField: id>, value = <User: doliver@smith.com> def to_python(self, value): if value is not None and not isinstance(value, uuid.UUID): try: > return uuid.UUID(value) venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2325: self = <[AttributeError("'UUID' object has no attribute 'int'") raised … -
How to increase upload image size on Nginx server?
I have developed an application in Django. I was stuck in the problem that some image(size:2MB)was uploaded successfully while some images(size:4,5MB) generate an error after upload. After research, I found that this issue is due to my Nginx server file upload size. This is my nginx.conf file user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml … -
Can't import models on python console in Pycharm
I am trying to import one of my models in Python Console in PyCharm and I am getting the following error from damage.models import Damage Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "C:\projects\django\deya\damage\models.py", line 2, in <module> from django.contrib.auth.models import User File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "C:\projects\django\deya\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) File "C:\projects\django\deya\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\projects\django\deya\venv\lib\site-packages\django\db\models\base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "C:\projects\django\deya\venv\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "C:\projects\django\deya\venv\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Everything else in my project works fine. I am able to import my models when i run python manage.py shell from command line or even PyCharm Terminal. Can anyone helps? Thanks in advanced Kostas -
Extending Django-admin's DateFieldListFilter for custom "Upcoming" filter
I am trying to add a custom "Upcoming" filter to the Django Admin DateFieldListFilter. It's really simple, just selecting dates after today. Building on this thread i was able to extend Django's standard DateFieldListFilter into my own custom one as follows : class MyDateTimeFilter(DateFieldListFilter): def __init__(self, *args, **kwargs): super(MyDateTimeFilter, self).__init__(*args, **kwargs) today = datetime.now() self.links += (('Upcoming'), {self.lookup_kwarg_since: today.strftime('%d %B %Y')}), It correctly displays "Upcoming" at the bottom of my filters, but clicking does not actualy filter the results. I do not know what's wrong with my syntax and I have tried many alternatives... Your help is very much appreciated! PS: I am using Python 3.5.2 and Django 2.0.6 -
override save to act as save and continue on add
I have an Model Admin that requires at least one associated inline record. The inline form is not displayed on add, only on change. I would like for the 'save' button to behave as 'save and continue editing' only when the change_form is adding a record (this seems less complex than hiding the save button while showing the save and continue in this case only). The 'save'and 'save and continue editing' buttons should behave as normal when modifying, only behave differently during add. Thanks! -
PostgreSQL full text search doesn't work in some case (Django)
I notice that in django when there is a sentence containing PLAZA/MASTERPIECE then when we search masterpiece I can't find this sentence. Is this a limitation of PostgreSQL full text search. Or how to solve this? finalquery = SearchQuery("keyword") vector = SearchVector('thefieldIwanttosearch') self.search_results = self.search_results.annotate(search=vector).filter(search=finalquery).annotate(rank=SearchRank(vector, finalquery)) Is there any document about this? Thanks! -
Django urlpatterns settings
I have a Django project, the working urls.py looks like: urlpatterns = [ path('', views.index, name='index'), path('polls/search', views.search, name='search'), ] Then I want to add additional path for my image in the urls.py urlpatterns += patterns('django.views.static',(r'^media/(?P<path>.*)','serve',{'document_root':settings.MEDIA_ROOT}), ) But I got: unresolved reference 'patterns' I am using python 3.4 and Django 2.0.8. How do I properly add the additional path to my original urls.py ? Thanks! -
django locale is not loading correctly
I am using django 1.8.7. From my understanding django locale is supposed to be loading from <site_root>/locale/<lang_code>/LC_MESSAGES/django.po I have <site_root>/locale/zh_CN/LC_MESSAGES/django.po and ran python3 manage.py compilemessages and I got <site_root>/locale/zh_CN/LC_MESSAGES/django.mo and I have request.session[LANGUAGE_SESSION_KEY] = 'zh-cn' But my django application not loading anything from my <site_root>/locale/zn_CN/LC_MESSAGES/django.po but only loading a few works from locale translation from django 's default translations. Somewhere I should look into? -
Django - Reverse for 'list1' not found. 'list1' is not a valid view function or pattern name
I'm trying to upload a file, I got the code from some website. Which was written in older Django version and i'm using a latest version. Got some errors while running, fixed them by going through stackoverflow. But now i'm stuck with no clue with the error mentioned, this is my first Django project. Thanks in advance. Below are my files views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Document from .forms import DocumentForm from django.urls import reverse # def list1(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('myproject.myapp.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render(request, 'csv_manipulation/list.html', ) def index(request): return render('myapp/index.html') urls.py from django.urls import path, include from .views import list1 urlpatterns = [ path(r'', list1), path(r'list/', list1), ] forms.py from django import forms class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', ) list.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Minimal Django File Upload Example</title> </head> <body> <!-- List … -
Django: How would I translate keys in an HTML template with values in a CSV?
I'm facing a few troubles in regards to getting started with some work I'm doing involving translations. I currently have a .csv file that is formatted as such: KEYS,en-US,ko-KR active,Active,사용 여부 actual,Actual,실적 경비 addNewCostType,Add New Cost Type,경비 등록 etc... and am trying to use this CSV as an i18n file for an HTML file I'm creating using Django to dynamically insert data into the file. Ideally what I'd like to do is have a table in the HTML file where the header is a key and then based on the locale of the browser Django will insert the proper translation. I saw a few examples where users were able to use .JSON files to do this but I was curious if there was a way to use the .csv that I currently have to achieve this as it would save a lot of time. I think my code is supposed to be something like {% load i18n %} <table> <tbody> <tr> <th>{% trans trainingTitle %}</th> <td>{{training_title}}</td> <th> {% trans targetAudience %}</th> <td>{{audience}}</td> </tr> </tbody> </table> but I don't know how to reference the .csv or really much about how translations work in Django's template rendering. Could someone guide me in … -
Cannot Connect to server error while Dockerizing a django project with multiple apps
I have a Django application that uses Python 3.6.5 and Django 1.9.5. My Dockerfile contains the following: # Dockerfile # FROM directive instructing base image to build upon FROM python:3 # Set environment varibles ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE myapp.settings.dev-postgres # Set work directory WORKDIR /MyProj # Install dependencies COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt # Copy project COPY . /MyProj # EXPOSE port 8000 to allow communication to/from server EXPOSE 80 # CMD specifies the command to execute to start the server running. CMD ["python", "manage.py", "runserver", "8000"] and my requirements.txt has beautifulsoup4==4.4.1 cffi==1.7.0 cryptography==2.1.4 Django==1.9.5 django-appconf==1.0.2 django-compressor==2.0 django-grappelli==2.8.1 django-markdown-deux==1.0.5 django-model-utils==2.5 django-pagedown==0.1.1 django-sendgrid==1.0.1 idna==2.1 inflection==0.3.1 markdown2==2.3.1 more-itertools==2.2 ndg-httpsclient==0.4.2 pandas Pillow==5.0.0 pyasn1==0.1.9 pycparser==2.14 pyOpenSSL==17.5.0 python-dateutil==2.5.3 pytz==2016.6.1 rcssmin==1.0.6 requests==2.9.1 rjsmin==1.0.12 sendgrid==1.4.0 sendgrid-django==1.4.0 six==1.10.0 smtpapi==0.2.0 stripe==1.37.0 Unidecode==0.4.19 djangorestframework==3.4.0 django-extensions django-guardian psycopg2 gunicorn django-analytical==2.2.2 raven == 6.5.0 boto==2.45.0 django-storages==1.5.2 twilio boto3 I first did a "docker build -t my_image .", then "docker run -p 4000:80 my_image" following the tutorial from https://docs.docker.com/get-started/part2/#run-the-app The output after executing docker run command is Performing system checks... Spaces List: ['dev1', 'dev2', 'dev3'] System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f1181d35598> Traceback (most recent call last): File … -
Django project couldn't find image given absolute path:
I have the following line in an html file of my Django project: '<img src="/Users/edamame/workspace/git/my-analysis/django_services/mysite/polls/my_img.jpg" >' However, when the page is loaded, the image can't be found and below is the error message in the console: [22/Aug/2018 20:04:51] "POST /polls/polls/search HTTP/1.1" 200 733 Not Found: /Users/edamame/workspace/git/my-analysis/django_services/mysite/polls/my_img.jpg [22/Aug/2018 20:04:51] "GET /Users/edamame/workspace/git/my-data-analysis/django_services/mysite/polls/my_img.jpg HTTP/1.1" 404 2315 Any idea why the image can't be found? Thanks! -
How to automatically add group and staff permissions when user is created
I'm runnging Django 2.0.8 and currently using django-allauth. When a new user registes/signs up, I would like them to automatically be added to a group and given staff status so they can log into the admin page. I've read some of the documentation but I currently don't understand how it all ties together and each new user is defaulted to some permissions. -
Django REST Framework create nested serializers gives pk error
My models: class ContentHotel(models.Model): hotel_id = models.IntegerField(unique=True, blank=True, primary_key=True) class Meta: managed = False db_table = 'content_hotels' ordering = ('hotel_id',) def __str__(self): return str(self.hotel_id) class RateHotel(models.Model): rate_hotel_id = models.IntegerField(blank=True, primary_key=True, unique=True) content_hotel = models.ForeignKey(ContentHotel, on_delete=models.CASCADE, related_name='rate_hotel') class Meta: managed = False db_table = 'rate_hotels' ordering = ('rate_hotel_id',) def __str__(self): return str(self.rate_hotel_id) My Serializers: class RateHotelSerializer(serializers.ModelSerializer): class Meta: model = RateHotel fields = __all__ class ContentHotelSerializer(serializers.ModelSerializer): rate_hotel = RateHotelSerializer(many=True) class Meta: model = ContentHotel fields = ('hotel_id', 'rate_hotel') def create(self, validated_data): rate_hotels = validated_data.pop('rate_hotel') content_hotel = ContentHotel.objects.create(**validated_data) for rate_hotel in rate_hotels: RateHotel.objects.create(content_hotel=content_hotel, **rate_hotel) return content_hotel JSON: { "hotel_id": -1, "rate_hotel": [{"content_hotel": -1, "rate_hotel_id": 1}] } Above JSON input gives me error like: { "rate_hotel": [ { "content_hotel": [ "Invalid pk \"1\" - object does not exist." ] } ], "status_code": 400 } REFERENCE: http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers I referenced the link above, anyone knows how to address this? But f I create the two objects separately, it works correctly, like this: { "hotel_id": -1, } { "content_hotel": -1, "rate_hotel_id": 1 } -
django-filter - add aggregate in filtered data
I need to add some counts of my filtered data and i'm using aggregate to do this: class MunicipioList(generics.ListAPIView): queryset = Municipio.objects.filter().order_by('-id') extra_counts = queryset.aggregate( cidades=Count('pk', filter=Q(cidade__isnull=False)), estados=Count('pk', filter=Q(cidade__isnull=True)), estados_aderidos=Count('pk', filter=(Q(usuario__estado_processo=6) & Q(cidade__isnull=True))), municipios_aderidos=Count('pk', filter=(Q(usuario__estado_processo=6) & Q(cidade__isnull=False))), ) serializer_class = MunicipioSerializer metadata_class = MunicipioMetadata filter_backends = (DjangoFilterBackend, filters.OrderingFilter,) filter_class = MunicipioFilter ordering_fields = ('cidade__nome_municipio', 'estado__nome_uf') def list(self, request): response = super(MunicipioList, self).list(self, request) response.data['cidades'] = self.extra_counts['cidades'] response.data['estados'] = self.extra_counts['estados'] response.data['estados_aderidos'] = self.extra_counts['estados_aderidos'] response.data['municipios_aderidos'] = self.extra_counts['municipios_aderidos'] return response But the counts are wrong, cause the queryset is not filtered, so it's always based on all objects. I'm using django-filter. Can someone help with this? -
Django: update model field using button
I would like to use a button to update a field (claimant) in one of my models (PieceInstance) and then redirect the user to a page where he sees all of the claimed instances. The code is the following: button: (looping through all instances) <a target="_blank" method="POST" class="button" href="{% url 'claim' pk=instance.pk %}"> Claim </a> views.py def claim(request, pk): piece_instance = PieceInstance.objects.get(pk=pk) piece_instance.claimant = request.user piece_instance.save() return HttpResponseRedirect(reverse('my-claimed')) urls.py urlpatterns += [ path('myclaimedpieces/<uuid:pk>', views.claim, name='claim'), ] It runs smoothly but does not update the field in the model and hence the content on the redirected page is still empty. Help is much appreciated! -
Changing admin classes in runtime
I want to change admin classes programmatically without restarting server. I want to for example change list displays of a model in runtime. Now it only changes when I restart the server... Example (Versionadmin is an extention of modeladmin): admin.site.unregister(model) class YourModelAdmin(VersionAdmin): list_display = new_list_display admin.site.register(model, YourModelAdmin) This works if I run it in admin.py, but if I run it when the admin site is already setup, nothing changes. Any idea how to go about this?