I create form on django project. I have a error csrf failed.
My wievs.py file:
def durum(request):
if request.method == "POST":
adi = request.POST.get('durum')
db = sql.connect("/usr/connect.db")
im = db.cursor()
db.execute("INSERT INTO durum VALUES ("+str(adi)+")")
db.commit()
asd = "Durum mesajı '"+str(adi)+"' olarak değiştirildi."
return render(request, asd, {})
else:
BASE = os.path.dirname(os.path.abspath(__file__))
return HttpResponse(open(os.path.join(BASE, "html/durum.html")).read())
My urls.py file:
url(r'^durum/', db.durum),
My html file:
<form action="/durum" method="post">
{% csrf_token %}
<table>
<tr><th>Durum Mesajı:</th><td><input type="text" name="durum"/></td></tr>
<tr><th></th><td><input type="submit" value="Ekle"/></td></tr>
</table>
You should follow the "django-way" to render your template. The way your view works is sending the template as plain html instead of proccessing it.
Try it this way:
def durum(request):
if request.method == "POST":
adi = request.POST.get('durum')
db = sql.connect("/usr/connect.db")
im = db.cursor()
db.execute("INSERT INTO durum VALUES ("+str(adi)+")")
db.commit()
asd = "Durum mesajı '"+str(adi)+"' olarak değiştirildi."
return render(request, asd, {})
else:
return render('your_template_name.html', context_instance=RequestContext(request))
This way, django will proccess your template and render a correct csrf_token. I strongly suggest you follow the tutorial on djangoproject.com and make use of the ORM as well
You should use django templates and RequestContext.
The very fast way to check it:
in your app folder create following directory structure:
1.templates/myapp_name
Use name of the app, not project name!
Create file my_template.html
in your view add import:
from django.shortcuts import render
add replace your return with
return render('myapp_name/my_template.html')
Read more about configure template directory:
Django template Path
Read more about render:
https://docs.djangoproject.com/en/1.7/intro/tutorial03/#a-shortcut-render
Note:
It's better to use django forms instead of your way:
https://docs.djangoproject.com/en/1.7/topics/forms/
and class based views instead of functions(they may looks complicated by believe me - they are really awesome:
https://docs.djangoproject.com/en/1.7/topics/class-based-views/
Also try do not use hardcoded urls, use https://docs.djangoproject.com/en/1.7/topics/http/urls/#reverse-resolution-of-urls instead
It will done all work for you!
Related
I want to display a picture with Django, which is already saved on a mysql database. In all Methods I found people used models.Imagefield(upload_to='path'), but I think this will save the file into this directory and people from other computers won´t have access later.
So the question is, how do I access the database directly and display the picture without saving it in between?
I already managed to do this in python, but I am not quite sure how to implement the code into the models.py.
Something like this was my approach :
class mysqlpicture(models.Model):
#mysqlpic=something?
def openpic():
connection = pymysql.connect(user='root', passwd='***',
host='localhost',
database='db')
cursor = connection.cursor()
sql1='select * from Pictures'
cursor.execute(sql1)
data=cursor.fetchall()
mysqlpic=io.BytesIO(data[1][0])#one means second element of column zero
#img=Image.open(mysqlpic)
#img.show()
cursor.close()
return mysqlpic
and then I tried in the views.py to give mysqlpicdirectly to the httpresponse like this:
def MysqlView(request):
query_results = mysqlpicture.objects.all()
template = loader.get_template('polls/pic.html')
context = {
'query_results': query_results,
}
return HttpResponse(template.render(context, request))
using a template pic.htmlto insert a picture like:
{% for n in query_results %}
<mysqlpic src="{{ n.mysqlpic.url }}" />
{% endfor %}
Has someone an idea how to to this in the right way?
Yes, using ImageField does allow people from other computers to access it later. It inherits all attributes and methods from FileField which uploads the file into the server in the path specified in upload_to and also saves this path into your database to keep its reference. All of that happens when you call the save() method in your model instance.
Then, you can create the url to build a link by calling your_instance.image_field.url in your template. Also remember to have a look at MEDIA_ROOT and MEDIA_URL which respectively tells Django the server root path for saving your files and the url that handles the media served from MEDIA_ROOT.
You can use BinaryField for this purposes.
But as stated in the django documentation:
Although you might think about storing files in the database, consider that it is bad design in 99% of the cases.
from django.db import models
class MysqlPicture(models.Model):
mysqlpic = models.BinaryField()
# ...
And then to display in the template you can convert binary data to base64:
from base64 import b64encode
def mysql_view(request):
query_results = MysqlPicture.objects.all()
template = loader.get_template('polls/pic.html')
context = {
'images': [b64encode(obj.mysqlpic) for obj in query_results],
}
return HttpResponse(template.render(context, request))
Template:
{% for image in images %}
<img src="data:;base64,{{ image }}">
{% endfor %}
I know this question was asked before, but none worked for me. I have this code that I want it to be executed when a button is clicked and a message is passed
import time
from sinchsms import SinchSMS
number = '+yourmobilenumber'
message = 'I love SMS!'
client = SinchSMS(your_app_key, your_app_secret)
print("Sending '%s' to %s" % (message, number))
response = client.send_message(number, message)
message_id = response['messageId']
response = client.check_status(message_id)
while response['status'] != 'Successful':
print(response['status'])
time.sleep(1)
response = client.check_status(message_id)
print(response['status'])
Basically, what I need is to add an input in a template "HTML File", this input get passed to the message variable in the code above, same with the number. I can easily do that with instances, but how can the below get executed when a button is clicked from the form in the template?
I'm kinda newbie in Django and still finding my way
Here is the tutorial that explains how to make the python file, but execute it from the shell, not a django application.
I hope I was clear describing my problem and any help would be appreciated!
All you need is a form with a message field. In a view, you want to show that form and when the user press submit, you want to execute your script.
Here is some pseudo-code:
urls.py
url('^my-page/' my_views.my_view, name='my-page'),
forms.py
SmsForm(forms.Form):
message = fields.CharField(...)
my_views.py
def my_view(request):
form = SmsForm(data=request.POST or None)
if request.method == 'POST':
if form.is_valid():
send_sms(form.cleaned_data['message']) # do this last
messages.success(request, "Success")
return HttpResponseRedirect(request.path)
else:
messages.warning(request, "Failure")
return render(request, 'my_template.html', {'form': form})
Check the Django documentation about urls, views, forms and messages and proceed step by step:
get the page to load
get the form to load
get the form submission to work and simply show "Success" or "Failure"
finally, write the send_sms function (you've almost done it)
Lets start from the dust cloud.
What you are asking is mostly about how the web pages work. You need to know how to pass parameters using HTML. There are lots of ways to do it. But with django there is a pattern.
You need a url, and a view to catch any requests. Then you need to create a template and a form inside it. With this form you could create some requests to send data to your view.
To create you need to edit urls.py inside your project add an url:
urls.py
from django.conf.urls import url
from my_app.views import my_view
urlpatterns = [
...
url(r'^my_url$', my_view, name='my_view')
...
]
For more about urls please look at URL dispatcher page at documentation.
Then create your view inside your app which is my_app in my example. Edit my_app/views.py
my_app/views.py
from django.http import HttpResponse
def my_view(request):
return HttpResponse('IT WORKS!')
This way you get a working view which could be accessed with path /my_url. If you run ./manage.py runserver you could access your view from http://localhost:8000/my_url.
To create a form you need to create a template. By default django searches app directories for templates. Create a templates directory in your app, in our case my_app/templates and create an HTML file inside. For example my_app/templates/my_form.html. But i advice to create one more directory inside templates directory. my_app/templates/my_app/my_form.html. This will prevent template conflicts. You can check Templates page at documentation for more.
my_app/templates/my_app/my_form.html
<html>
<body>
<form action="/my_url" method="POST">
{% csrf_token %}
<input type="text" name="number">
<input type="text" name="message">
<input type="submit" value="Run My Code">
</form>
</body>
</html>
This is the one of the ways of creating your form. But I do not recommend it. I will make it prettier. But first lets "Make it work", edit your views.py:
csrf_token is a django builtin template tag, to put CSRF token into your form. By default django requires CSRF tokens at every post
request.
my_app/views.py
from django.http import HttpResponse
from django.shortcuts import render
def my_view(request):
if request.method == 'GET':
return render('my_app/my_form.html')
elif request.method == 'POST':
# get post parameters or None as default value
number = request.POST.get('number', None)
message = request.POST.get('message', None)
# check if parameters are None or not
if number is None or message is None:
return HttpResponse('Number and Message should be passed')
# your code goes here
...
return HttpResponse('Your code result')
Till this point the purpose of this answer was "Making it work". Lets convert it nice and clean. First of all we would create Form. Forms are like models, which helps you create forms as objects. It also handles form validations. Forms are saved inside forms directory generally. Create my_app/forms.py and edit it:
my_app/forms.py
from django import forms
class MyForm(forms.Form):
number = forms.CharField(max_length=15, required=True)
message = forms.CharField(max_length=160, required=True)
Put your form inside your template:
my_app/templates/my_app/my_form.html
<html>
<body>
<form action="{% url 'my_view' %}" method="POST">
{% csrf_token %}
{{ form }}
</form>
</body>
</html>
Besides the form, the action of the HTML form tag is also changed.
url template tag is used to get url form url name specified in urls.py.
Instead of url tag, {{ request.path }} could have been used.
Create a form instance and pass it to the template rendering:
my_app/views.py
from django.http import HttpResponse
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == 'GET':
form = MyForm()
return render('my_app/my_form.html', {'form': form})
elif request.method == 'POST':
form = MyForm(request.POST)
# check if for is not valid
if not form.is_valid():
# return same template with the form
# form will show errors on it.
return render('my_app/my_form.html', {'form': form})
# your code goes here
...
return HttpResponse('Your code result')
You can use class based vies to write your view, but it's not necessary. I hope it helps.
You can create a view that takes up query parameters from the url and use it for further implementation. Then you can create a link/button in the html template which can redirect you to that url. For example:
in urls.py:
url(r'^run_a/(?P<msg>\w{0,25})/(?P<num>\w{0,25})/$', yourcode, name='get_msg'),
in template:
submit
in views.py:
def get_msg(request,msg,num):
message=msg
number=num
#rest of the code
Hope this helps :)
I want to show registered users/company name list to template in django. i am new in working with django forms.
I had registered successfully company by using template now i want to show all the company name which has been registered.
my models.py
class Company(models.Model):
company_id=models.IntegerField(default=0,primary_key=True)
company_name=models.CharField(max_length=255,blank=True,null=True)
company_email=models.EmailField(max_length=255,blank=True,null=True)
is_active=models.BooleanField(default=False)
last_login=models.DateTimeField(default=datetime.now,blank=True,null=True)
i am stuck that how can i show all information on template using forms. how can i make form for this and how can i get all companies name to show
I wrote this to get all companies name
def allcompanies(request):
context = RequestContext(request)
if request.method =='GET':
all_company=comoanyForm(request.GET)
data=Company.objects.all()
print "print all data",data
else:
pass
return render_to_response(
'allcompany.html',
{ },
context_instance=RequestContext(request))
i get values in data but did not showing on template.
You should not be using render_to_response - it is likely to be depreciated in the future.
You should be using render.
from django.shortcuts import render
return render(request, 'allcompany.html', {'data': data,})
then within your template you should have something like:
{% for company in data %}
{{company.company_name}}
{% endfor %}
You should do the django tutorial (or refer to it) if you haven't already, these are simple concepts.
I new to Python and Django, i am trying to create a user interface using django for the calculation of the speed (speed= distance/time). I have created a project using django in that i have created a weapp called speed. The below are my files
Webapp
speed
-Templates
-views.py
-forms.py
-urls.py
webapp
-settings.py
-urls.py
-init.py
-wsgi.py
My codes:
forms.py
from django import forms
class Calculatespeed(forms.Form):
distance=forms.CharField(
required=True,max_length=10,
widget=forms.TextInput(attrs={"placeholder":"0.0",
"style":"width:100px"}))
time=forms.CharField(
required=True,max_length=10,
widget=forms.TextInput(attrs={"placeholder":"0.0",
"style":"width:100px"}))
views.py
# Create your views here.
from django.shortcuts import render
from django import template
from speed.forms import Calculatespeed
def speed(Speed):
distance=float(raw_input("Please Give the disance"))
Time=float(raw_input("Please Give the Time"))
Speed=distance/Time
return Speed
def Main(request):
if request.GET:
form = speed_form.SpeedForm(request.GET)
if form.is_valid():
Distance = form.cleaned_data["distance"]
Time = form.cleaned_data["time"]
return shortcuts.render_response(
"speed.html",
page_context,
context_instance=template.RequestContext(request)
)
Templates:
<html>
<head>
<title>WebApp1</title>
</head>
<h1>Speed Calculator</h1>
<form action="/contact/" method="post">
<br>
Distance:
<input type="interger" distance="Distance" />
<br>
Time:
<input type="interger" Time="Time" />
<input type="submit" value="Submit" />
urls.py
from django.conf.urls import *
from speed.views import speed
urlpatterns = patterns('',
url(r'^$', speed),
)
The problem is when i am trying run server i am getting an error i am unable to get the user interface of speed can any one help me on this.
Is the templates files and all the other files which i gave are correct or not ??
Thanks in advance
There are a lot of things wrong with your code, so it seems to me like a very basic misunderstanding of working with django, and maybe with python in general. there are a lot of pythonic errors in your code (you have wrong indentation, you did a 'return' without a function, and so on), and a lot of django-ic errors too (you can't use raw_input in django it doesn't work that way, you created a form but then wrote the entire html yourself).
I suggest that before you write it in django, write this as a python program and see if it works. When you feel like you understand the language enough and want to web-app your program, go over the django docs and take some time to learn how it works.
You're using raw_input in your view to ask data wanted. I think you didn't understand what a web app is :-) (Or the speed function is just for tests, so in that case it would be placed in the tests.py of the application)
In your view main(request), you should init a form and if a request POST (can be check with request.method) is sent, check if the form is valid.
Here some code which might working (I replace the render_to_response by render to not confusing you with the context that you misused)
from django.shortcuts import render
def speed(distance, time_): # don't like to name a var time because of the module with the same name...
return distance/ time_
def compute_speed(request):
if request.method == 'POST':
form = Calculatespeed(request.POST)
if form.is_valid():
distance = form.cleaned_data["distance"]
time_ = form.cleaned_data["time"]
speed = speed(distance, time_)
# Do your stuff here
else:
form = Calculatespeed()
return render(request, "speed.html", {'form': form})
And in the urls.py:
urlpatterns = patterns('',
url(r'^$', compute_speed, name="compute_speed"),
)
You have also some typos in your HTML:
The inte r ger input type doesn't exists
Why action="/contact/" instead of {% url 'compute_speed' %} ?
Your form isn't closed
I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows:
def email_selected(self,request,queryset):
rep_list = []
for each in queryset:
reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.name))
contact_reps = reps.filter(is_contact=True)
for rep in contact_reps:
rep_list.append(rep)
return email_form(request,queryset,rep_list)
email_form exists as a view and fills a template with this code:
def email_form(request,queryset,rep_list):
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('email','noreply#localboast'),['redacted#email.com'],
)
return HttpResponseRedirect('thanks')
else:
form = EmailForm()
return render_to_response('corpware/admin/email-form.html',{'form':form,})
and the template exists as follows:
<body>
<form action="/process_mail/" method="post">
<table>
{{ form.as_table }}
</table>
<input type = "submit" value = "Submit">
</form>
</body>
/process_mail/ is hardlinked to another view in urls.py - which is a problem. I'd really like it so that I don't have to use <form action="/process_mail/" method="post"> but unfortunately I can't seem to POST the user inputs to the view handler without the admin interface for the model being reloaded in it's place (When I hit the submit button with , the administration interface appears, which I don't want.)
Is there a way that I could make the form POST to itself (<form action="" method="post">) so that I can handle inputs received in email_form? Trying to handle inputs with extraneous URLs and unneeded functions bothers me, as I'm hardcoding URLs to work with the code.
You can use django's inbuilt url tag to avoid hardcoding links. see...
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url
Chances are you'd be better off setting up a mass mailer to be triggered off by a cron job rather than on the post.
Check out the answer I posted here
Django scheduled jobs
Also if you insist on triggering the email_send function on a view update perhaps look at
http://docs.djangoproject.com/en/dev/topics/signals/