Passing data view-template-view in django - python

I'm handling input file in my project and passing processed text to another html for user approvement
def vm_to_csv_upload(request):
if request.method == "POST":
some code here
br_work_string = re.sub('\\n', '<br>', work_string)
page_text = 'Here\'s what gonna be uploaded to crowdin:<br><br><br>' + br_work_string + '<br><br><br>Is that okay?'
return render(request, 'upload_crowdin_check.html', {'page_text': page_text, 'csv_text': work_string})
On this page i show passed data:
<body>
<div id="text_check">
{% autoescape off %}
{{ page_text }}
{% endautoescape %}
</div>
<form action="/crowdin_approve/" method="POST" value={{ csv_text }} id="csv">
{% csrf_token %}
<input type="submit" class="btn btn-xs btn-danger" value="Okay">
</form>
</body>
And trying to pass it to another view to process it again.
def crowdin_approve(request):
if request.method == "POST":
return HttpResponse(request.POST)
else:
return HttpResponse('nope')
But only thing i get is csrfmiddlewaretoken. What am i doing wrong? How should i pass {{ csv_text }} value to view? Thx.

You can pass the content of csv_text using an hidden input field:
<form action="/crowdin_approve/" method="POST" id="csv">
{% csrf_token %}
<input type="hidden" name="csv_text" value="{{ csv_text }}">
<input type="submit" class="btn btn-xs btn-danger" value="Okay">
</form>
Then you can access it in the view this way:
def crowdin_approve(request):
if request.method == "POST":
csv_text = request.POST.get('csv_text', None)

Related

Add item to dropdown without refresh

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.

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 ManyToMany relationship details

I want to build a website in which users can send words to each other using Django. When a user deletes a word, that word will be deleted for only that user. I have a working website; the only problem is when a word is deleted, it is deleted for all users. How can I fix this problem, is it a problem which is related to ManyToMany relationships?
Django word model:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Word(models.Model):
definition = models.CharField(max_length=350)
turkish = models.CharField(max_length=50)
english = models.CharField(max_length=50)
users = models.ManyToManyField(User)
creator = models.CharField(max_length=50)
def __str__(self):
return self.english
def summary(self):
return self.definition[:50] + "..."
The share view function:
#login_required
def send(request):
users_list = User.objects.all().exclude(username=request.user.username)
user = request.user
small = user.username.title()
send_to_str = request.POST['user']
sent_word_str = request.POST['word']
send_to = User.objects.get(username=send_to_str)
sent_word = Word.objects.get(id=sent_word_str)
if not users_list:
sendmessage = 'You have no friends'
else:
sendmessage = ''
sent_word.users.add(send_to)
words = Word.objects.filter(users=user).order_by('-english')
return render(request, 'intro.html', {'sendmessage': sendmessage, 'words': words, 'small' : small})
The delete view function:
#login_required
def delete(request):
if request.method == 'POST':
current_id = request.POST['word_id']
current_word = Word.objects.get(id=current_id)
current_word.delete()
messages.add_message(request, messages.INFO, 'Succesfully deleted.')
return redirect('translater:home')
else:
return render(request, 'intro.html', {'message': 'there is a problem'})
Redirected to this html:
{% if words %}
<h3 style="color:gray;font-weight:bold">My Word List</h3>
<br>
{% endif %}
{% for word in words %}
<h4 style="color:red">{{ word.english }} / {{ word.turkish }} </h4>
<h4 style="color:green">{{ word.summary }} / {{ word.creator }}</h4>
<br>
<button type="button" onClick="document.getElementById('deleterForm').submit()" class="btn btn-warning">Delete!</button>
<button type="button" onClick="document.getElementById('sharerForm').submit()" class="btn btn-primary">Share!!</button>
<form id="deleterForm" action="{% url 'translater:delete' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="word_id" value="{{ word.id }}">
</form>
<br>
<form id="sharerForm" action="{% url 'translater:share' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="word_id" value="{{ word.id }}">
</form>
<form id="senderForm{{ word.id }}" action="{% url 'translater:send' %}" method="POST">
{% csrf_token %}
{% for user in users_list %}
<input type="submit" name="user" value="{{ user }}">
<input type="hidden" name="word" value="{{ word.id }}">
{% endfor %}
{{ sendmessage }}
</form>
<br>
{% endfor %}

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

django-why this form is always invalid

i have created a form with minimal fields(for testing) , but it never enters form.is_valid()
Here is the minimal code
in the models.py
from django.db import models
class sample(models.Model):
field1=models.CharField(max_length=100)
field2=models.CharField(max_length=100)
in the forms.py
from django.forms import ModelForm
from app.models import sample
class someform(ModelForm):
class Meta:
model=sample
in the views.py
some imports
def index(request):
return render(request, 'app/index.html')
def contact(request):
if request.method=='POST':
form=someform(request.POST)
if form.is_valid():
field1=form.cleaned_data['field1']
field2=form.cleaned_data['field2']
return HttpResponse("valid")
else:
return HttpResponse("invalid")
else:
form=someform()
return HttpResponse("error")
The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help
in the index.html
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="submit" id="submit" name="submit">
</form></body></html>
First pass your form to index.html, when the request is not POST in views.py:
else:
form=someform()
return render(request, 'index.html', locals())
In template you should make it like this:
<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Submit</button>
</form>
When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="id_field1" name="field1">
<input type="text" id="id_field2" name="field2">
<input type="submit" id="submit" name="submit">
</form>
</body>
</html>
Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside or tags automatically.
You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.

Categories

Resources