I'm using Django to build a website. Modal bootstrap is what I'm utilizing. All works good for add, and delete data. However, In the Django form, I am unable to appear the data stored in the database for the update. Appreciate your help maybe I did something wrong with my code. I am not sure if my html or modal is correct. Thank you
-->> HTML <<--
<!-- Table Header -->
<thead>
<tr>
<th>User ID</th>
<th>Username</th>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Role</th>
<th>Created Date</th>
<th>Modified Date</th>
<th>Status</th>
<th>Settings</th>
</tr>
</thead>
<!-- Table Body -->
<tbody>
{% for members in member %}
<tr>
<td>{{members.id}}</td>
<td>{{members.username}}</td>
<td>{{members.first_name}}</td>
<td>{{members.middle_name}}</td>
<td>{{members.last_name}}</td>
<td>{% if members.role %}{{members.get_role}}{% endif %}</td>
<td>{{members.created_date}}</td>
<td>{{members.modified_date}}</td>
<td>
{% if members.status == 1 %}
<button type="button"
class="btn btn-success rounded-pill">{{members.get_status}}</button>
{% elif members.status == 2 %}
<button type="button"
class="btn btn-danger rounded-pill">{{members.get_status}}</button>
{% elif members.status == 3 %}
<button type="button"
class="btn btn-secondary rounded-pill">{{members.get_status}}</button>
{% endif %}
</td>
<td>
<a href="#" data-toggle="modal" data-target="#viewUserModal{{ members.id }}"><i class='bx bxs-folder-open'
data-toggle="tooltip" title="View"></i></a>
<a href="#" data-toggle="modal" data-target="#editUserModal{{ members.id }}"><i class='bx bxs-edit'
data-toggle="tooltip" title="Edit"></i></a>
<a href="#" data-toggle="modal" data-target="#deleteModal{{ members.id }}"><i class='bx bx-trash'
data-toggle="tooltip" title="Delete" ></i></a>
</td>
</tr>
{% include 'includes/modals.html' %}
{% endfor %}
</tbody>
<!-- End of Table Body -->
</table>
</div>
-->> Edit Modal <<--
<div class="modal fade" id="editUserModal{{ members.id }}" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit User Account</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
<div class="modal-body">
<form action="" method="POST">
{% csrf_token %}
<div class="form-group ">
<label>First Name</label>
{{form.first_name}}
</div>
<div class="form-group">
<label>Middle Name</label>
{{form.middle_name}}
</div>
<div class="form-group">
<label>Last Name</label>
{{form.last_name}}
</div>
<div class="form-group">
<label>Email</label>
{{form.email}}
</div>
<div class="form-group">
<label>Mobile Number</label>
{{form.mobile_number}}
</div>
<div class="form-group">
<label>Username</label>
{{form.username}}
</div>
<div class="form-group">
<label>Role</label>
<select class="form-control" id="inputGroupSelect01" name="role" value="{% if members.role %}{{members.get_role}}{% endif %}" required>
<option>Select Role</option>
<option value="2" {% if members.role == 1 %}{{members.get_role}} selected {% endif %} >Member</option>
<option value="2" {% if members.role == 2 %}{{members.get_role}} selected {% endif %} >Admin</option>
<option value="3" {% if members.role == 3 %}{{members.get_role}} selected {% endif %}>Super Admin</option>
</select>
</div>
<div class="form-group">
<label>Status</label>
<select class="form-control" id="inputGroupSelect01" name="role" value="{% if members.status %}{{members.get_status}}{% endif %}" required>
<option>Select Status</option>
<option value="1" {% if members.status == 1 %}{{members.get_status}} selected {% endif %} >Active</option>
<option value="2" {% if members.status == 2 %}{{members.get_status}} selected {% endif %}>Deactive</option>
</select>
</div>
<hr>
<input type="button" class="btn btn-secondary" data-dismiss="modal" value="Cancel">
<input type="submit" class="btn btn-primary" href="{% url 'edit_user' members.id %}" value="Save">
</form>
</div>
</div>
</div>
</div>
-->> urls.py <<--
urlpatterns = [
path('userAccounts/edit_user/<user_id>', views.edit_user, name='edit_user'),
]
-->> forms.py <<--
class UserFormAdmin(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'middle_name', 'last_name', 'username', 'email', 'mobile_number', 'password']
labels = {
'first_name': '',
'middle_name': '',
'last_name': '',
'mobile_number': '',
'email': '',
'username': '',
'password': '',
'confirm_password': '',
}
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Jones', 'class': 'form-control', }))
middle_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'A', 'class': 'form-control', }))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Smith', 'class': 'form-control',}))
mobile_number = forms.CharField(max_length=15, validators=[RegexValidator(
'^\+[0-9]{1,3}\.?\s?\d{8,13}', message="Phone number must not consist of space and requires country code. eg : +639171234567")],widget=forms.TextInput(attrs={'placeholder': '09123456789', 'class': 'form-control',}),
error_messages={'unique': ("Mobile Number already exists.")})
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'jonesmith#gmail.com', 'class': 'form-control',}),
error_messages={'unique': ("Email already exists.")},)
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Jones_Smith31', 'class': 'form-control',}),
error_messages={'unique': ("Username already exists.")},)
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '********', 'class': 'form-control',}))
#password = forms.CharField(validators=[MinLengthValidator(8),RegexValidator('^(?=.*[A-Z])(?=.*[!##$&*])(?=.*[0-9])(?=.*[a-z])$', message="Password should be a combination of Alphabets and Numbers")], widget=forms.PasswordInput(attrs={'placeholder': '********', 'style': 'width: 460px; '}))
confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '********', 'class': 'form-control', }))
-->> views.py <<--
def sa_userAccount_admin(request):
member = User.objects.filter(role = 2)
form = UserFormAdmin(request.POST)
context = {
'form': form,
'member': member,
}
print(context)
return render(request, 'pages/sa_userAccount.html', context)
def edit_user(request, user_id):
member = User.objects.get(pk=user_id)
form = UserFormAdmin(request.POST or None, instance=member)
if form.is_valid():
form.save()
return redirect('sa_userAccount')
return render(request, 'pages/sa_userAccount.html',
{'members': member,
'form':form})
You can do this using the following steps:
get user input to update an object in HTML Modal
send data using the POST method with object pk
fetch object using received pk
update object in views using setattr(object,field name,value) from POST data
call object.save() method
These steps will update your objects in the database using the partial update technique.
Related
I am using Form Wizard in Django. My form is okay the problem is adding multiple person details in the form. There is a button on the HTML to add person. If it is click there is a drop down. For now the code works for adding one person only. Is there a way that you can repeat the step in FormWizard if the user wants to add many people? Do I need to save it in session? Thank you
HTML
{% extends "incident_report_home.html" %}
{% block form_if %}{% block form_else %}
{% csrf_token %}
<fieldset>
{% comment %} <legend>Title</legend> {% endcomment %}
<div>
{% comment %} <label>{{ form.field.label }}:<p class="note">{{ form.field.help_text }}</p></label>
<hr> {% endcomment %}
<button class="btn btn-primary" type="button" data-toggle="collapse"
data-target="#collapsePeople" aria-expanded="false"
aria-controls="collapsePeople">
<i class='bx bx-plus'></i> Add Person
</button>
<div class="collapse pt-4" id="collapsePeople">
<form>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputFirstName">First Name</label>
{{form.incident_first_name}}
</div>
<div class="form-group col-md-4">
<label for="inputMiddleName">Middle Name</label>
{{form.incident_middle_name}}
</div>
<div class="form-group col-md-4">
<label for="inputLastName">Last Name</label>
{{form.incident_last_name}}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputAge">Age</label>
{{form.incident_age}}
</div>
<div class="form-group col-md-4">
<label for="inputGender">Gender</label>
{{form.incident_gender}}
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
{{form.incident_address}}
</div>
<!-- ================================= -->
<hr>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputInvolvement">Involvement</label>
{{form.incident_involvement}}
</div>
<div class="form-group col-md-4">
<label for="inputID">ID Presented</label>
{{form.incident_id_presented}}
</div>
<div class="form-group col-md-4">
<label for="inputIDNumber">ID Number</label>
{{form.incident_id_number}}
</div>
</div>
<div class="form-group">
<label for="inputInjury">Injury</label>
{{form.incident_injury}}
</div>
<div class="form-group">
<label for="inputInjury">Driver Error</label>
{{form.incident_driver_error}}
</div>
<div class="form-group">
<label for="inputInjury">Alcohol / Drugs</label>
{{form.incident_alcohol_drugs}}
</div>
<div class="form-group">
<label for="inputInjury">Seat belt / Helmet </label>
{{form.incident_seatbelt_helmet}}
</div>
<br>
<div class="modal-footer mb-3">
<input type="button" class="btn btn-secondary" data-dismiss="modal"
value="Clear">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
<p class="error">
{% if form.field.errors %}
{% for error in form.field.errors %}
{{ error }}
{% endfor %}
{% endif %}
</p>
</div>
</fieldset>
{% endblock %}{% endblock %}
Views
FORMS = [("information", UserReportForm),
("general", IncidentGeneralForm),
("people", IncidentPersonForm),
("vehicle",IncidentVehicleForm),
("media", IncidentMediaForm),
("remarks", IncidentRemarksForm)]
TEMPLATES = {"information": "pages/super/incident_report_user.html",
"general": "pages/super/incident_report_general.html",
"people": "pages/super/incident_report_people.html",
"vehicle": "pages/super/incident_report_vehicle.html",
"media": "pages/super/incident_report_media.html",
"remarks": "pages/super/incident_report_remarks.html"}
TEMPLATES1 = {"information": "pages/admin/incident_report_user.html",
"general": "pages/admin/incident_report_general.html",
"people": "pages/admin/incident_report_people.html",
"vehicle": "pages/admin/incident_report_vehicle.html",
"media": "pages/admin/incident_report_media.html",
"remarks": "pages/admin/incident_report_remarks.html"}
class multistepformsubmission(SessionWizardView):
# template_name = 'pages/incident_report.html'
# form_list = [UserReportForm, IncidentGeneralForm, IncidentPersonForm, IncidentVehicleForm, IncidentMediaForm, IncidentRemarksForm]
file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'media'))
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
# UserReport, IncidentGeneral, IncidentRemark, AccidentCausationSub, CollisionTypeSub, IncidentMedia, IncidentPerson, IncidentVehicle
profile = get_object_or_404(UserProfile, user=self.request.user)
user_instance = UserReport()
general_instance = IncidentGeneral()
person_instance = IncidentPerson()
vehicle_instance = IncidentVehicle()
media_instance = IncidentMedia()
remarks_instance = IncidentRemark()
#listing_instance.created_by = self.request.user
#listing_instance.listing_owner = self.request.user
#listing_instance.listing_type = 'P'
for form in form_list:
user_instance = construct_instance(form, user_instance, form._meta.fields, form._meta.exclude)
general_instance = construct_instance(form, general_instance, form._meta.fields, form._meta.exclude)
person_instance = construct_instance(form, person_instance, form._meta.fields, form._meta.exclude)
vehicle_instance = construct_instance(form, vehicle_instance, form._meta.fields, form._meta.exclude)
media_instance = construct_instance(form, media_instance, form._meta.fields, form._meta.exclude)
remarks_instance = construct_instance(form, remarks_instance, form._meta.fields, form._meta.exclude)
user_instance.user = self.request.user
user_instance.status = 2
user_instance.save()
general_instance.user_report = user_instance
general_instance.save()
person_instance.incident_general = general_instance
person_instance.save()
vehicle_instance.incident_general = general_instance
vehicle_instance.save()
media_instance.incident_general = general_instance
media_instance.save()
remarks_instance.incident_general = general_instance
remarks_instance.save()
context = {
'profile': profile
}
return redirect('/userReports', context)
def incident_form_super(request):
attWizardView = multistepformsubmission.as_view(FORMS)
return attWizardView(request)
URL
path('incidentReport/formsubmissions', views.incident_form_super, name='incident_form_super'),
Trying to edit a profile using a form I have that should allow a user to edit her first name, last name and email. Problem is when I try editing the form nothing happens. Still trying to learn Django so could be something I am missing/not getting right.
Here is my form;
<form id="edit-mentor-profile" class="form-horizontal" method="post" >
{% csrf_token %}
<div class="form-group">
<label for="photo" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
<input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}>
<label for="edit-mentor-profile-first_name"></label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
<input type="text" class="form-control" id="edit-mentor-profile-last_name" placeholder={{ user.last_name }}>
<label for="edit-mentor-profile-last_name"></label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="email" class="form-control" id="edit-mentor-profile-email" placeholder={{ user.email }}>
<label for="edit-mentor-profile-email"></label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox" checked="">
<label for="checkbox3">Subscribe to our Newsletter</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</form>
this is what I have on forms.py
class TeacherSignUpForm(UserCreationForm):
email = forms.EmailField(max_length=100)
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
linkedin = forms.URLField(max_length=200)
class Meta(UserCreationForm.Meta):
model = User
fields = ('email', 'username', 'first_name', 'last_name')
def save(self, commit=True):
self.instance.is_teacher = True
user = super(UserCreationForm, 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']
user.save()
mentor = Mentor.objects.create(
user=user,
linkedin=self.cleaned_data['linkedin']
)
return user
forms.py
# edit mentor profile
class MentorProfileForm(forms.Form):
first_name = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id': 'edit-mentor-profile-first_name',
'class': 'form-control'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'type': 'text', 'id': 'edit-mentor-profile-last_name',
'class': 'form-control'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={'type': 'email', 'id': 'edit-mentor-profile-email',
'class': 'form-control'}))
and teachers.py(views.py)
class TeacherSignUpView(CreateView):
model = User
form_class = TeacherSignUpForm
template_name = 'registration/signup_form.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'teacher'
return super().get_context_data(**kwargs)
def form_valid(self, form):
user = form.save()
# user.set_password(form.cl)
login(self.request, user)
return redirect('teachers:app-instructor-dashboard')
#edit mentor profile
def edit_user(request):
user = request.user
form = MentorProfileForm(initial={'first_name':user.first_name,'last_name':user.last_name,'email':user.email})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.email = request.POST['email']
# user.password = request.POST['password']
user.save()
return HttpResponseRedirect('%s'%(reverse('profile')))
context = {
"form":form
}
return render(request, 'classroom/teachers/app-instructor-profile.html', context)
UPDATE
Based on the answer provided I made the following changes
html form:
<form id="edit-mentor-profile" class="form-horizontal" method="post" >
{% csrf_token %}
<div class="form-group">
<label for="photo" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
{{ form.first_name }}
<label for="edit-mentor-profile-first_name"></label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
{{ form.last_name }}
<label for="edit-mentor-profile-last_name"></label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
{{ form.email }}
<label for="edit-mentor-profile-email"></label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<div class="checkbox checkbox-success">
<input id="checkbox3" type="checkbox" checked="">
<label for="checkbox3">Subscribe to our Newsletter</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</form>
and forms.py
class MentorProfileForm(forms.Form):
class Meta:
widgets = {
'first_name': forms.TextInput(attrs={'class':'form-control'}),
'last_name': forms.TextInput(attrs={'class':'form-control'}),
'email': forms.EmailInput(attrs={'class':'form-control'})
}
With these changes I cannot interact with the form. I cannot click the textboxes available.
Here is a sample of what i am seeing
You should render the inputs using the form field elements themselves
Instead of this
<input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}>
Use this
{{ form.first_name }}
If you need to add the class to the input then in your model form add the class attribute to the field's widget
class Meta:
widgets = {
'first_name': forms.TextInput(attrs={'class': 'form-control'})
}
I am trying to edit multiple rows of data in a model via formsets. In my rendered form, I use javascript to delete (hide and assign DELETE) rows, and then save changes with post.
My view:
def procedure_template_modification_alt(request, cliniclabel, template_id):
msg = ''
clinicobj = Clinic.objects.get(label=cliniclabel)
template_id = int(template_id)
template= ProcedureTemplate.objects.get(templid = template_id)
formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template = template))
if request.method == 'POST':
print(request.POST.get)
# Create a formset instance with POST data.
formset = ProcedureModificationFormset(request.POST)
if formset.is_valid():
print("Form is valid")
instances = formset.save(commit=False)
print(f'instances:{instances}')
for instance in instances:
print(f'Instance: {instance}')
instance.template = template
instance.save()
msg = "Changes saved successfully."
print("Deleted forms:")
for form in formset.deleted_forms:
print(form.cleaned_data)
else:
print("Form is invalid")
print(formset.errors)
msg = "Your changes could not be saved as the data you entered is invalid!"
template= ProcedureTemplate.objects.get(templid = template_id)
headings = SectionHeading.objects.filter(template = template)
return render(request, 'procedures/create_procedure_formset_alt.html',
{
'template': template,
'formset': formset,
'headings': headings,
'msg': msg,
'rnd_num': randomnumber(),
})
My models:
class ProcedureTemplate(models.Model):
templid = models.AutoField(primary_key=True, unique=True)
title = models.CharField(max_length=200)
description = models.CharField(max_length=5000, default='', blank=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
def __str__(self):
return f'{self.description}'
class SectionHeading(models.Model):
procid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200)
default = models.CharField(max_length=1000)
sortorder = models.IntegerField(default=1000)
fieldtype_choice = (
('heading1', 'Heading1'),
('heading2', 'Heading2'),
)
fieldtype = models.CharField(
choices=fieldtype_choice, max_length=100, default='heading1')
template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)
def __str__(self):
return f'{self.name} [{self.procid}]'
My forms:
class ProcedureCrMetaForm(ModelForm):
class Meta:
model = SectionHeading
fields = [
'name',
'default',
'sortorder',
'fieldtype',
'procid'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control'})
self.fields['default'].widget.attrs.update({'class': 'form-control'})
self.fields['sortorder'].widget.attrs.update({'class': 'form-control'})
self.fields['fieldtype'].widget.attrs.update({'class': 'form-control'})
ProcedureCreationFormset = formset_factory(ProcedureCrMetaForm, extra=3)
ProcedureModificationFormset = modelformset_factory(SectionHeading, ProcedureCrMetaForm,
fields=('name', 'default', 'sortorder','fieldtype', 'procid'),
can_delete=True,
extra=0
# widgets={"name": Textarea()}
)
The template:
{% block content %} {% load widget_tweaks %}
<div class="container">
{% if user.is_authenticated %}
<div class="row my-1">
<div class="col-sm-2">Name</div>
<div class="col-sm-22">
<input type="text" name="procedurename" class="form-control" placeholder="Enter name of procedure (E.g. DNE)"
value="{{ template.title }}" />
</div>
</div>
<div class="row my-1">
<div class="col-sm-2">Description</div>
<div class="col-sm-22">
<input type="text" name="proceduredesc" class="form-control" placeholder="Enter description of procedure (E.g. Diagnostic Nasal Endoscopy)"
value="{{ template.description }}" />
</div>
</div>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %} {{ formset.management_form }}
<div class="row mt-3">
<div class="col-sm-1">Select</div>
<div class="col-sm-6">Heading</div>
<div class="col-sm-8">Default (Normal description)</div>
<div class="col-sm-2">Sort Order</div>
<div class="col-sm-4">Type</div>
<div class="col-sm-2">Action</div>
</div>
{% for form in formset %}
<div class="row procrow" id="row{{ forloop.counter0 }}">
<div class="" style="display: none;">{{ form.procid }}</div>
<div class="col-sm-6">
{{ form.name }}
</div>
<div class="col-sm-8">
<div class="input-group">
{{ form.default }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
{{ form.sortorder }}
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
{{ form.fieldtype }}
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add{{ forloop.counter0 }}" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del{{ forloop.counter0 }}" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
</div>
{% endfor %} {% endif %}
<div class="row my-3">
<div class="col-sm-8"></div>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-append mx-1">
<button id="save_report" type="submit" class="btn btn-success"><i class="fal fa-shield-check"></i>
Save Report Format</button>
</div>
<div class="input-group-append mx-1">
<button id="save_report" type="button" class="btn btn-danger"><i class="fal fa-times-hexagon"></i>
Cancel</button>
</div>
</div>
</div>
<div class="col-sm-8"></div>
</div>
<div>
{% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %}
</div>
</form>
</div>
{% endblock %}
My data is displayed as below (Screenshot). I make changes with javascript when the delete button is pressed, so that the html becomes like this:
<div class="row procrow" id="row2" style="display: none;">
<div class="" style="display: none;"><input type="hidden" name="form-2-procid" value="25" id="id_form-2-procid"></div>
<div class="col-sm-6">
<input type="text" name="form-2-name" value="a" maxlength="200" class="form-control" id="id_form-2-name">
</div>
<div class="col-sm-8">
<div class="input-group">
<input type="text" name="form-2-default" value="v" maxlength="1000" class="form-control" id="id_form-2-default">
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<input type="number" name="form-2-sortorder" value="1000" class="form-control" id="id_form-2-sortorder">
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<select name="form-2-fieldtype" class="form-control" id="id_form-2-fieldtype">
<option value="heading1" selected="">Heading1</option>
<option value="heading2">Heading2</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="input-group">
<div class="input-group-append">
<button id="add2" class="btn btn-success add-row">+</button>
</div>
<div class="input-group-append">
<button id="del2" class="btn btn-danger del-row">-</button>
</div>
</div>
</div>
<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" checked=""></div>
On submitting the data, I get the following output, and data does not reflect the deletion I did. It displays the same thing again. There are no errors. But my edited data is not being saved.
Output:
<bound method MultiValueDict.get of <QueryDict: {'csrfmiddlewaretoken': ['ka3avICLigV6TaMBK5a8zeVJlizhtsKW5OTDBLlYorKd7Iji9zRxCX2vvjBv6xKu'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-procid': ['23'], 'form-0-name': ['External ear canal'], 'form-0-default': ['Bilateral external ear canals appear normal. No discharge.'], 'form-0-sortorder': ['100'], 'form-0-fieldtype': ['heading1'], 'form-1-procid': ['24'], 'form-1-name': ['Tympanic membrane'], 'form-1-default': ['Tympanic membrane appears normal. Mobility not assessed.'], 'form-1-sortorder': ['500'], 'form-1-fieldtype': ['heading1'], 'form-2-procid': ['25'], 'form-2-name': ['a'], 'form-2-default': ['v'], 'form-2-sortorder': ['1000'], 'form-2-fieldtype': ['heading1'], 'form-2-DELETE': ['on']}>>
Form is valid
instances:[]
Deleted forms:
{'name': 'a', 'default': 'v', 'sortorder': 1000, 'fieldtype': 'heading1', 'procid': <SectionHeading: a [25]>, 'DELETE': True}
You actually need to delete the instances: Loop through the formsets' deleted_objects property after you called saved(commit=False) and delete them.
I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database.
I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated.
jQuery code
var modalDiv = $("#modal-div");
$(".open-modal").on("click", function() {
console.log("button clicked");
var url = $(this).attr('data-url').replace('/', '');
console.log("url:",url); // this returns my customer number but is not used in the code below
$.ajax({
url: $(this).attr("data-url"),
type: 'get',
success: function(data) {
console.log("success");
modalDiv.html(data);
$("#myEdit").modal(); //#myEdit is the ID of the modal
},
error : function() {
console.log("Error: this did not work"); // provide a bit more info about the error to the console
}
});
});
a tag in form
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
Needless to say, I keep receiving the error console.log message.
Below is the complete codebase.
Model:
class Kunde(models.Model):
avd = [('610','610'), ('615', '615'), ('620', '620'), ('625', '625'), '630', '630'), ('635', '635'),('640', '640'),('645', '645'), ('650', '650'), ('655', '655')]
avdeling = models.CharField(max_length=3, choices=avd)
selskap = models.CharField(max_length=50, unique=True)
kundenr = models.CharField('Kundenummer', max_length=15, unique=True, primary_key=True)
gatenavn = models.CharField(max_length=50,)
postnr = models.CharField('Postnummer', max_length=4)
poststed = models.CharField(max_length=30)
kommune = models.CharField(max_length=30)
timestamp = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
def get_absolute_url(self):
return reverse("dashboard:index")
def __str__(self):
return self.selskap
class Meta:
ordering = ['selskap']
Urls
app_name = "dashboard"
urlpatterns = [
path('', views.dashboard, name='index'),
path('', views.customer_list, name='customer_list'),
url(r'^(?P<kundenummer>[0-9]+)$', views.customer_update, name='customer_update'),
]
Views:
main view to display the table
def dashboard(request):
template = 'dashboard/index.html'
if request.user.groups.filter(name__in=['Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='630') | Q(avdeling='635')).all()
elif request.user.groups.filter(name__in=['Nord']).exists():
queryset = Kunde.objects.filter(Q(avdeling='610') | Q(avdeling='615') | Q(avdeling='620')).all()
elif request.user.groups.filter(name__in=['Øst']).exists():
queryset = Kunde.objects.filter(Q(avdeling='660') | Q(avdeling='655') | Q(avdeling='650')).all()
elif request.user.groups.filter(name__in=['Sør']).exists():
queryset = Kunde.objects.filter(Q(avdeling='640') | Q(avdeling='645')).all()
elif request.user.groups.filter(name__in=['Nord-Vest']).exists():
queryset = Kunde.objects.filter(Q(avdeling='625')).all()
else:
queryset = Kunde.objects.all()
context = {
"object_list": queryset,
}
return render(request, template, context)
view to display the modal with
def customer_update(request, kundenr=None):
template = 'dashboard/index.html'
instance = get_object_or_404(Kunde, kundenr=kundenr)
context={
'selskap': instance.selskap,
'instance': instance,
}
return render(request, template, context)
HTML table
<div class"container-table" style="overflow-x:auto;">
<table class="display table table-bordered table-condensed" id="table_kundeliste">
<thead class="thead-inverse">
<tr>
<th>Avdeling</th>
<th>Selskap</th>
<th>Kundenr.</th>
<th>Poststed</th>
<th>Kommune</th>
<th>Rediger</th>
</tr>
</thead>
<tbody>
{% for kunde in object_list %}
<tr>
<td> {{ kunde.avdeling }} </td>
<td> {{ kunde.selskap }} </td>
<td> {{ kunde.kundenr }} </td>
<td> {{ kunde.poststed }} </td>
<td> {{ kunde.kommune }} </td>
<td>
<a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
this part include modal in html
<div id="modal-div" class="modal-div">
{% include 'dashboard/customer-modal.html' %}
</div>
this is the modal template itself
<div class="modal fade" id="myEdit" role="dialog">
<div class="modal-dialog">
<form class="well contact-form" method="post" action="{% url dashboard:'customer_update'}">
{% csrf_token %}
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label for="avdeling">Avdeling:</label>
<input type="text" class="form-control" required="" name="avdeling" value="{{ instance.avdeling }}" id="avdeling">
<label for="selskap">Selskap:</label>
<input type="text" class="form-control" required="" name="selskap" value="{{ instance.selskap }}" id="selskap">
<label for="kundenummer">Kundenummer:</label>
<input type="text" class="form-control" required="" name="kundenummer" value="{{ instance.kundenr }}" id="kundenummer">
<label for="gatenavn">Gatenavn:</label>
<input type="text" class="form-control" required="" name="gatenavn" value="{{ instance.gatenavn }}" id="gatenavn">
<label for="postnummer">Postnummer:</label>
<input type="text" class="form-control" required="" value="{{ instance.postnr }}" name="postnummer" id="postnummer" >
<label for="poststed">Poststed:</label>
<input type="text" class="form-control" required="" value="{{ instance.poststed }}" name="poststed" id="poststed" >
<label for="kommune">Kommune:</label>
<input type="text" class="form-control" required="" value="{{ instance.kommune }}" name="kommune" id="kommune" >
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Valider</button>
<button value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
I wrote in index.html
<div class="heading col-lg-6 col-md-12">
<h2>New account registration</h2>
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>
{{ regist_form.username }}
</div>
<div class="form-group-lg">
<label for="id_email">email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
{{ regist_form.password1 }}
</div>
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
{{ regist_form.password2 }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
</div>
I wanna set minlength&maxlength in template of username&password input tag.If i wrote in html stye,it is
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>
<input id="id_username" name="username" type="text" value="" minlength="5" maxlength="12" placeholder="username" class="form-control">
</div>
<div class="form-group-lg">
<label for="id_email">email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
<input id="id_password1" name="password1" type="password1" value="" minlength="8" maxlength="12" placeholder="password1" class="form-control">
</div>
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
<input id="id_password2" name="password2" type="password2" value="" minlength="8" maxlength="12" placeholder="password2" class="form-control">
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
in forms.py
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password1','password1',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
in views.py
#require_POST
def regist_save(request):
regist_form = RegisterForm(request.POST)
if regist_form.is_valid():
user = regist_form.save(commit=False)
password = regist_form.cleaned_data.get('password')
user.set_password(password)
user.save()
login(request, user)
context = {
'user': request.user,
}
return redirect('detail')
context = {
'regist_form': regist_form,
}
return render(request, 'registration/regist.html', context)
I wanna set username minlength="5" &maxlength="12" and password minlength="8" & maxlength="12".I wanna write it in template,although I searched the way in Google but i cannot find it.I think i can do it by template but do i misunderstand it?Can't i do it in template?
you can set maxlength and minlength by using these attributes with your desired limit and validation will work accordingly
Working example on W3schools