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>
Related
There is a view in the Django project (a paginated blog) that is responsible for how likes work. It has one drawback: when a user likes a post, it is redirected to the main page of the site. How can I fix this so that the user would remain on the page where they liked.
views.py
class AddLikeView(View):
def post(self, request, *args, **kwargs):
blog_post_id = int(request.POST.get('blog_post_id'))
user_id = int(request.POST.get('user_id'))
url_from = request.POST.get('url_from')
user_inst = User.objects.get(id=user_id)
blog_post_inst = News.objects.get(id=blog_post_id)
try:
blog_like_inst = BlogLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst)
except Exception as e:
blog_like = BlogLikes(blog_post=blog_post_inst,
liked_by=user_inst,
like=True)
blog_like.save()
return redirect(url_from)
template.py
<form action="{% if not is_liked_bool %}{% url 'add' %}{% else %}{% url 'remove' %}{% endif %}" method="post">
{% csrf_token %}
<input type="hidden" name="blog_post_id" value="{{ blog_post_id }}">
<input type="hidden" name="user_id" value="{% if user.is_authenticated %}{{ request.user.id }}{% else %}None{% endif %}">
<input type="hidden" name="url_from" value="{{ request.path }}">
{% if is_liked_bool %}
<input type="hidden" name="blog_likes_id" value="{{ blog_likes_id }}">
{% endif %}
<button type="submit" class="btn btn-success">
{% if not is_liked_bool %}
<i class="fi-xnluxl-heart">♥</i>
{% else %}
<i class="fi-xnluxl-heart-solid">♥</i>
{% endif %}
<span class="likes-qty">{{ likes_counter }}</span>
</button>
I think you should check the url_from field first. Just print it and if it's wrong, you should change the {{request.path}} field in your template.
You can try this:
{{ request.get_full_path }}
And also if I remember correctly, you can access the path with request.path in your view and no need to send path via template.
When i click on the submit button i am getting the 404 error, i want to submit to the "new_search"
{% extends 'base.html' %}
{% block content %}
<form action="{ % url 'new_search' %}" method="post">
{% csrf_token %}
<input type="text" name="search" value="search" placeholder="search">
<input type="submit" name="submit">
</form>
{% endblock content %}
page
There is a typo in your code, replace:
{ % url 'new_search' %}
with
{% url 'new_search' %}
So, i want to get the checked checkboxes items ids as a list and show them on another page. But when i get to that specific page i get the value 'None' instead of the list of ids. What could go wrong? I tried some different versions from another questions already posted on the site, but the result was the same.
Here is the code:
models.py:
from django.db import models
class afirmatii(models.Model):
text = models.CharField(max_length = 250)
def __str__(self):
return self.text
views.py:
def exam(request):
if request.method == 'POST':
checks = request.POST.get('selected[]')
request.session['checks2'] = checks
context = {
'title' : 'Title1',
'aff': afirmatii.objects.order_by('id')
}
return render(request, 'pages/exam.html', context)
def result(request):
checks = request.session.get('checks2')
context = {
'title' : 'Title2',
'checks': checks
}
return render(request, 'pages/result.html', context)
exam.html:
{% extends "./base.html" %}
{% block content %}
<div class="text-break">
<form action="{% url 'result' %}" method="POST">
{% csrf_token %}
{% for q in aff %}
<div class="border mb-3 rounded-sm bg-light p-2">
<div class="custom-control custom-checkbox checkbox-info">
<input type="checkbox" class="custom-control-input" id="{{ q.id }}" name = "selected[]">
<label class="custom-control-label" for="{{ q.id }}" name = 'selected[]'> {{ q.text }} </label>
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-md btn-outline-info">Next</button>
</form>
</div>
{% endblock content %}
result.html:
{% extends "./base.html" %}
{% block content %}
<body>
<div class="text-center">
<p class="pb-5"> {{ checks }} </p><br>
<div class="row">
<div class="col">
Home
</div>
<div class="col">
Learn more
</div>
</div>
</div>
</body>
{% endblock content %}
You can try use FORMSETS A formsets is a layer of abstraction to work with multiple forms on the same page.
You can paint the list of questions according to records in the table and get ids (or other fields) of the marked answers
forms.py
class ExamForm(forms.Form):
checkbox = forms.BooleanField(required=False)
id = forms.CharField(widget=forms.HiddenInput)
text = forms.CharField(widget=forms.HiddenInput)
views.py
from django.shortcuts import render
from django.forms import formset_factory
from .forms import *
def exam(request):
aff = afirmatii.objects.order_by('id')
exam_formset = formset_factory(ExamForm, extra=0)
formset = exam_formset(initial=[{'id': x.id, 'text': x.text} for x in aff])
checks = []
if request.method == 'POST':
formset = exam_formset(request.POST)
if formset.is_valid():
for form in formset.forms:
if form.cleaned_data.get('checkbox', None):
checks.append(form.cleaned_data)
context = {
'formset': formset,
'checks': checks,
}
return render(request, 'pages/exam.html', context)
exam.html
{% if not checks %}
<h1>Exam:</h1>
<form action="{% url 'exam' %}" method="POST">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset.forms %}
<div class="form-group">
{{ form.checkbox }}
{{ form.text.value }}
{{ form.id }}
{{ form.text }}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% else %}
<h1>Results:</h1>
{% for check in checks %}
<p>{{ check.id }} {{ check.text }}</p>
{% endfor %}
{% endif %}
I have a page that contains a form. It has 3 buttons, Enter/Leave and Options. My enter and leave button operate just fine, but the options button is supposed to redirect to a list of entries and currently it does not do anything, not even produce errors, which I can't figure out why it's happening.
I feel like I'm missing something very slight, I tried moving the Manager Options button into the form tags but this did not work either, so I'm not sure I'm missing an important piece as I am fairly new to Python/Django.
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['adp_number']
if 'enter_area' in self.request.POST:
form.save()
return HttpResponseRedirect(self.request.path_info)
elif 'leave_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(adp_number=emp_num).update(time_out=datetime.now())
return HttpResponseRedirect(self.request.path_info)
elif 'manager_options' in self.request.POST:
return redirect('enter_exit_area_manager_options_list')
class EnterExitAreaManagerOptionsList(ListView):
filter_form_class = EnterExitAreaManagerOptionsFilterForm
default_sort = "name"
template = "operations/list.html"
def get_initial_queryset(self):
return EmployeeWorkAreaLog.active.all()
def set_columns(self):
self.add_column(name='Employee #', field='adp_number')
self.add_column(name='Work Area', field='work_area')
self.add_column(name='Station', field='station_number')
urls.py
urlpatterns = [
url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),
url(r'enter-exit-area-manager-options-list/$', EnterExitAreaManagerOptionsList.as_view(), name='enter_exit_area_manager_options_list'),
]
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<div>
{{ form.adp_number.help_text }}
{{ form.adp_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
<div>
{{ form.station_number.help_text }}
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% endblock main %}
{% block panel_footer %}
<div class="text-center">
<button type="submit" name="manager_options" value="Options">
Manager Options
</button>
</div>
{% endblock panel_footer %}
list.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block head %}
<script src="{% static "js/operations/enter_exit_area_manager_options_list.js" %}"></script>
{% endblock head %}
{% block main %}
{% include 'core/list_view/list.html' %}
{% endblock main %}
You option buttons is really link to another page so you should add it to your template like this. Replacing button-styles class with however you want your button to look.
<a href="{% url 'enter_exit_area_manager_options_list' %}" class="button-styles">
Manager Options
</a>
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