Add item to dropdown without refresh - python

City is a (dropdown in a main form ) with a +(Add) button.
This +(Add) button opens another form in separate window.
On saving a new city in the second form, I want the new city name to be added in the City dropdown without refreshing the main form.
Here is my code.
<form method="POST" enctype="multipart/form-data" id="form">
{% csrf_token %}
<td>City: {{ form.city }}
<button class="btn btn-primary" onclick="addCity(event)">+</button>
</td>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<script>
function addCity(e){
e.preventDefault();
window.open("/city/", "", "width=500,height=500");
}
</script>
city.html
<form method="POST" class="post-form" action="/city/" id="form">
{% csrf_token %}
<div class="container">
<div class="form-group row">
<label class="col-sm-2 col-form-label">City:</label>
<div class="col-sm-4">
{{ form.name }}
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
urls.py
urlpatterns = [
path('city/', views.add_city, name='city_master'),
]
views.py
def add_city(request):
cities = City.objects.all()
if request.method == "POST":
form = CityForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/city/')
except:
pass
else:
form = CityForm()
return render(request,'city.html',{'form':form})

I can not comment that is why i am writing here, Sir you need ajax call. Do not use POST request, for all post request the page reloads it self. so try using ajax, you can create a route and function inside controller.

Related

HTML button onclick action with Django function

HTML form on Django.
I want to perform or create web page in which the button performs the action, and in backend I am handling the Django function.
The code of HTML file is:
<form name="bookappointment" class="form" method="POST">
{% csrf_token %}
<br>
<input type="hidden", name="selecteddoctornumber" value="{{i.doctornumber}}">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn approve" name="approvebtn">Approved</button>
</div>
<div class="col-md-1"></div>
<div class="col-md-4">
<button class="btn notapprove" name="notapprovebtn">Not Approved</button>
</div>
<br>
</div>
<a class="btn cancel" href="requests">Cancel</a>
<br>
</form>
and the other side the Django function is:
if request.method == 'POST':
if request.POST.get('approvebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Approved'
return redirect('request')
if request.POST.get('notapprovebtn'):
for i in doctor:
if pendingDoctorNumber == i.contactNumber:
i.status = 'Not Approved'
return redirect('request')
but its not working any action just get me back to same page
<form action="{% url 'bookappointment' %}" method="POST">
you have to define bookappointment in your urls.py which redirect to views.py where your function lies with name bookappointment.

go back to previous page in django

I want to save the data in the form and go back to previous page when I click on 'Add' button. It's showing some errors. Can anyone suggest the correct way to do it?
template.html
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Add your own Category </h3>
</div>
<div class="panel-body">
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
</div>
</div>
</div>
<input type="hidden" name="next" value="{{ request.path }}">
<button type="submit" class="save btn btn-default" >Add</button>
</form>
views.py
class CustomCategory(LoginRequiredMixin,CreateView):
model = Category
form_class = CategoryForm
def form_valid(self, form):
obj = form.save(commit=False)
def category(request):
next = request.POST.get('next', '/')
return render (request,HttpResponseRedirect(next))
Instead of adding the redirect as an element of the form, why don't you use the success_url field on the view, or if the URL you need to go to depends on an object, use the get_success_url method on the view?
https://docs.djangoproject.com/en/2.0/ref/class-based-views/mixins-editing/

Passing value along with form in POST data in Django

When I render the form in HTML, I use this view. the patient_id is used to denote what patient the check in is for and for name display and such.
def Checkin(request, patient_id):
patient = get_object_or_404(PatientInfo, pk=patient_id)
form = forms.PatientCheckinForm()
return render(request, 'patientRecords/checkin.html', {'patient': patient, 'form':form})
When I submit the patient form filled out as a POST method, I still need access to the patient_id. Currently this is the view that accepts the filled form:
def CheckinSubmit(request):
if request.method == 'POST':
form = forms.PatientCheckinForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.date_time_of_checkin = dt.now()
instance.patient = patient.patient_id
instance.save()
return redirect('patientRecords/index.html')
I want to set the instance.patient to the patient_id that was part of patient from the Checkin view. Is there a way to pass the patient data back along with the POST method or is there another way this can be done?
For reference, here is my template and I am using ModelForm not form.
{% block content %}
<div class="container">
<h1>Patient Checkin</h1>
<h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
<form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
Thanks in advance!
You should be able to simply add a hidden input to your form to capture the patient ID:
{% block content %}
<div class="container">
<h1>Patient Checkin</h1>
<h2>{{patient.first_name}} {{patient.last_name}}</h2>
</div>
<div class="container">
<form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form">
<input type="hidden" name="patient_id" value="{{patient.patient_id}}" />
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
(Note this assumes that the patient ID is accessible from the patient_id property of the patient object.)
Then, in your CheckinSubmit method, you can access this value via request.POST.get('patient_id')
Alternatively, it appears that your check in form loads with the patient ID in the URL. In your CheckinSubmit method, you should be able to access this URL through the request.META.HTTP_REFERER property. You could then parse the URL (e.g., using request.META.HTTP_REFERER.split('/')[len(request.META.HTTP_REFERER.split('/')) - 1] to pull out the patient ID.
Example
<form method="post" action = "{% url 'user_search_from_group' %}">
<div class="module-option clearfix">
<div class="input-append pull-left">
<input type="hidden" name="groupname" value="{{ gpname }}" />
{% csrf_token %}
<input type="text" class="span3" placeholder="Filter by name" id="username3" name="username3" required>
<button type="submit" class="btn" name="submit">
<i class="icon-search"></i>
</button>
</div>
</div>
</form>
Here a hidden field is used to pass a value along form.
def user_search_from_group(request):
if request.method == 'POST':
username3 = request.POST.get('username3')
gname = request.POST.get('groupname')
Using request we are use the value inside view

Django: redirect user two pages back

I have a list of multiple objects from my database (named "plp's"), arranged in a table. Next to each "plp" element I have a button "Edit" to modify that particular entry.
Next, I redirect the user to a new url, where I pass the id of that "plp", and show the form to edit it, with a "save" button.
After pressing the "save", which is request.POST, I want to redirect the user back to the first url, with the list of all the "plp" objects in one list. That means to the site, where he first pressed "Edit".
Can I somehow save the url of where the "Edit" was clicked, and pass it to my views.py?
Thank you
listdns.html:
<td>
Uredi
</td>
urls.py:
rl(r'^(?P<plp_id>\d+)/uredi$', plp_list_uredi,name="plpuredi")
views.py:
def plp_list_uredi(request, plp_id=None):
moj_plp=PLPPostavka.objects.get(id=plp_id)
form=PLPPostavkaForm(request.POST or None,request=request,dns=moj_plp.dns, instance=moj_plp)
context ={
'plp':moj_plp,
'form':form,
}
if request.POST:
if form.is_valid():
plp = form.save()
return redirect(request.path)
return render(request, "plp_pos/uredi.html",context)
uredi.html
<form action="" method="POST">
{% csrf_token %}
<div class="box">
<div class="box-header">
<h4 class="box-title">
Urejanje PLP Postavke
</h4>
</div>
<div class="box-body">
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" class="col-md-2 control-label detail">{{ field.label }}</label>
<div class="col-md-10">
{% if field|field_type == "datefield" %}
{% render_field field class+="form-control dateinput" %}
{% else %}
{% render_field field class+="form-control" %}
{% endif %}
</div>
</div>
{% endfor %}
</div>
<div class="box-footer">
<div class="box-tools pull-right">
<input type="submit" value="Shrani" class="btn btn-primary" />
</div>
</div>
Don't you only have 1 page to edit all the elements? Then you could perhaps hardcode the link e.g.
return HttpResponseRedirect(my_edit_url)
If this doesn't work and you need to go 2 pages back take a look at this post:
How to redirect to previous page in Django after POST request

Django : get data and edit in the same form, edit in one place

I've been working to make an edit form where shows data saved in db and user can edit it like jsp model and view. When user click button it shows add form but all the relevant information in db is already filled up in the form, so user can modifying old data and once they click submit button it redirect to main.
I succeeded to display a form when user click edit button but failed to get data.
this is views.py
#login_required
def update_article(request, article_no):
article = get_object_or_404(Article, no=article_no)
if request.method == "POST":
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog.views.detail', no=article.no)
else:
form = ArticleForm(instance=article)
return render(request, 'blog/update_article.html', {'form': form})
urls.py
url(r'^update_article/(?P<article_no>[0-9]+)/$', views.update_article, name='update_article'),
update_article.html
{% extends 'blog/base.html' %}
{% block body %}
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<button type="submit" class="button-primary">submit</button>
</form>
list
{% endblock %}
detail.html
This is part of the page send users to update_article.html
<form action="{% url 'blog:update_article' item.no %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit" class="button-primary">edit</button>
</form>
form_template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2" for="title">{{ field.label_tag }</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
In update_article views
pass article object with form
return render(request, 'blog/update_article.html', {'form': form, 'article': article})
and then form in html page
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<input class="u-full-width" type="text" name="title" value="{{article.title}}"/>
<textarea class="u-full-width" name="content" value="{{article.content}}"></textarea>
<button type="submit" class="button-primary">등록</button>
</form>
I think this would help your problem
also I guess your action link is not valid

Categories

Resources