django+uploadify - don't working - django

I'm trying to use an example posted on the "github" the link is http://github.com/tstone/django-uploadify. And I'm having trouble getting work. can you help me? I followed step by step, but does not work.
Accessing the "URL" / upload /
the only thing is that returns "True"
part of settings.py
import os
PROJECT_ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media')
TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT_PATH, 'templates'))
urls.py
from django.conf.urls.defaults import *
from django.conf import settings
from teste.uploadify.views import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
url(r'upload/$', upload, name='uploadify_upload'),
)
views.py
from django.http import HttpResponse
import django.dispatch
upload_received = django.dispatch.Signal(providing_args=['data'])
def upload(request, *args, **kwargs):
if request.method == 'POST':
if request.FILES:
upload_received.send(sender='uploadify', data=request.FILES['Filedata'])
return HttpResponse('True')
models.py
from django.db import models
def upload_received_handler(sender, data, **kwargs):
if file:
new_media = Media.objects.create(
file = data,
new_upload = True,
)
new_media.save()
upload_received.connect(upload_received_handler, dispatch_uid='uploadify.media.upload_received')
class Media(models.Model):
file = models.FileField(upload_to='images/upload/', null=True, blank=True)
new_upload = models.BooleanField()
uploadify_tags.py
from django import template
from teste import settings
register = template.Library()
#register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True)
def multi_file_upload(context, upload_complete_url):
"""
* filesUploaded - The total number of files uploaded
* errors - The total number of errors while uploading
* allBytesLoaded - The total number of bytes uploaded
* speed - The average speed of all uploaded files
"""
return {
'upload_complete_url' : upload_complete_url,
'uploadify_path' : settings.UPLOADIFY_PATH, # checar essa linha
'upload_path' : settings.UPLOADIFY_UPLOAD_PATH,
}
template - uploadify/multi_file_upload.html
{% load uploadify_tags }{ multi_file_upload '/media/images/upload/' %}
<script type="text/javascript" src="{{ MEDIA_URL }}js/swfobject.js"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.uploadify.js"></script>
<div id="uploadify" class="multi-file-upload"><input id="fileInput" name="fileInput" type="file" /></div>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('#fileInput').uploadify({
'uploader' : '/media/swf/uploadify.swf',
'script' : '{% url uploadify_upload %}',
'cancelImg' : '/media/images/uploadify-remove.png/',
'auto' : true,
'folder' : '/media/images/upload/',
'multi' : true,
'onAllComplete' : allComplete
});
});
function allComplete(event, data) {
$('#uploadify').load('{{ upload_complete_url }}', {
'filesUploaded' : data.filesUploaded,
'errorCount' : data.errors,
'allBytesLoaded' : data.allBytesLoaded,
'speed' : data.speed
});
// raise custom event
$('#uploadify') .trigger('allUploadsComplete', data);
}
// ]]</script>

But that's exactly what you've told it to do - if you're not POSTing, then the /upload/ view will simply return True.
I would imagine you want to return an actual rendered template, presumably containing the {% multi_file_upload %} tag.

You may find the following site useful:
https://github.com/tstone/django-uploadify/wiki

line 1 on your template, your tags aren't properly closed/open
should be
{% load uploadify_tags %}{% multi_file_upload '/myphotos/my-photos/'%}
with that said, i am getting all sorts of errors my self... mainly with the csrf verification. i see that tstone is exempting csrf but it still thinks it should be there... and it isn't. so according to django's docs https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax i added the stuff to make it so csrf should be working. but now i get a 405 because it is trying to post to its self. i'll keep digging and hopefully find a solution.

Related

How can I print the url to the order id field of my django form?

I am doing a simple form site with Django. This is what my sites url is looks like: mysite.com/register/12345678
I want to print the part after the register (12345678) to the order id field. When someone goes this mysite.com/register/87654321 url then i want to print it.
How can i do that? These are my codes.(Currently using Django 1.11.10)
forms.py
from django import forms
from .models import Customer
from . import views
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = (
'order_id','full_name','company','email',
'phone_number','note')
widgets = {
'order_id': forms.TextInput(attrs={'class':'orderidcls'}),
'full_name': forms.TextInput(attrs={'class':'fullnamecls'}),
'company': forms.TextInput(attrs={'class':'companycls'}),
'email': forms.TextInput(attrs={'class':'emailcls'}),
'phone_number': forms.TextInput(attrs={'class':'pncls'}),
'note': forms.Textarea(attrs={'class':'notecls'}),
}
views.py
from django.shortcuts import render
from olvapp.models import Customer
from olvapp.forms import CustomerForm
from django.views.generic import CreateView,TemplateView
def guaform(request,pk):
form = CustomerForm()
if request.method == "POST":
form = CustomerForm(request.POST)
if form.is_valid():
form.save(commit=True)
else:
print('ERROR FORM INVALID')
theurl = request.get_full_path()
orderid = theurl[10:]
return render(request,'forms.py',{'form':form,'orderid':orderid})
customer_form.html
{% extends 'base.html' %}
{% block content %}
<h1>REGÄ°STRATÄ°ON</h1>
<form class="registclass" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-default">REGISTER</button>
</form>
{% endblock %}
urls.py
from django.conf.urls import url
from django.contrib import admin
from olvapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^thanks/$',views.ThankView.as_view(),name='thank'),
url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'),
]
You have passed the value to your view as 'pk' so you can use that to set the the initial value:
views.py
form = CustomerForm(initial={'order_id': pk})
SamSparx is right, here's some additional information to help prevent such errors in advance:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^thanks/$',views.ThankView.as_view(),name='thank'),
url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'),
]
You are using regex to parse your path. Regex is generally speaking not recommended in this case according to the docs because it might introduce more errors and is harder to debug. (Unoptimized) RegEx also tends to be slower.
For simple use cases such as your path here, consider choosing the default pathing syntax as below:
urlpatterns = [
url('admin/', admin.site.urls),
url('thanks/',views.ThankView.as_view(),name='thank'),
url('register/<int:pk>',views.guaform,name='custform'),
]
You could of course also use string instead of int depending on your usage of pk.
Your paths do not all end with a slash consistently. This might impact your SEO and confuse users. See this and this.
Also your form is not imported .as_view() for some reason which could cause some problems.

can not render ' / ' in url in Django templates

Update :: Problem solved.just follow the guy below.
in my urls.py
path('', store_view, name='store'),
path('category/<str:category_name>/', category_view, name='category'),
in views.py
def store_view(request):
categories = list(Category.objects.all())
context = {
'categories': categories,
}
return render(request, 'store/store.html', context)
def category_view(request, category_name):
category = Category.objects.get(name=category_name)
context = {
'category': category,
}
return render(request, 'store/single-category-view.html', context)
in my template : store.html , that is rendered by store_view >>
{% for item in categories %}
<a href="{% url 'category' item.name %}">
{{item.name}}
</a>
{% endfor %}
Now,the problem is, in the category column in my DB, i have got one category called 'Laptop/MacBook'.when ever this name is passed to the url, it says >>
"Reverse for 'category' with arguments '('Laptop/MacBook',)' not
found. 1 pattern(s) tried: ['category/(?P<category_name>[^/]+)/$']
But when i changed the category name from Laptop/MacBook to Laptop and MacBook , it worked fine and showed no error.
But i want to keep it as it was,'Laptop/MacBook'.How can i do that??and how do you guys deal with that?
Try encoding and decoding your DB values. Assuming its Python 3:
from urllib.parse import quote, unquote
encoded = quote("Laptop/Macbook", safe="")
decoded = unquote(encoded)
print(encoded, decoded)
Output:
Laptop%2FMacbook Laptop/Macbook
With this your route should take in the right param.
from django.http import HttpResponse, request
from django.shortcuts import render
def store_view(request):
name = "Laptop/Macbook"
return render(request, './store.html', context={"name": name})
def category_view(request, category_name):
print(category_name)
return HttpResponse(b"Here we go!")
templatetags/tags.py
from urllib.parse import quote, unquote
from django import template
register = template.Library()
#register.filter(name='encode')
def encode(name):
return quote(name, safe="")
#register.filter(name='decode')
def decode(name):
return unquote(name)
Template:
{% load tags %}
<a href="{% url 'category' name|encode %}">
{{name}}
</a>
Don't forget to add in settings:
'OPTIONS': {
'libraries':{
'tags': 'templatetags.tags',
}
},
When using a "/", django thinks that you are passing more than one parameter. To fix this, replace str by path in your urls like so:
path('', store_view, name='store'),
path('category/<path:category_name>/', category_view, name='category'),
This will make django understand that the / does not mean there are two separate parameters in your url.

Type Error Django 3.0.4 : Typer Error while Runserver

I am learning Django from clever programmer and have run into an issue.
I am trying to **./manage.py runserver and I run into a type error issue as provided on the below link
i assume there seems to be a problem on the line: return render(request, 'movies/movies_stuff.html' , stuff_for_frontend)
TypeError - Screen Shot
views.py_
from django.shortcuts import render
from .models import movies
# Create your views here.
def Home_page(request):
user_query = str(request.GET.get('query' , ''))
search_result = movies.objects.filter(name__icontains=user_query)
stuff_for_frontend={'Search_result :', search_result}
return render(request, 'movies/movies_stuff.html' , stuff_for_frontend)
urls.py
from django.urls import include, path
from .views import Home_page
urlpatterns= [
path('', Home_page, name='Home _page')
]
Templates-->movies-->movies_stuff.html
<html>
<body>
<form action = "" name="search"
<input type= "text" name="query" value="{{request.GET.query}}"
<input type = "submit" value="Search" />
{%for movies in search_result%}
<p>{{movies.name}}</p>
{% endfor %}
</body>
</html>
The issue here is as it states, it's a type error. This is happening because the render method requires a dictionary and you are sending a set instead.Correct the following
stuff_for_frontend={'Search_result :', search_result} // this will become a set
to this
stuff_for_frontend={'Search_result' : search_result} // now a dictionary
The error occurs when try to access using keys on set. And in the template try to correct the form as I suspect it is incomplete.
Hope that helps! Happy coding!

Input from template to a view in Django

As you can tell, i'm new to Django, but already love it. I have a functional scraping server that scrapes 7 selects from a diagnostics page on one server. All environments I want to use this will have many of these servers with the same data to monitor performance. I would like to use this function to scrape this data from all entered target servers by input from the html template. Adding each server to monitor that will show up below the input text field from the main html page. I have completed this with a static url, but have been unsuccessful passing the different urls to scrape from the html template to the views url variable I have for the static address.
I've attempted to create forms and pass that to the html template without success, including editing the views file. Reverted the code back to the original working code to not cause more confusion.
html template:
<form method="POST">
{% csrf_token %}
<div class="field has-addons">
<div class="control is-expanded">
<input type="text" class="input"
placeholder="Relay Name">
</div>
<div class="control">
<button type="submit" class="button is-info">
Add Relay
</button>
</div>
</div>
</form>
Views.py:
import requests, bs4
from django.shortcuts import render
from django.http import HttpResponse
from bs4 import BeautifulSoup
from urllib.request import urlopen
from .models import Relay
def index(request):
url = 'hardcoded server url'
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
relay = 'Relay'
dic = requests.get(url.format(relay))
elema = soup.select('body > div:nth-child(13) > div.forminput')
elem1 = elema[0].text.strip()
elemb = soup.select('body > div:nth-child(14) > div.forminput')
elem2 = elemb[0].text.strip()
elemc = soup.select('body > div:nth-child(15) > div.forminput')
elem3 = elemc[0].text.strip()
elemd = soup.select('body > div:nth-child(16) > div.forminput')
elem4 = elemd[0].text.strip()
eleme = soup.select('body > div:nth-child(17) > div.forminput')
elem5 = eleme[0].text.strip()
elemf = soup.select('body > div:nth-child(18) > div.forminput')
elem6 = elemf[0].text.strip()
elemg = soup.select('body > div.versioninfo')
elem7 = elemg[0].text.strip()
#creating dictionary object
dic = {}
dic['relay'] = relay
dic['FFSL'] = elem1
dic['FFCL'] = elem2
dic['FBFQFSL'] = elem3
dic['FBQFCL'] = elem4
dic['TQQ'] = elem5
dic['SQQ'] = elem6
dic['RV'] = elem7
print(dic)
context = {'dic' : dic}
return render(request, 'relchchk/relchck.html', context)
forms.py:
from django import forms
from django.forms import ModelForm, TextInput
from .models import Relay
class RelayForm(ModelForm):
class Meta:
model = Relay
fields = ['Name', 'Relay Version', ]
widgets = {'name' : TextInput(attrs={'class' : 'input',
'placeholder' : 'url'})}
models.py:
from django.db import models
class Relay(models.Model):
name = models.CharField(max_length=45)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Relays'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
]
The desired result would be to manually enter any of the target servers that could accumulate to all and save in database that exists (but not important now) and have the main page show all selected. I was moving along pretty well and thought this should be simple step and probably is, but I must be missing something. Any guidance would be much appreciated.
You haven't created an instance of your form. In your views.py file, it should look something like this.
if request.method="POST":
#code to handle the form
else:
form = RelayForm()
context = {
"form": form
}
You render the form like this:
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
</form>
Read the docs to learn more about form handling and rendering.

Using wkhtmltopdf with dynamic templates

I want to generate a PDf of a django template / view; that uses templatetags etc.
From django-wkhtmltopdf's documentation:
from django.conf.urls.defaults import url, patterns
from wkhtmltopdf.views import PDFTemplateView
urlpatterns = patterns('',
url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
filename='my_pdf.pdf'), name='pdf'),
)
Or they say in your own view:
from wkhtmltopdf.views import PDFTemplateView
class MyPDF(PDFTemplateView):
filename = 'my_pdf.pdf'
template_name = 'my_template.html'
cmd_options = {
'margin-top': 3,
}
If this was my view:
def download_report(request):
vends = Vends.objects.all()
return render(request, 'report_template.html', {'vends':vends})
How would I generate a report of this VIEW as its rendered? Not just the template, because that would be useless?
You can use PDFTemplateRespone instead of render_to_response.
from wkhtmltopdf.views import PDFTemplateResponse
Then you can do something like this:
def pdf(request, pk):
context = RequestContext(request)
template = 'test.html'
context = {
'variable1': variable1,
'variable1': variable1,
'variable1': variable1,
'variable1': variable1
}
return PDFTemplateResponse(request=request, cmd_options={'disable-javascript':True}, template=template, context=context)
It looks like I'm 3 years late :) I put here a working code sample anyway, as reference for future needs:
urls.py
# here you must import MyPDF from [your-app-name].views
urlpatterns = [
url(r'^pdf/$', MyPDF.as_view(template_name='my_template.html',
filename='my_pdf.pdf'), name='pdf'),
]
views.py
from wkhtmltopdf.views import PDFTemplateView
class MyPDF(PDFTemplateView):
def get_context_data(self, **kwargs):
context = super(MyPDF, self).get_context_data(**kwargs)
context['foo'] = 'BAR'
return context
my_template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>{{ foo }}</h1>
</body>
</html>
Having the same problem as yours, got everything working with rendering propetly CSS + JS but i'm also unable / don't know how to render or pass the data to get template rendered and then converted.
If someone could give a hint or point in a good direction, it would be awesome.