Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django cache a POST request (and it's parameters)?
I have a DRF API that implements views that allow GET and POST calls: @api_view([ 'GET', 'POST', ]) @cache_page(timeout=60 * 10) def my_view(request): # do stuff I noticed that: GET requests get cached as expected. POST requests do NOT get cached at all. Questions: Is this intended or am I doing something wrong? If this is working as intended...how can I get Django to cache POST requests as well? -
Unique URL generator for Object Items or hiding ID from URL parameter
I am working on an application built using Python3 and Django that generates PDFs (via HTML) using filled fields from a data model. I've created a URL function that takes a value of document ID and type, and then generates a PDF of that document. What I want to do is to email clients a link that contains that URL function with a specific document ID, however, the problem that I'm facing is that the generated URL has the document ID in the URL parameter, and this is terrible for security purposes as all they can do is change ID number on URL and get access to a different document (that they are not supposed to see) My questions are: A- Is there a way to create a unique link for every generated PDF that I can send to clients? B- Would it be better to create another field in the model of a randomly generated 15 character value, that I use instead of the ID in the parameter? -
How to implement a sequence of forms
New to Django here. I want to implement two forms in a sequence, where the second form depends on the saving of the first form. For example: View_A implements GET / POST methods of form A. Once Form A is submitted and saved, it will generate a unique ID. Form A also has a radio button with two choices (B and C). Depending on the choice made, I need to present the user with a second form B or a form C, where the unique ID from form A is filled automatically. The prerequisite for forms B and C is that the unique ID on form A is present. I can't use AJAX, because the form A needs to be saved first. My problem is, as soon as I hit the submit button of form A, it becomes a POST request. I can generate the unique ID and display it in the returned html template. However, it's still the same view and I don't know how the display of next form. The display of form B/C should ideally be a GET request. But I am in the POST request. I hope this is a clear enough question. Thanks -
Updating user profile - Django
I've created a template for updating account profiles using a Bootstrap snippet (from https://www.bootdey.com). With the django default format (like {{ form.as_p }}), updating accounts works (for example, when I modify the first name, it changes in the database). When I use the bootstrapp snippet, it doesn't update: it goes straight to 'homepage' without updating (as explained in views.py). In forms.py class EditAccountForm(UserChangeForm): class Meta: model = Account fields = ('email','first_name','last_name') In views.py def EditProfile(request): context= {} if request.POST: form = EditAccountForm(request.POST, instance=request.user) if form.is_valid(): form.save() email = form.cleaned_data.get("email") raw_password = form.cleaned_data.get("password1") account = authenticate(email=email,password=raw_password) return redirect('profile_page') else: context['edit_form'] = form return redirect('homepage') else: form = EditAccountForm(instance=request.user) context['edit_form'] = form return render(request,'Account/edit_page.html',context) the template: edit_profile.html (I only show the first_name part as example) <form method = "POST" class="form" novalidate=""> {% csrf_token %} <div class="row"> <div class="col"> <div class="row"> <div class="col"> <div class="form-group"> <label>First name</label> <input class="form-control" type="text" name="firstna" value={{ edit_form.first_name.value }}> </div> </div> </div> </div> <div class="row"> <div class="col d-flex justify-content-end"> <button class="btn btn-primary" type="submit">Save Changes</button> PS: I've preferred to use those snippets instead of the Django style since I find them more attractive and offer more freedom. -
In Django, why does the reverse fucntion passes a tuple as argument?
The Django tutorial uses the reverse function as HttpResponseRedirect(reverse('polls:results', args=(question.id,))). The 'results' view is defined as results(request, question_id). I understand that (question.id,) is a single element tuple but, why do we even pass a tuple instead of just question.id? -
relation does not exist - Django
I am getting this error. I have no errors on localhost but I am moving this over to Heroku and am getting this error. relation "users_profile" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "users_profile" Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="userprofile") address = models.CharField(max_length=50, blank=False) zipcode = models.CharField(max_length=5, validators=[RegexValidator(r'^[0-9]{5}$')]) date_of_birth = models.DateField(null=False, blank=False) phone_number = models.CharField(max_length=10, validators=[RegexValidator(r'^[0-9]{10}$')]) def __str__(self): return f"Extended Fields of: {self.user}" Forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True, help_text='Required. Enter a Valid Email Address.') first_name = forms.CharField(required=True, help_text='Required. Enter Your First Name') last_name = forms.CharField(required=True, help_text='Required. Enter Your Last Name') class Meta: model = User fields = ['username','first_name','last_name', 'email', 'password1', 'password2' ] def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user class ProfileCreationForm(forms.ModelForm): zipcode = forms.CharField(required=True, max_length=5) date_of_birth = forms.DateField(required=True, help_text='Required. Ex. MM/DD/YYYY, 12/30/2000') address = forms.CharField(max_length=50, required=True) class Meta: model = Profile fields = ['address', 'zipcode', 'date_of_birth', 'phone_number'] def save(self, commit=True): profile = super(ProfileCreationForm, self).save(commit=False) profile.address = self.cleaned_data['address'] profile.zipcode = self.cleaned_data['zipcode'] #zipcode in Profile Model is equal to the Field in ProfileCreationForm profile.date_of_birth = self.cleaned_data['date_of_birth'] #date_of_birth in Profile Model is equal to the Field in ProfileCreationForm if commit: profile.save() return profile … -
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