Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query using large amount of memory
I have a query that is causing memory spikes in my application. The below code is designed to show a single record, but occasionally show 5 to 10 records. The problem is there are edge cases where 100,000 results are passed to MultipleObjectsReturned. I believe this causes the high memory usage. The code is: try: record = record_class.objects.get(**filter_params) context["record"] = record except record_class.MultipleObjectsReturned: records = record_class.objects.filter(**filter_params) template_path = "record/%(type)s/%(type)s_multiple.html" % {"type": record_type} return render(request, template_path, {"records": records}, current_app=record_type) I thought about adding a slice at the end of the filter query, so it looks like this: records = record_class.objects.filter(**filter_params)[:20] But the code still seems slow. Is there a way to limit the results to 20 in a way that does not load the entire query or cause high memory usage? -
Generic views for updating objects?
How do I rewrite the function-based view that only updates an object into a class-based view? Something like this (wrote this for a tutorial). from django.contrib.auth.decorators import permission_required @permission_required("catalog.mark_returned") def mark_returned(request, pk): bk = BookInstance.objects.get(pk=pk) if bk.status == "a": #some tests here bk.status = "a" bk.due_back = None bk.borrower = None bk.save() return redirect("on-loan") And in general, does it make sense to use generics for things like that? Because currently, I only use the generic list and detail views. Sorry for beginner-level questions:) -
Passing flags to Django call_command
How do you pass a flag to Django's call_command()? I thought it was simply call_command('command', flag=True), but this doesn't work in Django 1.11. I'm trying to run manage.py collectstatic --noinput from inside a unittest, but even though I'm calling it like: call_command('collectstatic', noinput=True) my unittest keeps hanging because collectstatic prompts for input. -
Mezzanine Static files not serving from STATIC_ROOT
I am new to Mezzanine and not an expert in Django. I am trying to make changes in the default Mezzanine theme. I am doing these steps to override default Mezzanine theme, python manage.py collectstatic A new static folder is created which stores all the static files across the project in this folder (STATIC_ROOT). This includes Mezzanine default static files as well from virtualenv/lib/python2.7/site-packages/mezzanine/core/static/ Then I run python manage.py collecttemplates A new templates folder is created which stores all the templates across the project in this folder. Now when I make changes in files from /templates directory I get to see those changes in development server. but when I make changes in /static directory files I do not see those changes in development server. to make changes to css files I have to go to virtualenv/lib/python2.7/site-packages/mezzanine/core/static/ path and then only I can see the changes in development server. I want to know what am I doing wrong. I do not want to make changes in mezzanine css files, I want to overwrite them form static_root. -
Python error: This method is only available to the class, not on instances
I am working on a Django application and have defined the line below in my urls.py path('organizations/', views.OrganizationListView().as_view(), name='organizations'), When I run my server, I get the error below lib\site-packages\django\utils\decorators.py", line 11, in __get__ raise AttributeError("This method is available only on the class, not on instances.") AttributeError: This method is available only on the class, not on instances. I understand that this must be because of the difference in calling a method on object vs class but not sure exactly what is causing it and how to resolve. -
How does SECRET_KEY = os.environ['SECRET_KEY'] in Django work?
I have my hardcoded SECRET_KEY in my settings.py file locally and want to put this file onto my live Digital Ocean server. If I just replace SECRET_KEY = 'xxx-xxx-xxx' with SECRET_KEY = os.environ['SECRET_KEY'] will it work? I'm assuming I have to do something else to actually get my local SECRET_KEY on there. -
django template tags showing on webpage instead of what they reference
I think I did a pretty decent job of reviewing all available resources before posting this online so apologies if it was already asked and I missed it. I am trying to learn how to use template tags and am following an online course while building my own website. When I put the template tag in {{ }}, the only thing that shows up is the actual template tag. In this case, that is: insert_content. See pic of broken template tag on webpage here. The way I build my template tag: The tag corresponds to a dictionary key in views.py file that has some text as a value. (And that is the text that I want to see on the webpage). I've gone over each file several times and I found a few typos but even after fixing all of them, the template tag is still showing up on webpage (instead of the value it should be returning). HTML code: <body> <h1>DATA DASHBOARD: FINANCIAL INCLUSION IN PAKISTAN</h1> <h2>{{ insert_content }}</h2> views.py code (from application folder): def index(request): my_dict = {'insert_content': "Hello, I'm from the app for Pak Fin Incl."} return render(request,'AppPakFinIncl/index.html',context=my_dict) Since my webpage is not erroring out, I am … -
Implement items ordering in Django
Suppose, I want to build a simple TODO-app. I want to make it possible to create todo-items, and also it should be possible to rearrange items manually. I made following model: class Item(models.Model): title = models.CharField(max_length=500) Now, I need to add a special field, let's call it order, to keep custom ordering. It should be unique, and it should be greater for any new record, so I tried to make an AutoField. class Item(models.Model): title = models.CharField(max_length=500) order = models.AutoField(primary_key=False) But it turned out that Django doesn't support several auto fields for a single model. I guess, it should be possible to write custom raw SQL code and use Postgres sequences directly, but it would look really ugly, and I don't want to write DB-specific code for such simple functionality. So, here is a question: what is a common way to implement items ordering in Django? It sounds like a very common requirement, and, I think, it should be a simple way to do this. -
ImportError at /hello/ Module "myapp.templates" does not define a "hello" attribute/class
I'm trying to make a simple webapp using Django 2.0.2. But I'm getting ImportError. Searched a lot but didn't find a way to resolve it. Can someone please help me with this error. Module "myapp.templates" does not define a "hello" attribute/class. Here's my code views.py from django.shortcuts import render def hello(request): return render(request,'hello.html',{}) urls.py from django.contrib import admin from django.urls import path from myapp.views import hello as myapp_hello urlpatterns = [ path('admin/', admin.site.urls), path('hello/', myapp_hello), ] settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'x+ve9z=f1_%t@*4uo@!h#b*!g-1ayc1d4+ct$q853nczss)#5c' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] 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', ] ROOT_URLCONF = 'DjProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'myapp.templates.hello', ], }, }, ] WSGI_APPLICATION = 'DjProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' Folder Structure . ├── db.sqlite3 ├── DjProject │ … -
Django Multiple Form Usage
How do I differentiate the post requests from different buttons in django? For instance, if I want to create a calculator, how do I make it so the POST of the "multiply" button is different from that of the "add" and the "subtract" buttons? -
Django get ID of Max after GROUP BY
I have two models: Forum: pk (ID) Thread: pk (ID), last_activity (datetime), forum (foreign key) I want to retrieve all the latest threads, group them by forum and in addition to that get at least the ID of each latest thread. Here's what I tried: Thread.objects.values( 'forum' ).annotate( latest=Max('last_activity') ).order_by() Here's what it produces: <QuerySet [ {'forum': 1, 'latest': datetime.datetime(...)}, {'forum': 2, 'latest': datetime.datetime(...)}, {'forum': 3, 'latest': datetime.datetime(...)}, {'forum': 4, 'latest': datetime.datetime(...)}, {'forum': 5, 'latest': datetime.datetime(...)}, {'forum': 6, 'latest': datetime.datetime(...)} ]> And what it should produce in addition to each entry in the queryset is the ID of the thread that has the greatest value of latest. Here's a sample entry: {'forum': 6, 'latest': datetime.datetime(...), thread_id: 60} -
How can i covert serializer data into dict type in Django
>>>from django.core import serializers >>>from generic.models import banner >>>query = banner.objects.all() >>>querydata = serializers.serialize("json",query) >>>querydata '[{"model": "generic.banner", "pk": 1, "fields": {"banner": "banner1", "link": null, "category": "bus", "status": "active"}}, {"model": "generic.banner", "pk": 3, "fields": {"banner": "banner2", "link": null, "category": "Mobile", "status": "active"}}]' >>>type(querydata) <class 'str'> In Querydata i am getting a string but i want to convert the querydata in dict in below format: {'bus':{'model': 'generic.banner', 'pk': 1, 'fields': {'banner': 'C:\wamp\www\Paymentapi\cbanner\cban_7500.png', 'link': null, 'category': 'bus', 'status': 'active'}}, 'Mobile':{'model': 'generic.banner', 'pk': 3, 'fields': {'banner': 'C:\wamp\www\Paymentapi\cbanner\cban_7318.png', 'link': null, 'category': 'Mobile', 'status': 'active'}}} can anyone help me, i am new in django and python? -
AttributeError: builtin_function_or_method object has no attribute value
I am trying to initialize a file directly using the type="file" method by using forms from django library. I'm running on raspi3 for your info. I have tried using the following codes but return the error of AttributeError: 'builtin_function_or_method' object has no attribute 'value' for the part which states: input.value = "/photos/image01.jpg"; Why is this so and how should I edit it? Thank you! :) The following are my codes for forms.py: from django import forms class UploadFileForm(forms.Form): file = forms.FileField() input.value = "/photos/image01.jpg"; input.form.submit(); -
Django Rest Framework: Cannot serialize or save uploaded image
Cannot serialize or save uploaded an image in APIview. If saving, a file is broken and cannot be open. If serialzing, getting: {"avatar":["No file was submitted."]} Request content: MultiValueDict: {u'name': [<TemporaryUploadedFile: Avatar.jpg (image/jpeg)>]} Settings: FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') URLs: urlpatterns = [ url(r'^test/$', TestReturn.as_view(), name='test-detail'), url(r'^users/$', UserProfileAll.as_view(), name='userprofile-detail'), url(r'^avatar/', UploadAvatar.as_view(), name='images') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Model: class AvatarStorage(models.Model): avatar = models.ImageField(verbose_name="Uploaded image", upload_to='media', null=True) Serialzier: class AvatarStorageSerializer(serializers.ModelSerializer): avatar = serializers.ImageField(use_url=True) class Meta: model = AvatarStorage fields = '__all__' Views: class UploadAvatar(APIView): parser_classes = (MultiPartParser,) def post(self, request, format=None): serializer = AvatarStorageSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) For posting, i am using Postman, over there settings: Body=>Form-Data and choosing a file from disk. If it's important, this is API for mobile -
Why when I create admin in the cmd on windows for Django?
Why when I create admin in the cmd on windows for Django? It give me this werid error and nothing is in the file at all ,but my computer said there a file name "mysite" already there? I'm using the last version of python... CommandError: 'C:\Users\Tm\Desktop\django-server\mysite' already exists -
Unable to debug Django process from vs code
Im trying to debug my Django process from vs code. But I am not able to get it to work. In my manage.py: import ptvsd try: ptvsd.enable_attach("my_secret", address=('localhost', 3000)) except: pass In my docker-compose: version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" - "3000:3000" depends_on: - db And my debug info in launch.json: { "name": "Attach (Remote Debug)", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "/code", "port": 3000, "secret": "my_secret", "host": "localhost" }, When starting the debug session I get no feedback at all in the debug window. Does anyone have any tips on how to get this working? Im running ptvsd 3.0.0 both on my computer and in the docker container. -
django mixin to make sure that user is active
I need to make sure that authenticated user is active for access the page. Is there any mixin for that in django? If not then how to do so. Thanks in advance. -
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using ajax to call the following url: "https://www.bittrex.com/api/v1.1/public/getticker?market=usdt-btc" I am getting the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have installed django-cors-headers and my settings.py looks like this: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'crispy_forms', # The following apps are required: 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:8000', ) Why am I still getting the error? ** I have read all the other answers related to this but they have not helped me. I have used the chrome plugin too and it does work with it but I want a solution without it ** Django Version = 1.8 -
How to update django model fields without knowing which fields to be updated beforehand?
I want to update a model without knowing which fields to update beforehand. For example: The request to my url api/user/(?P<pk>[0-9]+)/message-update/(?P<id>[0-9]+)/ will have a payload JSON with a POST request method like this: { "category": "personal", "type_of_transaction": "paid" } The problem here is that the payload key-value pairs will keep changing depending upon the fields to be changed. I have tried this but it seems to have no effect at all: message = Message.objects.get(user=pk, id=id) json_data = json.loads(request.body.decode(encoding='UTF-8')) attributes_to_be_changed = json_data.keys() values = json_data.values() for i in attributes_to_be_changed: message.i = values[attributes_to_be_changed.index(i)] message.save(update_fields=attributes_to_be_changed) try: json_message = MessageSerializer(Message, many=False) except Exception as e: return JsonResponse({"error": e}) return JsonResponse(json_message.data, safe=False) I have a message model as below: user = models.ForeignKey(User, related_name='messages') sender = models.CharField(max_length=15, blank=True) body = models.CharField(max_length=400, blank=True) account = models.ForeignKey(Account, blank=True, null=True) card = models.ForeignKey(CreditCard, blank=True, null=True) type_of_transaction = models.CharField(max_length=10) message_date = models.DateTimeField(blank=True, null=True) category = models.CharField(max_length=15, blank=True) spent_at = models.CharField(max_length=15, blank=True) meta = models.CharField(max_length=30, blank=True) amount = models.FloatField() lat = models.CharField(max_length=50, default="null") lon = models.CharField(max_length=50, default="null") def __str__(self): try: state = "Message from "+self.account.name+" for "+self.user.username except Exception: state = "Message from "+ self.card.card_number+"for"+self.user.username return state -
./manage.py shell deletes the contents of the file
In my Django project I have a couple of methods I manually call time to time for testing purposes, but lately something strange is happening. Whenever I try to run a function in the context of my Django app: ./manage.py shell > scraper/update_db.py it overwrites the contents of "update_db.py" with this: >>> I've tried creating arbitrary python files with simple print statements, but same happens to all of them. My current update_db.py looks like this: def consistency_check(): # removed my code with print statement print('Hello') consistency_check() Any ideas what is happening? I guess it's worth mentioning that I'm working in Pycharm and when I import my functions in python console, it's working just fine in there: from scraper import update_db update_db.consistency_check() # Runs smoothly -
Custom Data Model in Django
Problem: A company has to work with different forms of automobiles like car, truck, bus etc. Primary Goal: Implement a solution that allows users to define their own custom data model for their automobiles. There should be no database tables called car, truck, or bus. Instead, users should be able to create their own automobiles types and attach as many different fields as they would like. Data: For the data layer, model the automobiles types and how the generic fields and field types would relate to these automobiles types. Field types should be either text, number, date, or enum. Backend: Create two API endpoints. One that returns a single automobile type and one that returns a list of all automobiles types. Include all of the automobiles type's fields, field types, and any other data about the fields. How do I achieve this functionality using Django and any JavaScript Framework (AngularJS or ReactJS)? My question here is that: How to provide a form in JavaScript where the user can add these custom fields and then save these fields in Django? -
How to use django-markdownx in my view in similar way to admin?
I'm stuck using django-markdownx to automatically update page and to submit changes. I followed this question and answer and managed to get django-markdownx working in admin, and within my view. However in my view editing the textarea does not automatically update the page. The admin page with django-markdownx is exactly what I want, updating the textarea updates the page, but not the underlying database field until you hit save. So I then tried to rip out the admin code into my own view. In my view/template I have a form, textarea similar to admin one. I also included "/static/markdownx/js/markdownx.js" and set my form to mostly be similar to the admin page: <form method="POST" action="">{% csrf_token %} <div class="markdownx"> <textarea name="myfield" rows="10" cols="40" required="" data-markdownx-upload-urls-path="/markdownx/upload/" data-markdownx-editor-resizable="" class="markdownx-editor" id="id_myfield" data-markdownx-urls-path="/markdownx/markdownify/" data-markdownx-latency="500" data-markdownx-init="" style="transition: opacity 1s ease;"> {{ note.myfield }} </textarea> </div> <div class="markdownx-preview"> {{ note.formatted_markdown|safe }} </div> </form> This didn't work. I see periodically there is requests to /markdownx/markdownify/ when you edit in admin, but not mine. I'm not sure if I should aim to do the same or just do some timed javascript page refresh and pass all the data from within my form back to my view to then re-render … -
Django admin site lost all its formatting
I change my computer and I migrated my django project just by copying the directory created by django-admin create project from the old computer to the new one. I installed all required modules in the new computer (including django) under a new Python virtual environment, and everything worked perfectly, but the admin site of the project, that shows in plain html with no styling at all. I don't know how to fix it -
load language file temporarily for specific purpose only
I am using gettext(), which works very fine depending on the logged in user's preference. Currently, there are French and English languages. THe app is django 1.11 with python 3.4 Now, an English is loaded for user A. But he wants to send a predefined message to User B, who has indicated French as his preferred language. Without reloading the loaded language, is there a simple way to load the french language for that specific task, get the required message by its msgid and destroy it from memory? The current solution in the existing system is to read Json files for such tasks. But I am looking forward to have one language file for each language (.po) instead of Json and po files. -
Materialize css 'select' not working with django
I have this template that collects all names of authors from author_info model. These names are shown as a drop down list. When i pass the selected value to the view, it shows null. The template: <select> <option value="" disabled selected>Choose author</option> {% for author in ainfo %} <option value="{{author.name}}" name="author_name">{{author.name}}</option> {% endfor %} </select> The code snippet from views: if request.method=="POST": author=request.POST.get('author_name')