Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I to test an Internet connection with Django?
I need to check with my application when there is an internet connection in order to send emails, it's happening to me that every time I send an email it's lost because there is some internet failure. Also, how can I put these emails in a queue of pending so that once there is connection are sent ?. -
How to combine any fields in one in Django filters
I wonder how you combine search from multiple fields into one. The fields would be textoQuestao, perguntaQuestao, aOpcao, bOpcao, cOpcao, eOpcao, eOpcao. I would like all of these fields to be combined into one called texto and to search all selected fields. filters.py class FiltroQuestoes(django_filters.FilterSet): texto = class Meta: model = Questao fields = ['textoQuestao','perguntaQuestao','aOpcao','bOpcao','cOpcao','dOpcao','eOpcao','idProva','idQuestao','idCategoria'] views.py def FiltroDeQuestoesView(request): qs = filter(request) context = { 'queryset': qs, 'categorias': Categoria.objects.all(), 'provas': Prova.objects.all() } return render(request, "polls/pesquisa.html", context) def filter(request): qs = Questao.objects.all() categorias = Categoria.objects.all() prova = request.GET.get('prova') provas = Prova.objects.all() questao = request.GET.get('questao') categoria = request.GET.get('categoria') return qs search.html {% block content %} <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.texto.label_tag }} {% render_field filter.form.texto class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.idProva.label_tag }} {% render_field filter.form.idProva class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.idQuestao.label_tag }} {% render_field filter.form.idQuestao class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.idCategoria.label_tag }} {% render_field filter.form.idCategoria class="form-control" %} </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> {% endblock %} -
How to fix "django ImproperlyConfigured exception: Requested setting, You must either define the environment variable DJANGO_SETTINGS_MODULE ."
Traceback (most recent call last): File "./manage.py", line 5, in from settings import base, development File "/home/ijdev/Área de Trabalho/izio/izio-bank/settings/base.py", line 12, in from corsheaders.defaults import default_methods as cors_default_methods File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/corsheaders/defaults.py", line 14, in CORS_ALLOW_HEADERS = getattr(settings, 'CORS_ALLOW_HEADERS', default_headers) File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/django/conf/init.py", line 79, in getattr self._setup(name) File "/home/ijdev/Área de Trabalho/izio/Izioenv/lib/python3.7/site-packages/django/conf/init.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting CORS_ALLOW_HEADERS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Our django application use DJANGO REST framework, Oauth2 and double settings - one to development and other to production, and a general one called base.py. The development.py is currently setted up on manage.py file. We are also using django-cors-headers package. This exception starts yesterday when I use ./manage.py runserver or other command. I tryed to fix it. I read many posts from here (Stackoverflow) and in other websites, but I did not make it. Could someone help me, please? -
Django allauth: Extract activate_url for mailchimp
I want to use Mailchimp to handle the email communication. To do this I have to send the email activation URL (used by allauth to comfirm the email address) to Mailchimp. How can I retrieve the activation URL including key from Django allauth? -
Django - query CharFields ignoring local characters
Is there a way in Django to filter some CharField/TextField using string containing only ASCII characters but matching records in the database that may contain non-ASCII characters? eg. I would like below code to find a city with name set to Köln: from django.db import models class City(models.Model): name = models.CharField(max_length=30) City.objects.filter(name__<some lookup>='koln') -
Django form fields not showing up on webpage
I am doing a "Contact Us" section on my site. When I goto the contact section on my webpage it displays like: This I'm not sure if its my views because that section of the page shows up like http://127.0.0.1:8000/#contact-section ? forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() subject = forms.CharField(max_length=100) message = forms.CharField(widget=forms.Textarea) Views.py from django.shortcuts import render from django.views.generic import View from django.http import HttpResponse from contact.forms import ContactForm def index_view(request): return render(request, 'index.html', {}) def post_view(request): return render(request, 'single.html', {}) def contact_us(request): if request.method == 'POST': form =ContactForm(request.POST) if form.is_valid(): # Send email goes here return HttpResponse("Thanks for contacting, We will be in touch soon!") else: form = ContactForm() return render(request, 'index.html', {'form': form}) Template <div class="row no-gutters block-9"> <div class="col-md-6 order-md-last d-flex"> <form method="POST" action="." class="bg-light p-4 p-md-5 contact-form"> <div class="form-group"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send Message" class="btn btn-primary py-3 px-5"> </div> </form> </div> -
Filter objects based on a specific category name
I'm trying to filter all products whose category name is 'Books'. See below what I have tried but I'm getting an empty queryset. Here is my models.py just in case: from django.db import models from django.urls import reverse [...] class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10) year = models.PositiveSmallIntegerField() image = models.ImageField(upload_to=get_image_path, blank=True, null=True) date_added = models.DateTimeField(auto_now=True, null=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) [...] class Category(models.Model): parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name I have tried this: >>> from products.models import Product, Category >>> c = Category(name='Books') >>> c1 = Category(name='Textbooks', parent=c) >>> c2 = Category(name='Primary school', parent=c1) >>> p = Product(title='spam', description='spameggs', price=200, year=2018, category=c2) >>> for x in (c, c1, c2, p): ... x.save() ... >>> Product.objects.get(category=c2) <Product: Product object (1)> >>> Product.objects.filter(category__name='Books') <QuerySet []> -
Django-model-utils UnicodeEncodeError
I have my book model in models.py, that contains title as CharField: title = models.CharField( verbose_name = "Название книги", max_length = 75, null = False, unique = True ) Also, I'm using django-model-utils to track this, and other fields changes. When I'm trying to add book with title Колобок, I got this error: 'locale' codec can't encode character '\u041a' in position 0: encoding error I'm afraid that, if I type anything in other fields of this model in Cyrillic, it throws me same error. Also, in my models.py I have model for Author with 1 field: author = models.CharField(max_length=80, null=False) But, in this case, I have no error. I think it django-model-utils's problem. -
The view FG.contact.contact didn't return an HttpResponse object. It returned None instead
I have gone through numerous explanations of the error "...didn't return an HttpResponse object. It returned None instead." I am unable to find what I am doing wrong even after following the django documentation instructions. Can someone please help. Error code: [1]: https://i.stack.imgur.com/TWIBb.png my code (as per django): [1]: https://i.stack.imgur.com/Yav7S.png -
How to access label from view.py file
I'm trying to get the label tag text of HTML code but I'm not abling to get it. At previous work i get the data from textbox but now i'm not abling to get the label text html file <label name="hello_text">HELLO</label> <input type="text" name="textbox1"/> view.py file if request.method == "POST": textbox = request.POST["textbox1"] val = request.POST["hello_text"] #didn't get the value of label here I want to receive the text value of label -
Not understanding how Python Class works
I am in need of some help understanding how Python and Django work based on some code I'm looking at. Say my urls.py file has the following router.register(r'testing', SomeClass) and then in my views.py file, it is set up like this: class SomeClass(): database = DatabaseValues.objects.all() def first_def(self): # do some filtering and such on db results return database def second_def(self): a = 20 b = 40 return b - a def third_def(self): z = 200 y = 400 return y - z When the SomeClass is called in UI by hitting the http://localhost/testing url, what is returned?? -
How to get permission associated with view programatically
In Django I have a function that provides a list of all URL Patterns for my system. I am attempting to create a search feature that shows users links to a list of urls that they have permissions to view, but I cannot seem to figure out how to grab the associated permission from the view function. How can I do this? Here is my code so far: def get_url_patterns(): from django.apps import apps list_of_all_urls = list() for name, app in apps.app_configs.items(): mod_to_import = f'apps.{name}.urls' try: urls = getattr(importlib.import_module(mod_to_import), "urlpatterns") list_of_all_urls.extend(urls) except ImportError as ex: # is an app without urls pass for thing in list_of_all_urls: # print(type(thing)) # print(type(thing.callback.__name__)) print(thing.callback.__dict__) return list_of_all_urls -
Django returns variable name not value in request.POST.get()
I define a <select/> in my django template as follows {% get_selected_item as selected_item %} <select name="item_selected" id="item_selected"> {% for item in items %} <option value=item{% if selected_item == item %} selected{% endif %}>{{ item }}</option> {% endfor %} </select> But when I examine the result of request.POST.getlist('item_selected') or request.POST.get('item_selected') the result is the string 'item', not the string value of the selected item. The items are not part of a model but are provided in a session variable. -
ngrok doesn't lift my local django web server
I have problems with negrok, it does not raise my local django web server, a few days ago everything worked correctly but a normal day, without having touched anything, it stopped working. Run the following: python manage.py runserver Everything works normally and correctly. Now I execute the following, in order to raise the local django server: ./ngrok http 8000 ngrok runs correctly without any problem but when accessing the ngrok link, the page is loading and everything is blank and does not work .... This appears in ngrok: ngrok by @inconshreveable (Ctrl+C to quit) Session Status online Account Julio (Plan: Free) Version 2.3.34 Region United States (us) Web Interface http://127.0.0.1:4040 Forwarding http://33822c5a.ngrok.io -> http://localhost:8000 Forwarding https://33822c5a.ngrok.io -> http://localhost:8000 Connections ttl opn rt1 rt5 p50 p90 2 0 0.03 0.01 0.20 0.21 HTTP Requests ------------- GET / 400 Bad Request GET / 400 Bad Request And this appears in django: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 25, 2019 - 17:23:19 Django version 2.2.2, using settings 'ibme_proyect.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Invalid HTTP_HOST header: '33822c5a.ngrok.io'. You may need to add '33822c5a.ngrok.io' to ALLOWED_HOSTS. Bad Request: … -
Gender Specific Translations
Task I have a extended UserModel, which includes the users gender: class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... gender = models.CharField( _('Gender'), max_length=1, choices=( ('f', _('Female')), ('m', _('Male')), ), default='m' ) ... I would like to display a gender specific translations in my template: Please contact him. or Please contact her. Questions ? How would you handle the task? Is there a better solution, than my current (see: Answers)? maybe something equal as pluralization is handled -
Uploaded dynamic file cannot be found
I uploaded a dynamic picture named "IMG_4606.png" through admin page and when loading it through another app, it is not being found. setting.py import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(BASE_DIR, 'project_headshots') MEDIA_URL = '/project_headshots/' STATIC_ROOT = os.path.join(BASE_DIR, "static")` models.py from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.ImageField(null=True, blank=True, upload_to="iad") ` html code img class="card-img-top" src="{{project.image.url}}" alt="" ERROR: `Not Found: /projects/project_headshots/iad/IMG_4606.png [25/Sep/2019 16:28:34] "GET /projects/project_headshots/iad/IMG_4606.png HTTP/1.1" 404' -
Does django manage.py migrate command creates database/schema if not exists?
I have an existing django project and need to create an instance of it in a new environment with new database. I have the database connection configured in the settings file. The schema does not exist. If I run the manage.py migrate command, does it also create the schema? It looks like it assumes the schema already exists because I am getting an error django.db.utils.OperationalError: (1049, "Unknown database 'my_db'"). Just wondering if I have to create the database first or if some django command is available to create it if it does not exists. -
Django - how to make a link in an html template open an app and pass a objects value as a parameter
Hello I have an app that displays some database information in a table. Inside of the html template I am making an edit link that I want to open another app(page viewLit) while passing a value to it's view. I have added my code below. My question is I am unsure of how to make this links url and pass the object data located inside circuit.circuitid along with it. I haven't been able to find the right way to code this yet and this is just how I thought that this should be done. If anyone has a better idea I am open to suggestions. search_custom.html(code for link) {% for circuit in filter.qs %} <tr> <td class="actions"> <a href="?" class ="view-item" title ="View">View</a> </td> <td>{{ circuit.circuitid }}</td> </tr> {% endfor %} myapp/myapp/urls.py urlpatterns = [ path('viewLit/', include('viewLit.urls')), ] myapp/viewLit/urls.py urlpatterns=[ path('viewLit/circuitid.id', views.viewLit, name='viewLit'), ] myapp/viewLit/views.py def viewLit(request, circuitid): #display records fields here return HttpResponse("You are at the viewLit page!") -
Django Ajax Unexpected token < in JSON at position 1
I am working on a simple form with Django. My code seems to be all right, but this snippet does not seem to send any data. document.getElementById('schoolAddForm').addEventListener('submit', function (e) { e.preventDefault(); let schoolname = document.getElementById('schoolname').value; alert(schoolname) $.ajax({ method: "POST", url: "/dashboard/schools", data: { 'schoolname': schoolname, 'added_by': {{ user.id }}, }, dataType: 'json', success: function (data) { alert(data) }, error: function (xhr, errmsg, err) { $('#results').html("<div class='alert-box alert-danger alert radius' data-alert>Oops! We have encountered an error: <strong>" + err + "</strong>. Reload page and try again"); // add the error to the dom console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }) }) it results to an error SyntaxError: Unexpected token < in JSON at position 1 I have gone through couple times, it seems the url is the one that brings the error, I dont know why, I simply cant progress past this -
Use model current object in django model form
I want to create queryset from current curriculum that pass from View. This is my form: class MyForm(ModelForm): valid_students = Enrollment.objects.filter(curriculum=self.curriculum) students = forms.ModelMultipleChoiceField(queryset=valid_students) class Meta: model = ArgumentGroup fields = ( 'title', 'curriculum', 'teacher_assistant', 'students', ) How can I get students that have specific curriculum that pass from the view? -
What is best practice to make website in container? How to start with developing Django+postgres app using containers?
I am new in container based application. I want to make a simple django based website. I have installed minishift and sample django+postgres template to start with.After making changes in this sample application and finsh with development on website. I am planning to use the same application and migrate entire application to google cloud or azure after development to make it live? PS: I want to learn end to end container based applications, (e.g. openshift). Now the question is: is this a good approach to build a new website or there is any other best practice? -
Error 5 Access denied on IIS (python.exe)
I have a project in Python 2.7.10/Django 1.8.5 this portal use a function that create a directory and store images and video in this directory I use this portal with IIS 7.5 but when this function is used gives me this error: WindowsError at /somedir/0001/ [Error 5] Acceso denegado: u'D:\\directory\\data\\something\\01' Request Method: POST Request URL: http://localhost:8001/somedir/0001/ Django Version: 1.8.5 Exception Type: WindowsError Exception Value: [Error 5] Acceso denegado: u'D:\\directory\\data\\something\\01' Exception Location: C:\Python27\lib\os.py in makedirs, line 157 Python Executable: C:\Python27\python.exe Python Version: 2.7.10 Python Path: ['.', 'C:\\inetpub\\wwwroot\\miproyect', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] I tried give all the permissions to the users/groups IUSR/IIS_IUSR on the directory and the python.exe but gives the same error. Thanks in advance for any help. -
Is it possible to use Django-Filter for a ManyToMany relationship?
Essentially, I've been using Django-Filter to filter a large list of publications on various fields. One field is keywords, which has a many to many relationship through a PublicationKeywords table. The models look as follows (withholding certain fields and information): class Publication(models.Model): keywords = models.ManyToManyField(Keyword, through='PublicationKeywords') class Keyword(models.Model): value = models.CharField(max_length=100) class PublicationKeywords(models.Model): keyword = models.ForeignKey(Keyword, db_column='keyword_id', on_delete=models.SET_NULL, null=True) publication = models.ForeignKey(Publication, db_column='publication_id', on_delete=models.SET_NULL, null=True) So, I'm wondering if it's at all possible to use a ModelChoiceFilter in this case to do something similar to PublicationKeywords.objects.filter(keyword__value_in=keyword_list).distinct('publication') Basic filter set up looks as follows class PublicationFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='icontains') state = django_filters.ChoiceFilter( choices=STATE_CHOICES) sac = django_filters.ModelChoiceFilter(queryset=Sac.objects.all()) published_date_after = DateFilter( field_name='published_date', lookup_expr=('gte')) published_date_before = DateFilter( field_name='published_date', lookup_expr=('lte')) data_begin_year = django_filters.NumberFilter( lookup_expr='gte') data_end_year = django_filters.NumberFilter( lookup_expr='lte') keywords = django_filters.ModelChoiceFilter(queryset=??????) # TODO figure out how to get this keywords filter to work like # PublicationKeywords.objects.filter(keyword__value_in=keyword_list).distinct('publication') class Meta: model = Publication strict = False fields = ['title', 'state', 'sac', 'published_date', 'data_begin_year', 'data_end_year', 'keywords'] def __init__(self, *args, **kwargs): super(PublicationFilter, self).__init__(*args, **kwargs) if self.data == {}: self.queryset = self.queryset.none() -
resets error during normal import on python django
I have an import error. I have a User model on models.py, I import it on serializer.py. Previously, everything worked as it should, I even worked with other files and suddenly an error appears on serializer.py. And sorry for my English writing via google translate. models.py class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField('телефон номер', max_length=20, unique=True,db_index=True) avatar = models.ImageField('Аватар', blank=True, null=True, upload_to=get_timestamp_path, default='images/user.png') nickname = models.CharField('Никнейм', max_length=40, null=True, blank=True) register_date = models.DateField('Дата регистрация', auto_now_add=True) is_active = models.BooleanField('Активен', default=True) is_admin = models.BooleanField('Суперпользователь', default=False) region = models.ForeignKey(Region, verbose_name="", on_delete=models.CASCADE, null=True, blank=True) def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) self.nickname = 'User' + str(self.id) super(User, self).save(*args, **kwargs) def get_full_name(self): return self.phone_number def is_staff(self): return self.is_admin def get_short_name(self): return self.phone_number def __str__(self): return self.phone_number USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name= 'User' verbose_name_plural = 'Users' serializer.py from rest_framework import serializers from .models import User error File "/home/c2dent/afmoon/backend/afmoon/main/models.py", line 7, in <module> from .utilities import get_timestamp_path File "/home/c2dent/afmoon/backend/afmoon/main/utilities.py", line 8, in <module> from .serializers import HouseSerializer, LandSerialzier, VacancySerializer, ResumeSerializer, SecondSerializer, PersonalsClothesSerializer, PersonalsShoesSerializeres, CommonProductDetail, AvtomobilSerialzier, ApartmentSerializer File "/home/c2dent/afmoon/backend/afmoon/main/serializers.py", line 2, in <module> from .models import User, BaseProduct, Avtomobil, Apartment, House, Land, Vacancy, Resume, Second, Personals_clothes, Personals_shoes ImportError: cannot import name 'User -
takes exactly 2 arguments (1 given)
It is views def hi(request,hh_id): return HttpResponse(hh_id) it is local urls urlpatterns = [ url('<int:hh_id>',views.hi) ] 1.i create a django project but it appears 2.what can i do now ?