Django 3: ValidationError is not displayed - python

I recently started learning Django framework and had some problems with variable validation. When I try to output field.errors variable in html file there is no output, although when I pass error variable from create method, it outputs "errors" list (i.e. clean_number method is supposed to work) and when I fix them, list gets smaller (i.e. clean_number method does not work). Please tell me what I am doing wrong. Thanks in advance.
File create.html
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport>
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Adding a train to the list</title>
<link href="https://getbootstrap.com/docs/5.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<style>
.sidenav {
height: 100%;
width: 267px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #f2f2f2;
overflow-x: hidden;
padding-top: 50px;
}
.container {
max-width: 900px;
}
</style>
</head>
<body>
<body class="bg-light">
<header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3 fs-6" href="/">Home page</a>
<button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<input class="form-control form-control-dark w-100 rounded-0 border-0" type="text" placeholder="Search" aria-label="Search">
<div class="navbar-nav">
<div class="nav-item text-nowrap">
<a class="nav-link px-3"></a>
</div>
</div>
</header>
<div class="container">
<main>
<div class="row g-5">
<div class="py-5 text-center">
<h2>Add a train</h2>
<p class="lead">On this page, you need to fill in all the fields and follow the instructions.</p>
<form method="post">
<div class="row g-3">
{% csrf_token %}
{% for field in form %}
{{ field }}
<div class="alert alert-danger">
{{ field.errors }}
{% if !field.errors %}
{{ error }}
{% endif %}
</div>
{% endfor %}
<hr class="my-4">
<button class="w-100 btn btn-primary btn-lg" type="submit">Save changes</button>
</div>
</form>
</div>
</div>
</main>
</div>
</body>
</body>
</html>
File forms.py
from .models import Train
from django.forms import ModelForm, NumberInput
from django.core.exceptions import ValidationError
class TrainForm(ModelForm):
class Meta:
model = Train
fields = ["number", "amount_stops"]
widgets = {
"number": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the train number',
}),
"amount_stops": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the number of stops'
})
}
def clean_number(self):
number = self.cleaned_data['number']
if number > 100:
raise ValidationError('The number is over 100!')
return number
def clean_amount_stops(self):
amount_stops = self.cleaned_data['amount_stops']
if amount_stops > 100:
raise ValidationError('The amount of stops is over 100!')
return amount_stops
File views.py
from django.shortcuts import render, redirect
from .forms import TrainForm
def create(request):
error = ''
if request.method == 'POST':
form = TrainForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
error = form.errors
form = TrainForm()
context = {
'form': form,
'error': error
}
return render(request, 'main/create.html', context)
Changed the template, but still nothing has changed.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }}<p>
{{ field.errors }}<p>
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
===========================
10/02/23: I tried to re-create the project without using the PyCharm IDE, just using Windows PowerShell, but nothing has changed, as it is not displayed and does not show(. My project creation:
Creating an AppDjango folder
In Terminal PowerShell:
-> cd D:\AppDjango\ - Navigate to Project
-> PS D:\AppDjango> python -m venv virenv
-> PS D:\AppDjango> virenv\Scripts\Activate.ps1
-> (virenv) PS D:\AppDjango> python -m pip install Django
-> (virenv) PS D:\AppDjango> django-admin startproject AppDjango
-> (virenv) PS D:\AppDjango> cd AppDjango
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py runserver
-> (virenv) PS D:\AppDjango\AppDjango> ^C (Ctrl + C) - Finish process
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py startapp MainApp
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py migrate
Next, I changed the configuration of the setting.py file:
import os <- Only added
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MainApp' <- Only added
]
...
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR,'templates'),], <- Only changed
...
},
]
I added the table to the models.py file:
from django.db import models
class Train(models.Model):
number = models.IntegerField()
amount_stops = models.IntegerField()
def __str__(self):
return str(self.number)
I created the forms.py file and added the code:
from .models import Train
from django.forms import ModelForm, NumberInput
from django.core.exceptions import ValidationError
class TrainForm(ModelForm):
class Meta:
model = Train
fields = ["number", "amount_stops"]
widgets = {
"number": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the train number',
}),
"amount_stops": NumberInput(attrs={
'class': 'form-control',
'placeholder': 'Enter the number of stops'
})
}
def clean_number(self):
number = self.cleaned_data['number']
if number > 100:
raise ValidationError('The number is over 100!')
return number
def clean_amount_stops(self):
amount_stops = self.cleaned_data['amount_stops']
if amount_stops > 100:
raise ValidationError('The amount of stops is over 100!')
return amount_stops
I added the code to the views.py file:
from django.shortcuts import render, redirect
from .forms import TrainForm
def create(request):
errors_Main = ''
if request.method == 'POST':
form = TrainForm(request.POST)
if form.is_valid():
form.save()
else:
errors_Main = form.errors
form = TrainForm()
context = {
'form': form,
'errors_Main': errors_Main
}
return render(request, 'MainApp/create.html', context)
I created a new file D:\AppDjango\AppDjango\MainApp\urls.py and added the code:
from django.urls import path
from . import views
urlpatterns = [
path('', views.create, name='create')
]
I also changed the file D:\AppDjango\AppDjango\AppDjango\urls.py (the one that originally generated Django):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('MainApp.urls'))
]
I created a template file .\MainApp\templates\MainApp\create.html and added code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field }}<p>
{% for error in field.errors %} <- added
{{ error }}
{% endfor %}
{% endfor %}
<button type="submit">Save</button>
</form>
</body>
</html>
Recent changes to the PowerShell Terminal:
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py makemigrations
Migrations for 'MainApp':
MainApp\migrations\0001_initial.py
- Create model Train
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py migrate
Operations to perform:
Apply all migrations: MainApp, admin, auth, contenttypes, sessions
Running migrations:
Applying MainApp.0001_initial... OK
-> (virenv) PS D:\AppDjango\AppDjango> python manage.py runserver
Result: Still does not display errors. Can you please tell me at what stage I screwed up?

Try to use the looping syntax of showing errors so instead of only {{field.errors}} use it as following:
{% for error in field.errors %}
{{ error }}
{% endfor %}

Thank you #Sunderam Dubey for helping. I found the answer to my question. The problem was in the create method, I rewrote it a little differently (code below) and I was able to display the error text:
def create(request):
form = TrainForm()
if request.method == "POST":
form = TrainForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
return render(request, "main/create.html", {"form": form})

Related

Select objects from django model based on user input

I have a large django model with about 800 objects and I want to create a view in which the user can select a certain number of those objects to pass to another view for further processing. The fact that there are so many objects of the model makes listing all the objects very unpractical, as the user would have to scroll through 800 objects.
In order to address this problem, I want to place an as-you-type search-bar in the top of the view so that the user can type the name of the objects and select them by clicking them. When the objects are selected, they should appear under the search-bar as tags that the user can remove by clicking an "x" next to each one.
When the user has made all the required selections, then they should be able to click a button and jump to the next view where those selected objects are accessible.
The model I am using can be simplified to:
class Song():
song_name = models.CharField(max_length=256)
song_author = models.CharField(max_length=256, blank=True)
song_content = models.TextField()
def __str__(self):
return self.song_name
class Meta:
ordering = ['song_order']
song_order = models.PositiveIntegerField(editable=False, db_index=True)
So far I have been able to make a view to search through the model.
mytemplate.html
<!DOCTYPE html>
{% load static %}
<html style="height: 100%;" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons" as="style" onload="this.rel='stylesheet'">
<link rel="preload" href="https://unpkg.com/bootstrap-material-design#4.1.1/dist/css/bootstrap-material-design.min.css" as="style" onload="this.rel='stylesheet'">
<link rel="stylesheet" href="{% static 'css/main.css' %}">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
</head>
<body>
{% block body_block %}
<div class="container" style="padding-bottom:40px;margin-top: 35px;">
<div class="form-group">
<label for="searchInput" class="bmd-label-floating">Search</label>
<input type="text" class="form-control" id="searchInput" oninput="filter()">
</div>
<ul class="list-group bmd-list-group-sm">
{% for song in songs %}
<div
class="list-group-item"
data-title="{{song.song_name}}"
data-author="{{song.song_author}}"
data-lyrics="{{song.song_content}}">
<h4>
{{song.song_name}}
{% if song.song_author %}
({{ song.song_author }})
{% endif %}
</h4>
</div>
{% endfor %}
</ul>
</div>
<script>
$('#searchInput').focus();
function short(s) {
let punctuationRegEx = /[.,\/#!$%\^&\*;:{}=\-_`~()]/g;
return s.replace(punctuationRegEx, '')
.toLowerCase()
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "");
}
function filter() {
let f = short($('#searchInput').val());
$('.list-group-item').each(function (index) {
if (short($(this).data('title') + "").includes(f) ||
short($(this).data('author') + "").includes(f)
) {
$(this).show();
} else {
$(this).hide();
}
});
}
</script>
{% endblock %}
</body>
</html>
views.py
class SongListView(ListView):
context_object_name = 'songs'
model = Song
template_name = "songapp/mytemplate.html"
Any ideas on how to do the selection?
I have created a part inventory program with the as you type search.
It's a complete example of ajax call for search and database.
You can modify it to show the results under the search with the X.
https://github.com/edcodes/Django-Parts-Inventory

MultiValueDictKeyError at /main/add at 'num1'

From below Coded project i want to add two numbers and want to print their resultant value. All things goes smoothly but when i try to print the resultant value it make me causes a "MultiValueDictKeyError" errors. I have searched and tried so many ways but failed to resolve the problem.
The project tree look like this
project files tress
views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
def home(request):
return render(request, 'base.html')
#csrf_exempt
def add(request):
val1 = int(request.POST['num1'])
val2 = int(request.POST['num2'])
res = val1 + val2
return render(request, "main/index.html", {'add_result': res})
Index.html
{% extends 'base.html' %}
{% block content %}
<h3>This two number adding form</h3>
<form action="{% url 'add' %}" method="POST">
Enter the first here: <input type="text" name="num1" placeholder="First Number"><br>
Enter the second here: <input type="text" name="num2" placeholder="Second Number"><br>
<input type="submit">
</form>
<hr>
<div>
Result : <p>{{ add_result }} </p>
</div>
{% endblock %}
base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0,
minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ADDTWONUMBER</title>
</head>
<body>
<H4>THIS IS FORM OF ADDING TWO NUMBER</H4>
<li>click here to add two number</li>
<div>
{% block content %} {% endblock %}
</div>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home'),
path('main/add' , views.add, name = 'add'),
]
Errors
> MultiValueDictKeyError at /main/add
> 'num1'
> Request Method: GET
> Request URL: http://127.0.0.1:8000/main/add
> Django Version: 3.0.4
> Exception Type: MultiValueDictKeyError
> Exception Value: 'num1'
> Exception Location: /home/hudacse6/Env/lib/python3.7/site-
packages/django/utils/datastructures.py in __getitem__, line 78
> Python Executable: /home/hudacse6/Env/bin/python
> Python Version: 3.7.4
> Python Path:
['/home/hudacse6/pr1_todoapps',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/home/hudacse6/Env/lib/python3.7/site-packages']
> Server time: Wed, 18 Mar 2020 17:09:20 +0000
Error in picture
How to do dealt with this error?
Have you tried with get() method on request.POST ?
val1 = int(request.POST.get('num1', None))
val2 = int(request.POST.get('num2', None))

How do I fix '... is not a registered namespace' Django 2.1 error

so Im building and simple mooc plataform using Django 2.1 and Im having a problem.
Here you can find my entire project but ill describe all situation above, and here u can find a entire printscreen of django error.
So i have this project called TamerMooc, this project has 2 apps. A core app and a courses app.
This is the /courses/views.py file:
from django.shortcuts import render, get_object_or_404
from .models import Course
def index(request):
courses = Course.objects.all()
template_name = 'courses/index.html'
context = {
'courses':courses
}
return render(request, template_name, context)
def details(request, slug):
course = get_object_or_404(Course, slug=slug)
template_name = 'courses/details.html'
context = {
'course': course
}
return render(request, template_name, context)
And this is the /courses/urls.py file:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('',views.index ,name='index'),
path('<slug:slug>', views.details , name='details'),
]
And at least the /core/templates/base.html file quoted in the error file.
<!doctype html>
{% load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Simple MOOC - Uma simples plataforma de ensino a distância" />
<title>Tâmer MOOC</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css">
<link rel="stylesheet" href="{% static 'css/styles.css' %}" />
</head>
<body>
<div class="header">
<div class="pure-menu pure-menu-open pure-menu-fixed pure-menu-horizontal">
<a class="pure-menu-heading" href="{% url 'home' %}">TÂMER MOOC</a>
<ul>
<li class="pure-menu-selected">Início</li>
<li>Cursos</li>
<li><a href="{% url 'contact' %}"}>Contato</a></li>
</ul>
</div>
</div>
<div class = "content">
{% block content %}{% endblock %}
<div class="footer">
Tâmer MOOC - Uma simples plataforma de ensino a distância
</div>
</div>
<script src="http://yui.yahooapis.com/3.12.0/build/yui/yui-min.js"></script>
</body>
</html>
I really read a lot of questions here on stackoverflow about similar errors but cant find a solution.
I think the problem is here.
<a href=" {{ course.get_absolute_url }} "> <!--- {% url 'courses:details' course.slug %}--->
^^^^^ ^^^^
In django template, comments does not work in this way. If you want to comment out something do it like this:
{% comment %}
{% url 'courses:details' course.slug %}
{% endcomment %}
Or
{# url 'courses:details' course.slug #}
Relevant documentation can be found here.

BOOTSTRAP Sign in template not working on FORM

My login page isn't looking like the way I want it to which is like this bootstrap signin page right here https://getbootstrap.com/docs/4.0/examples/sign-in/. This is what it looks like right now
If you can help me out with this, it would mean the world to me.
Also if you think it's because I didn't link to a CSS page here's what my base template looks like and my structure:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Accounts</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static 'accounts/signin.css' %}" />
</head>
<body>
<div class="jumbotron">
<div class="container">
{% block main_content %}
{% endblock %}
</div>
</div>
</body>
</html>
views.py
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .forms import UserLoginForm
# Create your views here.
def login_view(request):
title = "Login"
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# or any other success page
# return HttpResponse("Logged in")
return HttpResponseRedirect('accounts/home')
return render(request, "accounts/form.html", {"form":form, "title": title})
forms.py
from django import forms
from django.contrib.auth import (
authenticate,
get_user_model,
login,
logout,
)
User = get_user_model()
class UserLoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'email', 'password')
def clean(self,*args,**kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
user = authenticate(username=username,password=password)
if not user:
raise forms.ValidationError("This user does not exist")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("This user is no longer active.")
return super(UserLoginForm, self).clean(*args,**kwargs)
form.html (currently using this for login, open to use the same format for registration)
{% extends 'accounts/base.html' %}
{% block main_content %}
<div class="container">
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form }}
<input type='submit' class='btn btn-primary btn-block' value='{{ title }}' />
</form>
</div>
</div>
{% endblock %}
What My Framework Looks Like
Thanks a lot
#Lemayzeur this is what my site looks like now
And this is what I want it to look like
-it comes pretty close but unfortunately it's not the same. Nonetheless, I'll keep it and thank you.
Your CSS file works well because the button inherits the bootstrap design,
the problem is all the inputs that you have don't have the class form-control. So to add these classes, you can do it with the widget
class UserLoginForm(forms.Form):
username = forms.CharField(max_length=120,
widget=forms.TextInput(attrs={'class':'form-control',"placeholder":"Username"}))
password = forms.CharField(max_length=100,
widget=forms.PasswordInput(attrs={'class':'form-control',"placeholder":"Password"}))

Form input-box not displaying

I'm trying to display a simple form input-text box with Django. I'm am deploying on Amazon AWS. The site works fine on a different server (pythonanywhere) but there is a major problem on AWS. Specifically, the input box is not being displayed. I'm using templates as follows:
home.html
{% extends 'lists/base.html' %}
{% block header_text %}Start a new To-Do list {% endblock %}
{% block form_action %}{% url 'new_list' %}{% endblock %}
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X UA-Compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>To-Do lists</title>
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/base.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 jumbotron">
<div class="text-center">
<h1>{% block header_text %}{% endblock %}</h1>
<form method="POST" action="{% block form_action %}{% endblock %}">
{{ form.text }}
{% csrf_token %}
{% if form.errors %}
<div class = "form-group has-error">
<span class = "help-block">{{ form.text.errors }}</span>
</div>
{% endif %}
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3">
{% block table %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
models.py
from django.db import models
from django
.core.urlresolvers import reverse
class List(models.Model):
def get_absolute_url(self):
return reverse('view_list', args=[self.id])
# Create your models here.
class Item(models.Model):
text = models.TextField(default = '')
list = models.ForeignKey(List, default = None)
#list = models.ForeignKey(List , default=None)
forms.py
from django import forms
from lists.models import Item
EMPTY_ITEM_ERROR = "You can't have an empty list item"
class ItemForm(forms.models.ModelForm):
class Meta:
model = Item
fields = ('text',)
widgets ={
'text' : forms.fields.TextInput(attrs={
'placeholder': 'Enter a to-do item',
'class': 'form-control input-lg',
}),
}
error_messages = {
'text' : { 'required': EMPTY_ITEM_ERROR }
}
views.py
from django.shortcuts import redirect, render
from lists.models import Item, List
from django.core.exceptions import ValidationError
from lists.forms import ItemForm
from lists.models import Item, List
# Create your views here.
def home_page(request):
return render(request, 'lists/home.html', {'form': ItemForm()})
urls.py
from django.conf.urls import url
from lists import views
urlpatterns = [
url(r'^new$', views.new_list, name='new_list'),
url(r'^(\d+)/$', views.view_list, name='view_list'),
]
Currently the site displays the following:
However it should (and does on a different website) display this:
I've pushed/pulled the entire project to github and the code between each site is identical, yet I'm not seeing why the text input isn't displayed, unless the form needs to be initialized in Django somehow or a quirk to AWS?
When comparing the two sites, the one without the text-box does not generate the following:
<input class="form-control input-lg" id="id_text" name="text" placeholder="Enter a to-do item" type="text" />
Even though it should, per the base.html syntax.
Updated
The full views.py (per suggested comment) is:
from django.shortcuts import redirect, render
from lists.models import Item, List
from django.core.exceptions import ValidationError
from lists.forms import ItemForm
from lists.models import Item, List
# Create your views here.
def home_page(request):
return render(request, 'lists/home.html', {'form': ItemForm()})
def new_list(request):
form = ItemForm(data=request.POST)
if form.is_valid():
list_ = List.objects.create()
Item.objects.create(text=request.POST['text'], list=list_)
return redirect(list_)
else:
return render(request, 'lists/home.html', {"form": form})
def view_list(request, list_id):
list_ = List.objects.get(id=list_id)
form = ItemForm()
if request.method == 'POST':
form = ItemForm(data=request.POST)
if form.is_valid():
Item.objects.create(text=request.POST['text'], list=list_)
return redirect(list_)
return render(request, 'lists/list.html', {'list': list_, "form": form})
In my experience with Django, there are 2 things you often (always?) need to do to get static files to "refresh" after pushing them to a remote server:
Run ./manage.py collectstatic to make sure all your static files are in the right place.
While sshed into your server run the command sudo reboot now to restart your server (note that this will kick you out of your ssh session, and your server will be unreachable for a moment - usually just a few seconds in my case).
As for step 2 there might be a better way to do this, but in my experience, when I update static files the updated version is not served until I do this, and restarting nginx or the like is not sufficient for the changes to take effect. Note that this will mean that your site, if live, will not be reachable for a few seconds while the server is restarting (which is what makes me think there might be a better way to do it) but for me and my small user base this is not a big issue.
From reading some other posts about static files not updating, it seems like it could also be the case that your browser is caching the static files, and that restarting your browser/clearing the cache might do the trick as well, but I have not had a chance to try this yet.

Categories

Resources