Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + SSL + nginx + uwsgi + EC2
For the past couple of week's I've been trying to deploy a Django website that I made (using HTTPS everywhere) on an Redhat Amazon EC2 instance. I deployed the website using nginx and uwsgi but when I try entering the IP address of my EC2 instance I get a connection timed out. (My professor isn't going to use a hostname) Nginx will successfully redirect me to https, but anything I've tried so far has led me to this dreaded "Connection time out, too long to respond" screen. I've reads many tutorials online and threads on stackoverflow but have had no luck so far. Any help would be greatly appreciated. uWSGI 2.0.15 compiled with version 4.8.5 20160623 - I run the command (uwsgi --ini /etc/uwsgi/sites/uwsgi-django.ini) nginx 1.12.1 - I have it setup as a service (sudo service nginx start) Python 3.4 Django 2.0.1 My Amazon EC2 instance has port 80 and 443 open. My Nginx configuration is as follows: events { worker_connections 1024; } http { # nginx.conf # Redirects any requests on port 80 (http) to https: server { server_name 35.164.X.X; listen 80 default_server; rewrite ^ https://35.164.X.X$request_uri? permanent; access_log /spool/nginx-redirect.log; error_log /spool/nginx-redirect-error.log; } # django pass-thru via uWSGI, only from … -
Django: How to display formset as radio button group
I have my Form and Formset defined as below: class MCQChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', 'is_choice_correct'] labels = { 'choice_text': "", 'is_choice_correct': "" } widgets = { "choice_text": forms.Textarea(), # attrs={'rows': 2, 'cols': 15} # "is_choice_correct": # do something here } MCQSingleChoiceFormSet = formset_factory(MCQChoiceForm, min_num=4, max_num=4, extra=0) MCQSingleChoiceFormSet represents choices for a problem which can only have once correct choice. Choice.is_correct_choice field indicates if the given choice is correct. My Question: How can I display is_choice_correct field as a single radio button? True or False values saved in database will depend on whether the radio button is selected or not. How can I change my code so that only one of the radio buttons in the formset is selected? -
Allow user to edit a blog post live with Django
I'm making a blog feature on a website and I want to allow the User to edit the text of the post without taking them to a different view. Just like you can edit a post on Facebook, or on Stack. This is just the piece of code containing the form. {% if user.is_authenticated %} <button style="text-align:left;" class="content-editor"> <!-- line displays the text, I want to be able to make this editable on click --> <p class='body-font'>{{ post_detail.text|linebreaksbr }}</p> <!--the actual form that allows you edit, obviously it's just sitting there right now --> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </button> {% endif %} I'm not sure where to go from here, in my mind when the button is clicked, I should have some HTML that appears and replaces the HTML that was displaying just the text. The new editable text would be a model that is created by and passed from a view right? -
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.