Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unittest throwing disabling autocommit
I'm trying to write Django 1.11 Selenium unittests using the LiveServerTestCase, but I'm getting the strange non-deterministic error: TransactionManagementError: Your database backend doesn't behave properly when autocommit is off. Turn it on before using 'atomic'. The traceback follows to the point in a test where I call a factory method, which I create using the DjangoModelFactory class in factory-boy like: class CompanyFactory(factory.DjangoModelFactory): name = factory.Faker('company') status = factory.LazyFunction(models.Status.objects.first) region = factory.SubFactory(RegionFactory) owner = factory.SubFactory(UserFactory) class Meta: model = models.Company and my test method looks like: class Tests(StaticLiveServerTestCase): def test_company(self): autocommit = transaction.get_autocommit() print('autocommit:', autocommit) self.assertEqual(autocommit, True) company = CompanyFactory() # This throws the exception # test stuff... The StaticLiveServerTestCase/LiveServerTestCase inherits the TransactionTestCase, so each test gets wrapped in an atomic context manager, which creates a transaction in auto-commit mode. When I first started getting this error, I added the print of the output for transaction.get_autocommit() to confirm where autocommit was being turned off...but to my amazement, it's not. The test confirms autocommit is correctly turned on...until the call to the factory method. So then I thought the factory class is somehow breaking the transaction. However, when I went to test just the test method that was failed...I found it passed … -
How to Bundle Polymer Elements in a Django App
I'm using Polymer 2.0 and Django 1.9 in my project. Currently my Polymer elements are loading extremely slow in my app. So I've decided to polymer-bundle my elements. I'm facing a problem with that right now whereas my elements don't have just 1 entry-point. I'm used to loading templates in my views with request like index.html or login.html etc. Those are my entry points. But polymer-build only allows 1 entry point e.g. index.html. I want to be able to bundle my polymer-elements but how do I do so if I have more than 1 entry-point? -
django ListView query_set code abbreviation
The codes are as models.py class Firm(models.Model): name = models.CharField(unique=True, max_length=50, verbose_name="Firma Adı") slug = models.SlugField(unique=True, editable=False, max_length=50) class Worksite(models.Model): firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=50, verbose_name="Şantiye Adı") slug = models.SlugField(unique=True, editable=False, max_length=50) class Subcontractor(models.Model): worksite = models.ForeignKey('Worksite', on_delete=models.CASCADE) firm = models.ForeignKey('Firm', related_name="subcontractors", on_delete=models.CASCADE) Can the queryset code be written shorter? views.py class SubcontractorListView(ListView): template_name = 'firm/subcontractor_list.html' context_object_name = "firms" def get_queryset(self): ws = self.request.user.firm.worksites.values_list('id', flat=True) ss = Subcontractor.objects.values_list('firm_id', flat=True).filter(worksite_id__in=ws) return Firm.objects.filter(id__in=ss) Do you have different and short solutions? template {% for firm in firms %} <div class="btn btn-outline-secondary text-left button">{{ firm }} </div> {% endfor %} -
Why this django form not pass value back using initial argrument from view.py?
I have a form: class ConfigNotifyForm(forms.Form): sensor_name = forms.ChoiceField(widget=forms.Select(), label="Sensor", choices=[], required=True) value_min = forms.FloatField(label="Value Min", required=True) value_max = forms.FloatField(label="Value Max", required=True) def __init__(self, *args, **kwargs): super(ConfigNotifyForm, self).__init__(*args, **kwargs) # Get 'initial' argument if any initial_arguments = kwargs.get('initial', None) sensor_choices = '' if initial_arguments != None: #for choice in initial_arguments.get('src_choices'): sensor_choices = tuple(initial_arguments.get('src_choices')) self.fields['sensor_name'].choices = sensor_choices It's work ok with template. But when submit, sensor_name not in cleandata except value_min, and value_max. So, it not pass form.is_valid. But, if I code init like this: def __init__(self, *args, **kwargs): super(ConfigNotifyForm, self).__init__(*args, **kwargs) sensor_choices = ( ('', 'Select'), ('a0', 'Ndo'), ('a1', 'pH'), ('a2', 'DO')) self.fields['sensor_name'].choices = sensor_choices It's OK. Form is valid. I don't know why. Can anyone help me explain and resolve this issue ? Thanks -
type of object 'NewsletterUsuario' has no len()
i'm new using django as a framework, i got a problem when i try to save a newsletter on my custom control_panel, i can save the message but the web crash and showme a typeError telling me about a class model i made 'NewsletterUsuario' but just on de custom control_panel, in django admin mode it works normally, the problem start to happen after i eliminate some files from a app that i did not want to use and even i did a git reset to a working version still get this similar typeError, here is my models, views and traceback: models.py from django.db import models # Create your models here. class NewslettersUsuario(models.Model): email = models.EmailField() fecha_agregado = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Newsletter(models.Model): EMAIL_STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) subject = models.CharField(max_length =250) body = models.TextField() email = models.ManyToManyField(NewslettersUsuario) status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.subject Views.py from django.conf import settings from django.contrib import messages from django.shortcuts import render from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import get_template from .models import NewslettersUsuario, Newsletter from .forms import NewslettersUsuarioSignUpForm, NewsletterCreacionForm # Create your views here. def newsletter_signup(request): form = NewslettersUsuarioSignUpForm(request.POST or None) … -
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