Using one modal for multiple forms in django? - html

I can't figure out how to use one modal for multiple forms.
Now, I can not find a way to have only one modal for severals form that I want to create. I don't really want to have 30 modals in the html for the 30 forms that I am going to submit.
Is there another way to fill it automatically?
My model is
class Project(models.Model):
project_name = models.CharField(max_length=30)
project_status = models.IntegerField(choices=PROJECT_STATUS,default=1)
project_sponsor = models.CharField('Project Sponsor',
max_length=255,default=1)
scope = models.TextField(max_length=10240, blank=True)
description = models.TextField(max_length=10240, blank=True)
Then, I wanted to have one form for each model attribute. For example, I would like to have a form for description, then another one for scope...
class ScopeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ScopeForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = False
class Meta:
model = Project
fields = ['project_scope',]
class DescriptionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DescriptionForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = False
class Meta:
model = Project
fields = ['description',]
In my html file, I am using a modal to submit the form
Purpose</br>
<div class="modal fade" id="purpose" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Purpose</h3>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label>
The Purpose will provide a brief overview of the purpose of the project and provide enough of a description to complete
the following sections. If information to complete the following sections is not available, state that it is unavailable and
state the person accountable and schedule for completion. </label>
</div>
<div class="form-group" "width: 300px" "height: 100px" "border: 1px solid blue">
<label for="purpose">Purpose</label>
<textarea id="txtCommentHere" class="form-control" rows="3" id="purpose" placeholder="Purpose">
</textarea>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Draft
</label></br>
<label>
<input type="checkbox"> In Progress
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>

You could check out this in bootstrap documentation
Bootstrap (Many to 1) Modal
Basically you need to pass the data via js/jquery to modal.

Related

Displaying Textbox Information and updating in Angular and TS

Fairly new to stack overflow but I needed assistance.
I did a backend and the API is working fine after tests from postman.
I can add employee and I can retrieve employee. However, what I am trying to do is, when I click on the card, I want the card I clicked on to display information about the employee in the textboxes and allow me to change and update. I am failing to retrieve and update my HTML. Please help.
In MY TS, I have this:
updateEmployee(employee: Employee){this.load = true;this.users.updateEmployee(employee).subscribe(res => {this.load = false;this.onPrimaryOutline("Employee has been updated");this.getEmployee();},err=>{console.log(err);this.load = false;this.onErrorOutline("Failed to update Employee, please try again");});}
onOpenModal(employee: Employee, mode: string): void {const containerUpdate = document.getElementById('update-container');const button = document.createElement('button');button.type = 'button';button.style.display = 'none';button.setAttribute('data-toggle', 'modal');if (mode === 'save'){this.updateEmployee = employee;button.setAttribute('data-target', '#update-container');}if (mode === 'delete'){button.setAttribute('data-target', '#deleteEmployeeMasterModal');} containerUpdate.appendChild(button);
button.click()}
service:
public updateEmployee(employee: Employee): Observable<Employee>{ return this.http.put<Employee>(${this.updateEmployee_url}/employee/update, employee) }
HTML:
<div class="card" id="update-container" [hidden]="!showForm" data-toggle="modal" data-target="#updateEmployeeModal"><span aria-hidden="true">×</span><ng-template #template><ngx-loading-x [show]="load"></ngx-loading-x><div NgxLoadingXBlur [show]="load"><div class="modal-header">
<div>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span> </button>
</div>
<div class="modal-body">
<div class="card mb-4">
<div class="card-body">
<h6 class="mb-4">{{ 'forms.external-components' | translate }}
</h6>
<form [formGroup]="commonForm" #editForm="ngForm" (ngSubmit)="updateEmployee()" novalidate class="tooltip-label-right">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel="{{editEmployee?.name}}" formControlName="name">
<small>Only letters and at least 2 characters</small>
<div *ngIf="commonForm.get('name')?.errors?.required && !form.submitted" class="invalid-tooltip">Name is required!</div>
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" class="form-control" name="airlineCode" ngModel="{{editEmployee?.surname}}" formControlName="surname">
<small>Only letters and at least 2 characters</small>
<div *ngIf="commonForm.get('surname')?.errors?.required && !form.submitted" class="invalid-tooltip">Code is required!</div>
</div>
<div class="form-group">
<label>Number</label>
<input type="text" class="form-control" name="phonenumber" ngModel="{{editEmployee?.phonenumber}}" formControlName="phonenumber">
<div *ngIf="commonForm.get('phonenumber')?.errors?.required && !form.submitted" class="invalid-tooltip">Number is required!</div>
</div>
<button class="btn btn-primary" type="submit" [disabled]="!commonForm.valid" (click)="updateEmployee(employee, Employee)" (click)="modalRef.hide()">Update</button>
<button type="button" class="btn btn-danger" style="display: inline-block;margin-left: 20px;" (click)="delete()" (click)="modalRef.hide()">Delete</button>
</form>
</div>
</div>
</div>
</div>
I just need to retrieve the values for the specific card when I click on it and be able to update it. But I cannot see what I am omitting. Inspect element says:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead

DeleteView - confirm by Popup windows

I want to ask you, if you know, is here some point or solution how to do confirm delete item with DeleteView class by Popup bootstrap window. So I will not use template_name, but popup windows on current page.
Thank you so much for everything...!!!
To be more precise
I have this button in my index.html page
<button type="button" class=" ml-1 btn btn-outline-dark my-2 my-sm-0" data-toggle="modal" data-target="#exampleModal">
In
</button>
And here I have modal for deleting
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Are you sure to delete this?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<div class="modal-footer">
Yes
<button type="button" class="btn btn-danger" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
</div>
and here is my views.py for delete
class ItemDeleteView(DeleteView):
model = Item
# template_name = 'index.html'
success_url = reverse_lazy('index')
login_url = '/accounts/login/'
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
and I don't know what to do. now... thanks
Best option would be Javascript, but you could instead redefine the get method of your DeleteView class :
Add that to your class
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
Basically the Deleteview need a post request to get trigger, it is a bit of a hack but works well.
In your template place this in your modal or popup
<form method="POST" action="{% url "your_delete_url_name" %}">
{% csrf_token %}<input type="submit" value="DELETE">
</form>
Do not forget the object id in your URL

How to convert html form to Django form and preserve styling?

I have a pure html form which I wish to use to collect sign-in information using a Django backend.
Here is my pure non-Django html form:
<form id="contactForm" method="POST">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Username or E-mail Address</label>
<input type="text" value="" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<a class="pull-right" href="#">(Lost Password?)</a>
<label>Password</label>
<input type="password" value="" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<span class="remember-box checkbox">
<label for="rememberme">
<input type="checkbox" id="rememberme" name="rememberme">Remember Me
</label>
</span>
</div>
<div class="col-md-6">
Login
</div>
</div>
</form>
Here is what it looks like with all the styling:
In order to process this form I have created a view:
def login_page(request):
form = LoginForm(request.POST or None)
context = {'form': form}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_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)
try:
del request.session['guest_email_id']
except:
pass
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
return redirect('/')
else:
print('Error')
return render(request, 'users/login.html', context)
I am aware that I need a form.py class which I have created and is as follows:
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput())
How do I use this form class to render the same form as done by the html preserving the styling. Additionally, once rendered how do I submit the form data for processing to the view by using the link disguised as a button below?
Login
In my experience with Django, it is not possible to create an HTML form as is in a Form inheriting from forms.ModelForm or forms.Form. The best we can do is, assign classes to the widgets which are assigned to the specific form fields in form of attrs, like so:
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
This will attach your CSS classes to the rendered form when you use {{ form.as_p }} or similar others in your template.
Then for rendering the divs, you unpack the form yourself, rather than letting Django do the work, like so:
<form id="contactForm" method="POST">
<div class="row">
<div class="form-group">
<div class="col-md-12">
{{ form.username.errors }}
<label for="{{form.username.id_for_label}}">Username or E-mail Address</label>
{{ form.username }}
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
{{form.password.errors}}
<a class="pull-right" href="#">(Lost Password?)</a>
<label for="{{form.password.id_for_label}}">Password</label>
{{form.password}}
</div>
</div>
</div>
.........
And so on.
However, it is generally considered a bad practice to couple your design and logic, which we clearly are doing here.
References: Django Documentation - Working With Forms

Form error in a Django form with Bootstrap tagsinput plugin

I am using Bootstrap/Tagsinput for adding tags in a Django input form.
Problem
The first field is where I want the tags added and the second field is a simple text field. I am able to add the tags in the first field and a normal text in the second field. But, when I submit the form the input values get removed and am returned to the original form. The django form.errors indicates that the second field is empty with a This field is required message even though I had entered a text! What am I missing?
form.errors
Is returning
<ul class="errorlist"><li>experiments<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Here are the related files
tags_add.html
I am using a custom html rather than the django's forms.as_table. All required css and min.js have been added in the html file.
<form id="defaultForm" method="post" action="" class="form-horizontal">{% csrf_token %}
<div class="form-group">
<label class="col-lg-3 control-label">Tags:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="aa" class="form-control" value="" data-role="tagsinput" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Experiments:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="exp_id" class="form-control" value="" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
forms.py
class TagsForm(ModelForm):
tags = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'add tags'}), required=True )
experiments = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'expid'}), required=True )
def __init__(self, *args, **kwargs):
super(TagsForm, self).__init__(*args, **kwargs)
class Meta:
model = Tags
fields = '__all__'
views.py
def view_tags(request,formtype):
form_type = formtype
if request.method == "POST":
form = form_type(request.POST or None)#, extra=extra_additives)
if form.is_valid():
instances = form.save(commit=False)
temp_str= str(instances)
print temp_str
experiment_tags = temp_str
return HttpResponse(experiment_tags)
else:
print "from view_tags {0}".format(form.errors)
return HttpResponse(form.errors)
else:
form = TagsForm()
return render(request, 'tags_add.html', {'form': form})
models.py
class Tags(models.Model):
tags = models.CharField(max_length=1000)
experiments = models.CharField(max_length=1000)
def __str__(self):
return ':'.join([self.tags, self.experiments])
I got it working by adding the following to a scripts tag in the html file:
$("input[name='tags']").tagsinput({
confirmKeys:[13] //-- Only enter
});

Html button is too small

I have a html form with an add button which is attached to the right hand side of a textbox, and a separate delete button. The form uses some bootstrap css. However, the delete button shows up on the page as a small grey square, with no text inside it. What is making it show up so strangely?
<form id = "myform">
<div class="col-lg-6">
<h3> New Group: </h3>
<div class="input-group">
<input type="text" id = "input" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick = "addTag()" >Add</button>
</span>
</div><!-- /input-group -->
<table class = "table" padding = "5">
<ul id = "list" class="list-group">
</ul>
</table>
<button type = "button" class="btn btn-default" value = "Delete" id = "deleteBtn" onClick = "if(confirm('Are you sure?'))
Delete()"></button>
</form>
You must move the text from value in between the tags
<button type = "button" class="btn btn-default" id = "deleteBtn" onClick = "if(confirm('Are you sure?')) Delete()">Delete</button>
JSFiddle
The spaces. You shouldn't use spaces for and after your "="-s. So:
value = "Delete"
is bad.
value="Delete"
is okay. Good luck! :-)