Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework 'Manager' object is not subscriptable
I am using a custom Queryset as manager for my model like this. from django.db.models import QuerySet from django.db.models.manager import BaseManager class MyModelQuerySet(QuerySet): pass # some custom functionality here class MyModelManager(BaseManager.from_queryset(MyModelQuerySet)): pass # some extra methods here Everything works as expected but there is a check in django-rest-framework (relations.py). This check fails for my model. Actually they are checking type against Manager class but my manager is of type BaseManager (as expected) not Manager. This triggers an error by returning manager instead of queryset. Is there any way to make this check true from my side? (inheriting from Manager is not a choice) though I think this should be updated with a PR in DRF. -
Django serialize field from reverse related object
I have 2 models: ContentBuild & ContentBuildDeviceGroupLink like this: # models.py class ContentBuild(models.Model): content_build_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) class ContentBuildDeviceGroupLink(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) content_build = models.ForeignKey(ContentBuild, on_delete=models.CASCADE, related_name='content_build_deploy') release_date = UnixDateTimeField() preload_date = UnixDateTimeField() I serialize ContentBuild to include release_date & preload_date like this: # serializers.py class ContentBuildDeviceGroupLinkSerializer(serializers.ModelSerializer): class Meta: model = ContentBuildDeviceGroupLink fields = ('release_date', 'preload_date') class ContentBuildSerializer(serializers.ModelSerializer): deploy_dates = ContentBuildDeviceGroupSerializer(read_only=True, source='content_build_deploy', many=True) class Meta: model = ContentBuild fields = ('content_build_uuid', 'deploy_dates') This results in this: [ { "content_build_uuid": "uuid", "deploy_dates": [ { "release_date": "related release_date", "preload_date": "related preload_date" } ] }, ... ] My goal is to get the JSON response like this: [ { "content_build_uuid": "uuid", "release_date": "related release_date", "preload_date": "related preload_date" }, ... ] Is it possible to get my desired JSON output with a reverse related object? I tried to change my serializer like this: class ContentBuildSerializer(serializers.ModelSerializer): release_date = serializers.DateTimeField(read_only=True, source='content_build_deploy.release_date') class Meta: model = ContentBuild fields = ('content_build_uuid', 'release_date') This just shows the content_build_uuid. Is it possible to get my desired JSON results with fields from a reverse related field? If so, how do I get my desired results? -
'list' object has no attribute '_committed' while saving form data
I am trying to save the data in my form. Upon checking if the form is valid and trying to save the data, i am receiving AttributeError 'list' object has no attribute '_committed'. I can't understand what the problem is. here is my form. class issueAddForm(forms.Form): related_to = forms.ChoiceField(label = "Project") title = forms.CharField(label = "Heading") description = forms.CharField(label = "Description",widget=forms.Textarea ) attachments = forms.FileField(label = "Attachment(s)",widget=forms.ClearableFileInput(attrs={'multiple': True})) def __init__(self, user, *args, **kwargs): super(issueAddForm, self).__init__(*args, **kwargs) self.fields['related_to'].choices = [(o.id, o.name) for o in Projects.objects.filter(client=user.id)] views.py def addIssue(request): if request.method == "POST": form= issueAddForm(request.user,request.POST,request.FILES) if form.is_valid(): pr = Projects.objects.get(id=form.cleaned_data['related_to']) ti = form.cleaned_data['title'] de = form.cleaned_data['description'] o = issues(related_to=pr,title=ti,description=de,attachments=request.FILES.getlist('attachments')) o.save() return HttpResponse("added") -
How load to Django Paginator Page (next/ previous)?
Hy, i followed a tutorial for a multiple model search and it worked. now i want to paginate the output. But how can i load my paginator page data into my template? views.py from django.views.generic import TemplateView, ListView from django.views.generic import View from django.shortcuts import render from django.db.models import Q from django.core.paginator import Paginator from itertools import chain # --- Import Models from datainput.models import Animal from datainput.models import Farmer <....> class SearchView(ListView): template_name = 'farmapi/searchview.html' paginate_by = 2 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: farmer_results = Farmer.objects.search(query) animal_results = Animal.objects.search(query) # combine querysets queryset_chain = chain( farmer_results, animal_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return Farmer.objects.none() # just an empty queryset as default template.html {% extends 'base.html' %} {% load class_name %} {% load static %} {% block custom_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}"> {% endblock %} {% block content %} <div style="height: 10px;"> </div> <div class="container-fluid"> <div class='row'> <div class="col-4 offset-md-8"> <form … -
How to render the first element of a list different than others in jinja2
I want to render the first element of a list differently in Jinja. How can I differentiate the first iteration from others? Or is there any different way? I have tried doing - {% for item in results %} {% if loop.first %} First Element {% else %} Other element {% endif %} {% endfor %} What am I doing wrong? -
Celery is not working for more than 3 queues with redis
I am new to celery. I have been using three queues in celery and it was working fine. I have run the celery as follows: celery worker -A bdjsms -l debug -Q "swiftapi,swiftsms,celery" But now I need two more queues, and tried to run celery as follows: celery worker -A bdjsms -l debug -Q "swiftapi,swiftsms,celery,bulksms,singlesms" But this show the error CRITICAL/MainProcess] Unrecoverable error: NotBoundError("Can't call method on Exchange not bound to a channel",) I am not getting what is wrong with adding two more queues. I have used python==3.6.7, redis==2.10.6, and django-redis==4.10.0. The traceback is Traceback (most recent call last): File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/bootsteps.py", line 370, in start return self.obj.start() File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/worker/consumer/tasks.py", line 37, in start c.connection, on_decode_error=c.on_decode_error, File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/celery/app/amqp.py", line 302, in TaskConsumer **kw File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/messaging.py", line 386, in __init__ self.revive(self.channel) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/messaging.py", line 407, in revive self.declare() File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/messaging.py", line 420, in declare queue.declare() File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/entity.py", line 604, in declare self._create_exchange(nowait=nowait, channel=channel) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/entity.py", line 611, in _create_exchange self.exchange.declare(nowait=nowait, channel=channel) File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/entity.py", line 182, in declare return (channel or self.channel).exchange_declare( File "/home/sparrow/.virtualenvs/envpython3.6/lib/python3.6/site-packages/kombu/abstract.py", … -
List API view returns list of empty objects
I am trying to use generics.ListApiView to get a list of objects, here is my serializer class SitesSerializer(serializers.Serializer): class Meta: model = models.Sites fields = '__all__' Model # domain name without www class Sites(models.Model): SiteName = models.CharField(max_length=50) DomainName = models.CharField(max_length=50, primary_key=True) Currency = models.CharField(max_length=20) CurrencySymbol = models.CharField(max_length=10) SiteGroup = models.CharField(max_length=50, choices=SHOPZY_SITE_CHOICES, default=AMAZON) and this is my view class class SitesView(generics.ListAPIView): queryset = Sites.objects.all() serializer_class = SitesSerializer But instead of getting the list of site objects, i am getting a list filled with empty objects, the output produced by the above code is [ {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {} ] Whats wrong with this code? why rest framework cant show the fields of the sites object? -
Return JSON response along with a downloadable file
How can I return a response in terms of a success message along with the generation of a csv file in Django Rest API. I am able to return a csv file by using Http Response but unable to render the success message as a response on the browsable API page. -
Django: Resize image on pre-save signal
I have a model that contains ImageField field and I want to resize provided image if it's dimensions are too big (over 600x600). My signal looks like this: from django.conf import settings from django.db.models.signals import pre_save from PIL import Image def resize_profile_picture(sender, instance, **kwargs): img = Image.open(instance.profile_picture) print(img.__dict__['_size']) if any([img.width > settings.MAX_PROFILE_PICTURE_WIDTH, img.height > settings.MAX_PROFILE_PICTURE_HEIGHT]): img.thumbnail(settings.MAX_PROFILE_PICTURE_DIMENSIONS) print(img.__dict__['_size']) Those prints shows that in fact the image is being resized, from (645, 374) to (600, 347), but the problem is that this thumbnail is not being saved and I still have picture in the original size. Since thumbnail operates on the same picture it is invoked on, I can't find any reason why it does not work, because according to the documentation, thumbnail returns NoneType so in my understanding it's not up to me to save modified picture or return it (But I tried nonetheless, no luck). -
How to convert a list of dictionaries to a dictionary of values
I have a list of dictionaries which I want to convert into a dictionary. q2 = [{'ComplainDepartment':'Academic','count':1},{'ComplainDepartment':'Hostel','count':2}] Change it to:- data = {'Academic':1,'Hostel':2} -
How could fix list_display columns width in admin model
I have normal admin.py with custom list_display, list_filter and search_fields but the issue is some of columns looks so ugly, how could I arrange it to be fixed width or by max-width and save people eyes ? img of ugly admin.py : img class FollowUpsAdmin(admin.ModelAdmin): list_display = ('user', 'company', 'contact_person', 'action', 'result', 'next_action', 'new_action_date', 'result_class', 'notes', 'is_active', 'updated_date', 'created_date') list_filter = ('user', 'company', 'result_class', 'is_active') search_fields = ('user__email', 'company__name', 'action', 'result', 'next_action', 'new_action_date', 'result_class', 'notes', 'is_active', 'created_date') admin.site.register(FollowUp, FollowUpAdmin) -
how post method redirect in django-rest-framework
I have a POST EP /web/organizations/groups/1/add-members/ now due to security reasons i want it to be POST /web/organizations/groups/19845806-6b9b-43bf-bdc4-617e8d1ef1d1/add-members/ but in django POST method redirection i am getting problem as it says { "detail": "Method \"GET\" not allowed." } current it gives HTTP POST /web/organizations/groups/1/add-members/ 301 [0.34, 127.0.0.1:40380] HTTP GET /web/organizations/groups/8e15f7ac-c54b-49c6-88c1-80563909f430/add-members/ 405 [0.20, 127.0.0.1:40380] but this should redirect to the given url -
Weblate setup SES email for password reset
I tried to set up a Weblate instance on AWS to send password reset emails. I followeed the following steps: pip install boto pip install django-ses sudo vim /opt/bitnami/apps/django/lib/python3.7/site-packages/Django-2.1.4-py3.7.egg/django/conf/global_settings.py EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'xxxx' AWS_SECRET_ACCESS_KEY = 'xxx' However it still doesn't work properly and I'm not getting any errors. my AWS key has a full permission to SES. -
Django urls.py cannot create a python file
I am just started learning django so on my first lesson i am suppose to give a http response.when i create a python file urls.py it shows file cannot be created.. can anyone solve my problem enter image description here -
How are Django applications deployed at an Enterprise level?
I need a deployment plan for deploying my django application on windows server. I have deployed the application on Windows server using WAMP, but wamp is not getting approved by senior management as it is an open-source software and isn't thread-safe (i don't know about thread-safe). We are seeking for some alternative. Is wamp server actually used on Enterprise level ? -
running gunicorn django via pipenv environment on server using supervisor
I have a Django project with the following directory structure /var/www/html/my_project/ - Pipfile - Pipfile.lock - ... - src |- my_project |- settings |- manage.py Since the virtual environment is created on path /var/www/html/my_project/ using pipenv when I move to that directory and then run following script, it works fine /home/ubuntu/.local/bin/pipenv run gunicorn --pythonpath src my_project.wsgi:application -w 1 -b 127.0.0.1:8000 -t 300 --max-requests=100 When running from the home directory it stars creating a virtual environment in the home directory instead of running the application. I am using supervisor to execute the program with the following configuration app_config.conf [supervisord] [program:qcgbackend] command=/home/ubuntu/.local/bin/pipenv run gunicorn --pythonpath src my_project.wsgi:application -w 1 -b 127.0.0.1:8000 -t 300 --max-requests=100 directory=/var/www/html/my_project/ autostart=true autorestart=true stderr_logfile=/var/log/myproj-backend.err.log stdout_logfile=/var/log/myproj-backend.out.log and running following command to start supervisor supervisord -c /var/www/html/my_project/supervisor/app_config.conf This executes without giving any error but the application is not running. What could be the issue? -
Django FilteredSelectMulitple is not saving in User view
I have this form which is using the FilteredSelectMultiple widget (outside admin) class PlaylistForm(forms.ModelForm): class Meta: model = Playlist exclude = ['id'] widgets = { 'owner' : forms.HiddenInput(), 'name' : forms.TextInput ( attrs={ 'class' : 'form-control', 'placeholder' : _('Playlist Title'), 'label' : _('Playlist Title')}), 'projects' : FilteredSelectMultiple ('Items', is_stacked=True, attrs = {'class' : 'form-control'}) } class Media: css = { 'all': (os.path.join(settings.BASE_DIR, '/static/admin/css/widgets.css'),), } js = ( '/admin/jsi18n/', ) It is called from a CBV class CreatePlaylistView (LoginRequiredMixin, CreateView): model = Playlist form_class = PlaylistForm def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['form'] = PlaylistForm(self.request.POST or None, initial={'owner':self.request.user}) return ctx And displayed in a template <form method="post"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary">Create Playlist</button> </form> The Playlist object is saved but the ManyToMany relationship from the FilteredSelectMultiple are not saved. Do I need to overwrite the form_valid method or have I something wrong? -
Best way to write views for multiple queries in Django?
It's a simple question. I've organised my models so that most objects served to the page are of one type - Item. The model contains various attributes which help me serve it in different ways. I have articles, and videos, which are determined by a 'type' field on the model. Type = 'article' etc. I have a listview, which shows all the objects in the Item model, sorted by date. class ItemListView(generic.ListView): # This handles the logic for the UserForm and ProfileForm - without it, nothing happens. def item(self, request, *args, **kwargs): return index(request) def get_queryset(self): # return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return Item.objects.all().order_by('-create_date') I want a view which shows all the articles, sorted by date, and all the videos, sorted by date. I have a feeling I'll be writing many more such views. Is there a better way to do it than to write a new view for every single query? As, this is what I'm currently doing: Views.py class ItemListViewArticle(generic.ListView): # This handles the logic for the UserForm and ProfileForm - without it, nothing happens. def item(self, request, *args, **kwargs): return index(request) def get_queryset(self): # return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return Item.objects.filter(type__contains='article').order_by('-create_date') class ItemListViewVideo(generic.ListView): # This handles the logic for the UserForm and ProfileForm … -
Python Django - "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
if there is any bug in my code (code within a model that is used within a view which uses LoginRequiredMixin ) e.g. A bug like: if (True: Then I get the following error: "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed This makes it really hard to debug the code. I have figured out if I remove this line from my views.py: from django.contrib.auth.mixins import LoginRequiredMixin Even if I remove all instances where LoginRequiredMixin is used, just by importing it, it hides the true bug and generates the above auth error. I have read: AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL My research shows most of the time this is due to "django.contrib.auth'" missing from INSTALLED_APPS, which you can see I have (settings.py snippet, Django 2.2): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # <-- Important for this topic! 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.CommonConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I tried adding this to above the mixim import but neither helped: from django.contrib import auth from django.contrib.auth.models import User This part of the full … -
How to add multiple item using one key in python?
How to add multiple keys using one key in array? I tried to explain. Thanks def apidurusanalizi_func(self): isyerleri = data.iloc[:,0].values hatalar = np.delete(data.columns, 0) cluster1 = [] for i,row in enumerate(bc): for j, y in enumerate(row): if y: isyeri = isyerleri[i] hata = hatalar[j] record = {"isyeri":str(isyeri), hata.lower().replace(" ", ""):hata} if index == 0: cluster1.append(record)/*add record*/ return HttpResponse(json.dumps({'cluster1': cluster1}, indent=2), content_type="application/json") Output as below; { "cluster1": [ { "isyeri": "15400002",/*the same key*/ "olcmeodasi": "OLCME ODASI" }, { "isyeri": "15400002",/*the same key*/ "tipdegayari": "TIP DEG AYARI" } } The format I want to take as Json as below { "cluster1": [ { "isyeri": "15400002",/*the same value for two values*/ "olcmeodasi": "OLCME ODASI" "tipdegayari": "TIP DEG AYARI" } } -
Django GET parameters redirect
I'm in process of migrating my website to Django cms. But there is a problem with old URLs with GET parameters. They are still live in Google.Webmasters. When I go to site.com?catid=0&id=1517 it will open index page. I want to redirect all urls with get parameters from the root to my root index, ex: site.com?catid=0&id=1517 site.com?catid=0&id=1517&foo=123 site.com?catid=12 redirect(301) to: to site.com/ -
How can i subscribe a consumer and notify him of any changes in django channels
I'm currently building an application that allows users to collaborate together and create things, as i require a sort of discord like group chatfeed i need to be able to subscribe logged in users to a project for notications. i have a method "open_project" that retrieves details from a project that has been selected by the user, which i use to subscribe him to any updates for that project. so i can think of 2 ways of doing this. i have created a instance variable in my connect function: def connect(self): print("connected to projectconsumer...") self.accept() self.projectSessions = {} and heres the open_project method: def open_project(self, message): p = Project.objects.values("projectname").get(id=message) if len(self.projectSessions) == 0: self.projectSessions[message] = [] pass self.projectSessions[message] = self.projectSessions[message].append(self) print(self.projectSessions[message]) self.userjoinedMessage(self.projectSessions[message]) message = {} message["command"] = "STC-openproject" message["message"] = p self.send_message(json.dumps(message)) then when the user opens a project he is added to the projectsessions list, this however won't work as (i think) whenever a new user connects to the websocket, he gets his own projectconsumer. The second way i thought of doing this is to create a managing class that only has 1 instance and keeps track of all the users connected to a project. i have not tried … -
Running celery beat worker in my Django application
I am using celery for my Django project and to run celery beat worker I use the command celery -A <projectname> worker -B This works fine but if I want to execute this command from my application I run this command celery -A path\to\projectname worker -B Then I get this error ImportError: Import by filename is not supported. Is there any way I could run celery beat worker command from my application.Any help would be appreciated -
django apps on ports over uWSGI
One of my django apps is running ok if I run it on port directly # uwsgi --http :8000 --home /home/hsn/Env/site --chdir /home/hsn/djangy/site -w Blog.wsgi But when I run it over a webserver with reverse proxy settings with socket, I get internal server error is there anything wrong with socket configuration & need I move to port method instead?? uWSGI site configuration # cat site.ini [uwsgi] project = site uid = hsn base = /home/%(uid) chdir = %(base)/djangy/%(project) home = %(base)/Env/%(project) module = %(project).Blog.wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true nginx site configuration # cat site.conf server { listen 80; server_name site.vm www.site.vm; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/hsn/djangy/site; } location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; } } Also if I long list the socket file, it shows = sign next to filename like this # ls -l /run/uwsgi/site.sock srw-rw---- 1 hsn www-data 0 May 13 09:15 /run/uwsgi/site.sock= Does it mean something?? now the question part, if socket is not working, should I move to port method over uwgsi?? and how'd be the way to do it?? -
Gunicorn not able to run server
I am running the command "gunicorn --bind 0.0.0.0:8000 app.wsgi". But server is not running and also not accepting any request from the browsers . It should atleast show "using TensorFlow backend" as i it shows when i run the command. "python manage.py runserver 0.0.0.0:8000" Gunicorn shows just this only . [2019-05-13 08:59:53 +0000] [9693] [INFO] Starting gunicorn 19.9.0 [2019-05-13 08:59:53 +0000] [9693] [INFO] Listening at: http://0.0.0.0:8000 (9693) [2019-05-13 08:59:53 +0000] [9693] [INFO] Using worker: sync [2019-05-13 08:59:53 +0000] [9696] [INFO] Booting worker with pid: 9696 On running python manage.py runserver 0.0.0.0:8000 Performing system checks... Using TensorFlow backend. System check identified no issues (0 silenced).