'I've a problem with django update in crud?
I have a problem where, in the update part when the form is displayed, in whichever fields there is more than one word (like name, address) the first one is only displayed in the form to be edited, the rest is gone. I went through the whole project multiple times but I can't find the solution. Please help me. Thanks in Advance!!!
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.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
</head>
<body>
<div class="container" align="center">
{% block body %}
{% endblock %}
</div>
</body>
</html>
create.html
<!DOCTYPE html>
{% extends "testAppTem/base.html" %}
{% block body %}
<div class="jumbotron">
<h1>Employee insertion form</h1><hr>
<form method='post'>
<table border=3>
{{form}}
</table>
{%csrf_token%}<br><br>
<input type="submit" value="Insert" class="btn btn-lg btn-danger">
</form>
</div>
{% endblock %}
index.html
<!DOCTYPE html>
{% extends "testAppTem/base.html" %}
{% block body %}
<div class="jumbotron">
<h1><u>Employee Information Dashboard</u></h1><br><br>
<table border=4>
<thead>
<th>Employee Name</th>
<th>Employee Number</th>
<th>Employee Salary</th>
<th>Employee Address</th>
<th>Actions</th>
</thead>
{% if employees %}
{% for e in employees %}
<tr align=center>
<td>{{e.enum}}</td>
<td>{{e.ename}}</td>
<td>{{e.esal}}</td>
<td>{{e.eaddr}}</td>
<td><a href="/update/{{e.id}}" class="btn btn-sm btn-dark">Update</a> <a href="/delete/{{e.id}}" class="btn btn-sm btn-info">Delete</a></td>
</tr>
{% endfor %}
{% else %}
<p>There is no data...</p>
{% endif %}
</table><br><br>
<a href="/insertEmployee" class="btn btn-lg btn-success">Insert New Employee</a>
</div>
{% endblock %}
update.html
<!DOCTYPE html>
{% extends "testAppTem/base.html" %}
{% block body %}
<div class="jumbotron">
<h1>Employee information update form</h1><hr>
<form method='post'>
{%csrf_token%}
Employee Number: <input type="number" name="enum" value={{employee.enum}}><br><br>
Employee Name: <input type="text" name="ename" value={{employee.ename}}><br><br>
Employee Salary: <input type="number" name="esal" value={{employee.esal}}><br><br>
Employee Address: <input type="text" name="eaddr" value={{employee.eaddr}}><br><br><br>
<input type="submit" value="Update Record" class="btn btn-lg btn-warning">
</form>
</div>
{% endblock %}
populate.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crudFunctionBasedViewsProject.settings')
import django
django.setup()
from testApp.models import *
from faker import Faker
from random import *
fake = Faker()
def populate(n):
for i in range(n):
fnum= randint(1,1000)
fename = fake.name()
fesal = randint(10000,500000)
feaddr = fake.city()
emp_record = Employee.objects.get_or_create(enum=fnum, ename=fename, esal=fesal, eaddr=feaddr)
populate(20)
Views.py
from django.shortcuts import render, redirect
from testApp.models import Employee
from testApp.forms import EmployeeForm
# Create your views here.
def retrieve_view(request):
employees = Employee.objects.all()
return render(request, 'testAppTem/index.html', {'employees': employees})
def create_view(request):
form = EmployeeForm()
if request.method == 'POST':
form = EmployeeForm(request.POST)
if form.is_valid():
form.save()
return redirect("/")
return render(request, 'testAppTem/create.html', {'form': form})
def delete_view(request,id):
employee = Employee.objects.get(id=id)
employee.delete()
return redirect("/")
def update_view(request,id):
employee = Employee.objects.get(id=id)
# test = Employee.objects.get(id=15)
# print(test.eaddr)
if request.method == 'POST':
form = EmployeeForm(request.POST, instance=employee)
if form.is_valid():
form.save(commit=True)
return redirect('/')
return render(request, 'testAppTem/update.html', {'employee': employee})
models.py
from django.db import models
# Create your models here.
class Employee(models.Model):
enum = models.IntegerField()
ename = models.CharField(max_length=64)
esal = models.FloatField()
eaddr = models.CharField(max_length=256)
forms.py
from django import forms
from testApp.models import Employee
class EmployeeForm(forms.ModelForm):
class Meta:
model=Employee
fields='__all__'
settings.py
"""
Django settings for crudFunctionBasedViewsProject project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-gj7)^1kee34v3(jf_1w!o4x_hxm&q(29kcvf9!pwov9bn5b$u='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testApp',
]
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 = 'crudFunctionBasedViewsProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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',
],
},
},
]
WSGI_APPLICATION = 'crudFunctionBasedViewsProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
urls.py
"""crudFunctionBasedViewsProject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from testApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.retrieve_view),
path('insertEmployee/', views.create_view),
path('delete/<int:id>/', views.delete_view),
re_path('update/(?P<id>\d+)/$', views.update_view),
]
admin.py
from django.contrib import admin
from testApp.models import Employee
class EmployeeAdmin(admin.ModelAdmin):
list_display = ["ename", "enum"]
# Register your models here.
admin.site.register(Employee, EmployeeAdmin)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
