Django Function Base View Search Form By Primary Key - python

The code sample as novice of Django, is it right practice to achieve page load per ID as shown below?
View.py
def testidbasesearch(request,id=None):
if request.method == "GET":
print ('Inside IF GET')
if not id:
form = MtiForiegnForm()
else:
instance = Mt_Issue_foriegn.objects.get(id=id)
form = MtiForiegnForm(request.POST or None, instance=instance)
else:
print ('Inside Else GET')
id=request.POST.get('pkid')
return redirect(reverse('testidbasesearch', kwargs={"id": id}))
return render(request,'testingpost.html',{'form':form})
url.py
path('testidbasesearch',testidbasesearch,name='testidbasesearch'),
path('testidbasesearch/<int:id>',testidbasesearch,name='testidbasesearch'),
testingpost.html
{% extends 'base.html' %}
{% block content %}
<form id="postform1" method="post" action="">
{% csrf_token %}
<input type="text" name="pkid" />
<input type="submit" id="submit-form" />
{% for form1 in form %}
<fieldset disabled="disabled">
{{ form1 }}
</fieldset>
{% endfor %}
</form>
{% endblock %}
First of all my functionality is working as expected , I just need review is it right code practice, I purposely avoid AJAX/jquery ( i.e. js) pure django /python code to load form based on id submitted.

Related

Delete button in a template is inactive

enter code hereI have a group_edit.html which permit to update info of a group and delete it.
Upade(save) works great but button for delete is doing nothing.
Thanks for help:
My group_edit.html:
{% block page %}
<form method="POST">
{% csrf_token %}
<div class="col-lg-4 col-md-4 col-sm-4 content">
{% bootstrap_form form %}
<button type="submit" class="btn btn-pink pull-right">Save</button>
<button type="reset" class="btn btn-warning pull-left">Delete</button>
</div>
Back to list
</form>
{% endblock %}
My confirm_delete.html template:
{% block title %}Delete{% endblock %}
{% block heading %}<h3 class="page-header-center">Object Delete</h3> {% endblock %}
{% block page %}
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ obj }}"?</p>
<input type="submit" value="Confirm" class="btn btn-warning">
Cancel
</form>
{% endblock %}
my views.py:
def group_edit(request, group_id):
form = GroupForm(instance=Group.objects.get(group_id=group_id))
if request.method == "POST":
form = GroupForm(request.POST, instance=Group.objects.get(group_id=group_id))
if form.is_valid():
form.save()
messages.success(request, 'Group saved') # message for inform user of success - See messages in html file
return redirect(group_list)
return render(request, 'imports/group_edit.html', {
"group_id": group_id,
"form": form,
})
def confirm_delete(request, group_id):
obj = GroupForm(instance=Group.objects.get(group_id=group_id))
if request.method == "POST":
obj.delete()
messages.success(request, 'Deleted') # message for inform user of success - See messages in html file
return render(request, 'imports/group_list.html')
context = {
"obj": obj
}
return render(request, "imports/confirm_delete.html", context)
and my urls.py:
path('group_edit/<int:group_id>/', views.group_edit, name='group-edit'),
path('confirm_delete/<int:group_id>/', views.confirm_delete, name='confirm-delete'),
In your link, the span of <a> is empty. So instead of
Delete
it should be:
Delete
Probably it is better to specify the {% url ... %} parameters with named parameters:
Delete

Django - Template tags not working properly after form validation

I am having a form which takes some value as input, and I am processing the input and returning the required output. Now when I tried to display the output it not displaying on the webpage.
The following is my forms.py:
class CompForm(forms.ModelForm):
class Meta:
model = Comp
fields = ('inp',)
The following is my views.py:
def index(request):
form = CompForm(request.POST or None)
context = {
'form': form,
}
print context
if form.is_valid():
...
...
outData = "The values you gave is correct"
errData = "The values you gave is incorrect"
print context
context['outData'] = outData
context['errData'] = errData
print context
return render(request, 'comp/index.html', context)
The following is my index.html:
{% extends "comp/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form method="post" action="">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" name="Submit" />
</form>
</div>
</div>
{% if outData %}
{{ outData.as_p }}
{% endif %}
{% if errData %}
{{ errData.as_p }}
{% endif %}
{% endblock %}
In the terminal I am able to get the outData and errData in the dictionary, but its not getting displayed in the webpage. What might be the mistake? Kindly help.
You are trying to called the method as_p on strings which doesn't make sense.
as_p() is a helper method on form instances to make it easier to render them in the template so you need:
{{ form.as_p }}
you can also use as_table and as_ul
You can read more in the documentation

How to delete object in django view?

I have a model Product:
class Product(models.Model):
name = models.CharField(verbose_name="name", max_length=40)
cost = models.FloatField(verbose_name="price")
def __unicode__(self):
return self.name
I created a view where i can add new products but how can i delete these products?
my idea:
def delete_product(request, pk):
if request.method == "POST":
if form.is_valid():
product = form.delete(commit=False)
product.delete()
return redirect('homeshop.views.product_list', pk=product.pk)
But what next? I added to template (where i can edit product and save it) but it does not work:
{{ delete_product }}
Now in my template:
{% block content %}
<h1>Nowy wydatek</h1>
<form method="POST" class="product-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
You would need to do something like this:
template.html
{% for product in products %}
{% csrf_token %}
...
<form action="{% url 'delete_product' product.id %}" method="POST">
<button type="submit">Delete</button>
</form>
...
{% endfor %}
then you would need to update your urls.py to have a URL defined that calls your delete function when the proper URL is visited.
url(
r'^delete/<product_id>$',
'delete_product',
name='delete_product'
)
I don't know exactly how your urls.py is laid out so your URL may have to look a little different.

Django Very simple navigation bar, my form does not show up after {% extend "base.html" %}

I am writing a very simple navigation bar. For example I have my login view down below. When I open the login page I can see my the results of my base.html but for some reason I can not see the results of my login.html, meaning I cant see the form I wrote only the top links bar.
view.py -- login view
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
m = UserLogin.objects.get(user_name=request.POST['user_name'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponseRedirect('/game')
else:
c = {'form': form,
'error_message': "Your username and password didn't match."}
c.update(csrf(request))
return render_to_respons('game/login.html', c)
else:
form = UserLoginForm()
c = {'form': form}
c.update(csrf(request))
return render_to_response('game/login.html', c)
base.html
<div id="navigation">
Home
Upload
Register
Login
</div>
login.html
{% extends "base.html" %}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/game/login/" method="post">
{% csrf_token %}
<table border='0'>
<div class="fieldWrapper"><tr><td>
{{ form.user_name.errors }}</td><td></td></tr><tr><td>
<label for="id_user_name">User Name:</label></td><td>
{{ form.user_name }}</td></tr>
</div>
<div class="fieldWrapper"><tr><td>
{{ form.password.errors }}</td><td></td><tr><td>
<label for="id_password">Password:</label></td><td>
{{ form.password }}</td></tr>
</div>
</table>
<input type="submit" value="Login" />
</form>
You need to define blocks to use template inheritance. For example, change your base.html to:
<div id="navigation">
Home
Upload
Register
Login
</div>
{% block content %}{% endblock %}
then place your login code into the content block:
{% extends "base.html" %}
{% block content %}
...login.html content goes here
{% endblock %}
Check out the docs for more detail.

Setup POST HTTP Request to create variable .vnc file

I have a database with users information and IP's. What I would like to do is to dynamically create, and then open, a *.vnc file with their IP.
In my views.py file I have this:
def view_list(request):
template_name = 'reader/list.html'
cust_list = xport.objects.all()
#if request.method == 'POST':
#<a href=link to created *.vnc file>Connect to client</a>
return render(request, template_name, {'xport': cust_list})
The commented out portion is just what I've been playing with and what I currently think I need to do.
My template file is list.html and looks like this:
{% extends "base.html" %}
{% load url from future %}
{% block content %}
<h1> Customer List </h1>
<ul>
{% for c in xport %}
{% if c.ip %}
<li>{{ c.firstName }} {{ c.lastName }}</li>
<form method="POST" action=".">{% csrf_token %}
<input type="submit" name="submit" value="Create VNC to {{ c.ip }}" />
</form>
{% endif %}
{% endfor %}
</ul>
{% endblock %}
What I would like to do is to click on the "Create VNC" button and then that create and open the *.vnc file.
This should give you an idea:
url(r'^file/vnc/$', 'myapp.views.vnc', name='vnc-view'),
views.py
from django.views.decorators.http import require_POST
#require_POST
def vnc(request):
ip = request.POST.get('ip', None)
response = HttpResponse(ip, content_type='application/octet-stream')
# If you don't want the file to be downloaded immediately, then remove next line
response['Content-Disposition'] = 'attachment; filename="ip.vnc"'
return response
template
<form method="POST" action="{% url 'vnc-view' %}">{% csrf_token %}
<input type="hidden" name="ip" value="127.0.0.1" />
<input type="submit" name="submit" value="Create VNC to 127.0.0.1" />
</form>

Categories