How can show variable in UI in django from view function? - django

I want to show value of pro in UI but not getting , here is my test view function code .value of pro is getting from previous function using django session variable.
#api_view(['GET', 'POST'])
def test(request):
pro = request.session.get('j')
print("Request ID from Index View : ", pro)
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
print("Form is Valid")
selected = form.cleaned_data.get('myfield')
print(selected)
else:
# rq = request_id["request_id"]
s = sql()
query = f"""update request_form_db.request_form_mymodel
set is_approved=1
where request_id = '{pro}' """
print(query)
s.update_query(query)
print("Updated Successfully")
form = TestForm()
else:
form = TestForm()
context = {'form': form, 'pro': pro}
return render(request, 'test.html', context)
Here is my html code test.html
<form action ="{% url 'test' %}" method="POST">
<div class="form_data">
{% csrf_token %}
<br><br>
{{form.myfield}}
<label><b>Git Id</b></label> <br><br>
<br><br>
{{form.pro}}
<input type="submit" value="Submit" class="btn btn-success" />
form.myfield returns what i want but value of pro variable not getting.please help

Just pass same key as you created in context. you dont have to use {{ form.pro }}
context = {'form': form, 'pro': pro}
In html you can render with:
{{ pro }}

Related

Why my product photo is not updating? But product title is updating

I have an update form to update information. Here problem is, product_title is updating but product_image is not working. Where is the problem that's for why the photo is not updating?
views.py:
def update_product(request,id):
product = Products.objects.get(pk=id)
form = update_product_info(request.POST or None, instance=product)
if request.method == 'POST' and form.is_valid():
form.save()
print(form.errors)
messages.success(request,"Successfully product information updated.")
return redirect("my_products")
context = {
'product':product,
"form":form
}
return render(request, "update_product.html", context)
update form:
class update_product_info(forms.ModelForm):
class Meta:
model = Products
fields = ('product_title','product_image')
widgets = {
'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}),
'product_image':forms.FileInput(attrs={'class':'form-control', 'style':'font-size:13px;'})
}
template:
<form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<div class="d-flex align-items-center">
<button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button>
</div>
You should pass both request.POST and request.FILES to the form:
from django.shortcuts import get_object_or_404
def update_product(request, id):
product = get_object_or_404(Products, pk=id)
if request.method == 'POST':
form = update_product_info(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save()
messages.success(request, 'Successfully product information updated.')
return redirect('my_products')
else:
form = update_product_info(instance=product)
context = {'product': product, 'form': form}
return render(request, 'update_product.html', context)
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.
Note: normally a Django model is given a singular name, so Product instead of Products.
Note: Usually a Form or a ModelForm ends with a …Form suffix,
to avoid collisions with the name of the model, and to make it clear that we are
working with a form. Therefore it might be better to use ProductInfoForm instead of
update_product_info.

Cannot pull the value from the key of a session dictionary in django

I have a session variable for the name of a company saved in my django view from a user input form. When I try and use this in a later view, no matter what I try it pulls the {key: value} pair rather than just the value
Views:
def start(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = QuizTakerForm(request.POST )
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
post = form.save(commit=False)
post.user = request.user
post.save()
request.session['obj_id'] = post.id
request.session['company_name'] = form.cleaned_data
# redirect to a new URL:
return HttpResponseRedirect('industry/')
....
def Gov_q1(request):
company_name = request.session.get('company_name')
print(company_name)
question = Question.objects.get(pk=24)
context = {'question': question, 'company_name': company_name}
return render(request, 'ImpactCheck/detail.html', context)
html:
<h1> Hi my name is {{ company_name }} </h1>
<h1>{{ question.text }}</h1>
<form action="." method="post">
{% for answer in question.answer_set.all %}
<input type="radio" name="answer" id="answer" value="{{ answer.id }}">
<label for="answer">{{ answer.answer_text }}</label><br>
{% endfor %}
<input type="submit" value="Submit">
</form>
Ive also tried company_name=request.session['company_name'], but both then render as {'company_name': 'test_company'} rather than test_company.
FYI If anyone has a similar issue I've circumvented using
def Gov_q1(request):
id=request.session.get('obj_id')
company_name= QuizTakers.objects.get(pk=id)
question = Question.objects.get(pk=24)
context = {'question': question, 'company_name': company_name, 'cn': cn}
return render(request, 'ImpactCheck/detail.html', context)

My django form returns empty cleaned_data

I have a simple Form, view and a html that renders the form. but the problem is that the form always returns form.is_valid == False.
So I have checked the cleaned data but I noticed that self.cleaned_data returns an empty list.
Here is the relevant code:
class GraphForm(forms.Form):
from_month = forms.DateField(widget=forms.Select(choices=MONTHS))
from_year = forms.DateField(widget=forms.Select(choices=YEARS))
to_month = forms.DateField(widget=forms.Select(choices=MONTHS))
to_year = forms.DateField(widget=forms.Select(choices=YEARS))
def clean(self):
return self.cleaned_data <<< will always stay be empty
def showgraph(request):
if request.method == 'POST':
form = GraphForm(request.POST)
if form.is_valid():
>>> will never happen <<<
...
...
...
else:
form = GraphForm()
return render(request, 'graph.html', {"form": form})
<form method="post">
{% csrf_token %}
{{ form.from_month }}
{{ form.from_year }}
<br>
{{ form.to_month }}
{{ form.to_year }}
<br>
<p align="center">
<button type="submit" class="btn btn-primary">send</button>
</p>
</form>
Can anyone help with this peculiar problem?
The <form> tag should have action besides method so that the submit button can work, like this.
<form action="{% url 'name_of_the_view' %}" method="post">
...
</form>
If the code doesn't reach inside form.is_valid(), then it means the form is not valid, add an else to if and print the form.errors() and return the same form to template also add form error in the template to see the errors.
def showgraph(request):
if request.method == 'POST':
form = GraphForm(request.POST)
if form.is_valid():
>>> will never happen <<<
else:
print(form.errors())
else:
form = GraphForm()
return render(request, 'graph.html', {"form": form})
Add error for each field:
<span class="text-danger">{{field.errors.as_text|cut:'* '}}</span>

Form is not rendered in the template after redirection (django)

I have a view and its template that handles and prints a form. The form has a ChoiceField that takes a list of models as choices. Here is my view, template and form:
*views.py*
def index(request):
form = dbForm()
print "form is: ", form
return render(request, 'Directories/index.html', {'form':form})
*index.html*
<div id="content" align="center">
<form action="" method="get"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Edit" name="_add" />
</form>
*forms.py*
model_classes = []
class dbForm(forms.Form):
model_classes_field = forms.ChoiceField(choices=models())
def models():
apps = get_app('Directories')
for model in get_models(apps):
model_classes.append( (model._meta.verbose_name, model._meta.db_table), )
return model_classes
The model choice submitted is sent to another view where a ModelForm displays the model's fields and expects data for each of the fields to be submitted. The submitted data are then stored in the database and the user is redirected back to the index to start again from the beginning. Here is the view, template and form:
*views.py*
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
return render(request, 'Directories/index.html')
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')
*create.html*
<form action="" method="post"> {% csrf_token %}
{% for f_name in field_names %}
{% if not forloop.first %}
{{f_name}}: <input id="edit-{{f_name}}" type="text" name={{f_name}} /><br />
{% endif %}
{% endfor %}<br />
<input type="submit" name="update" value="Update" />
<input type="reset" name="Clear" value="Clear" />
</form>
*forms.py*
#create a ModelForm using a dynamic model
def get_dynamic_form(c_model):
model_class = get_model('Directories', c_model)
class ObjForm(forms.ModelForm ):
class Meta:
model = model_class
return ObjForm
The problem occurs when the form is redirected back to the index.html return render(request, 'Directories/index.html') after the data have been saved into the database. What happens is that the index.html does not display the form {{form.as_p}}at all. Although when i check print "form is: ", form in my server (Apache) error.log, my form is there printed as it should be.
I cannot understand why the data are not rendered in my template after the redirection occurs but still they are displayed correctly in my server log.
You should pass the form instance to your template as you do in index view. Your code shall be updated to
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
#------------------------------------------------v pass it to template
return render(request, 'Directories/index.html', {'form': form})
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')

Django POST to other view

I have the following form that lives on the site root at /
<form action='/play/' method='post'>
{% csrf_token %}
{{ form.player_name }}
<input id='play' type='submit' value='Play'>
</form>
then I have the view that validates this form:
def login(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/play/')
else:
context.update(dict(form=form))
else:
context.update(dict(form=LoginForm(initial={'player_name':'Please tell us your name'})))
return render_to_response('login.html', context, context_instance=RequestContext(request))
And the actual play view:
def play(request):
p1 = briscola.Player(request.POST['player_name'])
The problem is that of course the redirect looses the POST data. But why doesn't it POST directly to the play view by itself when the form.is_valid?