I got an error 405 as you can read, here is my code and my guess of what's wrong. The code is pretty basic, they are 3 files, main.py, blog.py, and form.html. As additional info: this code uses sessions, a subapp, and templates.
main.py --
import web
import blog
urls = (
"/blog", blog.app_blog,
"/(.*)", "index"
)
web.config.debug = False
app = web.application(urls, locals())
session = web.session.Session(app, web.session.DiskStore('sessions'))
render = web.template.render('views/', globals = {'session': session})
class index:
def GET(self, path):
session.names = ''
session.surnames = ''
session.nin = ''
session.address = ''
session.phone = ''
session.email = ''
return render.form()
if __name__ == "__main__":
app.run()
--
blog.py --
import web
urls = (
"", "reblog",
"/", "blog"
)
class reblog:
def GET(self): raise web.seeother('/')
class blog:
def GET(self):
return "getblog"
def POST(self):
return "postblog"
app_blog = web.application(urls, locals())
-- form.html--
<form method=post action=blog>
<ul>
<li><input name=names required maxlength=24 placeholder="Name" value="$session.names"></li>
<li><input name=surnames required maxlength=24 placeholder="Surname" value="$session.surnames"></li>
<li><input name=nin requiered maxlength=12 placeholder="RUT" value="$session.nin"></li>
<li><input name=address required maxlenght=64 placeholder="Address" value="$session.address"></li>
<li><input name=phone required maxlength=10 placeholder="Phone" value=$session.phone></li>
<li><input name=email type=email required maxlenght=254 placeholder="email" value=$session.email></li>
<li><input name=password type=password required placeholder="password"></li>
<li><input name=confirmpassword type=password required placeholder="Confirmar pass"></li>
<li><input type=submit value="registrarse"></li>
</ul>
The thing is that the user inputs are not use by the POST, rather it gives me an error 405 exactly like this:
"HTTP/1.1 POST /blog" - 405 Method Not Allowed
and the browser prints None.
Please give me a hand guys, this is pretty frustrating, if you know what I mean.
Thanks beforehand.
Cheers.
It happens because /blog url is mapped to class reblog that doesn't have POST method defined.
Related
I am developing an app in Django.
My users are allowed to save data by compiling a form like this
Tool:
acronym:
definition:
defined by the following function, in forms.py:
class tool_form(forms.ModelForm):
class Meta:
model=tool
fields=["Tool", "Acronym", "Definition"]
That saves the data into a model like this:
class tool(models.Model):
Tool = models.CharField(max_length=256, blank=True, null=True)
Acronym = models.CharField(max_length=25, blank=True, null=True)
Definition = models.TextField(blank=True, null=True)
The view function allowing this, is:
def add_tool(request):
if request.method=='POST':
form = tool_form(request.POST or None)
if form.is_valid():
form.save()
messages.success(request, ("Submit succeed!"))
return redirect('adding_tools')
else:
messages.error(request, ('ERROR: submit failed'))
return render(request, 'adding_tools.html', {})
else:
return render(request, 'adding_tools.html', {})
Now I want my users to be able to copile many times of the same form, all at once.
In order to achieve this, I am allowing my users to upload a file copiled with the data to insert.
So I am allowing my users to download a template xlsx file with colums with given name
Column 1 name (cell A1): Tool
Column 2 name (cell B1): acronym
Column 3 name (cell C1): definition
To compile it, inserting many records, and then to upload it back.
So I want my code to save this data into the same model declared before (tool)
I am trying to achieve this by:
in template add_tool_sheet.html:
<form class="container" method="POST" enctype="multipart/form-data" >
{% csrf_token %}
<div class="file-upload-wrapper" id="input-file-now">
<small id="inputHelp" class="form-text text-muted">Select file to upload.</small>
<input type="file" name="uploaded_file" id="input-file-now" data-max-file-size="5M" class="file-upload">
<br><br>
<div class="form-group">
<input name="Date" type="hidden" class="form-control" id="date_to_turn_into_toda">
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
in forms.py:
class tool_file_form(forms.ModelForm):
class Meta:
model=tool_file
fields=["Tool_file", "Date"]
In models.py
class tool_file(models.Model):
Tool_file = models.FileField(upload_to='uploaded_sheets/', blank=False, null=False)
Date = models.DateField(blank=False, null=False, default=timezone.now().date() )
class Meta:
ordering = ['Date', 'Tool_file']
def clean(self):
if not (self.Tool_file or self.Date):
raise ValidationError("something went wrong")
def __str__(self):
return "%s ----- [%s]" % (self.Tool_file, self.Date)
in views.py:
def add_tool_sheet(request):
if request.method=='POST':
form = tool_file_form(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, ("upload succeeded"))
return redirect('add_tool_sheet')
else:
messages.error(request, ('ERROR n1'))
return render(request, 'add_tool_sheet.html', {})
else:
return render(request, 'add_tool_sheet.html', {})
When I try to add new objects in the model tool_file from admin section, it works.
But when I try to add new objects from the user interface (template add_tool_sheet.html), it returns
ERROR n1
as message, and my console returns
GET /admin/ HTTP/1.1" 200 7381
Why?
Please note:
The upload from admin section works, the upload from user interface does not.
SOLVED
In template I put
name="uploaded_file"
but in order to match with the information in forms.py and model.py, it has to be:
name="Tool_file"
Now it works!
hello I'm in the process of converting my HTTP website to https but after getting https to work no post request from forms work
I have looked around a lot but nothing really describes what I have going on here, I doubt it nginx because when I start burp suite and make the website server HTTP it sends a post request like usual, but when I run it on https the post request isn't even sent doesn't show anything on the burp suite logs
<form action="" method="post" autocomplete="off">
<p><input type="text" name=username id="username">:username
<p><input type="password" name=password id="password">:password
<p><input type="checkbox" name = "rmbm" id="rmbm">
<label for = "rmbm">remember me</label>
<p><input type=submit value=Login>
forgot password?
</form>
this is my form but I don't even see a post request
I should see a post request but I don't on burp sute
update:
hello, I've just had an epiphany. could it be the service worker and yes I was right after unregistering the service worker it worked perfectly so the problem is the service worker.
knowing this I will post the code
my service worker:
console.log('Hello from sw.js');
'use strict';
var cacheVersion = 1;
var currentCache = {
offline: 'offline-cache' + cacheVersion
};
this.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCache.offline).then(function(cache) {
return cache.addAll([
'/static/html/offline.html',
'/sw.js'
]);
})
);
});
this.addEventListener('fetch', event => {
console.log("fetching");
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match('/static/html/offline.html');
})
);
}
else{
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});
now looking at my code it just dosnt handle post request
so i will try to fix this on my own
I have forms to Post Article in my blog Django2. When I run django server there is no error, but when I Post and submit Article in my frontEnd apps nothing happens and doesn't save any data.
Any help on this would be highly appreciated!
Template HTML
<div class="create-article">
<h2>Create an Awesome New Articles</h2>
<form class="site-form" action="{% url 'articles:create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create">
</form>
</div>
forms.py
from django import forms
from . import models
class CreateArticle(forms.ModelForm):
class Meta:
model = models.Article
fields = ['title', 'body', 'slug', 'thumb']
views.py
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
# save article to db
instance = form.save(commit=False)
instance.author = request.user
instance.save
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', {'form': form})
urls.py
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name="list"),
path('create/', views.article_create, name="create"),
path('<slug>/', views.article_detail, name="detail"),
]
Thanks.
It starts here: instance = form.save(commit=False), where you are not commiting the save.
Further down you have instance.save as if you were setting a model field, but with not value given to it.
Make that line instance.save() instead.
Image with error <--- when I use function update, I want to redirect to BooksController.index() but when i try it I have an error: object java.lang.ProcessBuilder.Redirect is not a value. Can somebody help?
BooksController:
val bookForm = Form(
tuple(
"id" -> number,
"title" -> text,
"price" -> number,
"author" -> text
)
)
def edit(Id: Int) = Action {
val book: Book = Book.findById(Id)
Ok(views.html.edit())
}
def update(Id: Int) = Action {
implicit request =>
val (id, title, price, author) = bookForm.bindFromRequest.get
val book: Book = Book.findById(id)
book.id = id
book.title = title
book.price = price
book.author = author
Redirect(routes.BooksController.index())
}
My edit view:
<html>
<head>
<title>Form example</title>
</head>
<body>
<form method="post" autocomplete="on">
Id: <input type="text" name="id"><br><br>
Title: <input type="text" name="title"><br><br>
Price:<input type="text" name="price"><br><br>
Author: <input type="text" name="author"><br><br>
<input type="submit">
</form>
</body>
</html>
Routes:
GET /books controllers.BooksController.index
GET /books/create controllers.BooksController.create
GET /books/:id controllers.BooksController.show(id: Int)
POST /books/create controllers.BooksController.save
GET /books/edit/:id controllers.BooksController.edit(id: Int)
POST /books/edit controllers.BooksController.update
Error:
play.sbt.PlayExceptions$CompilationException: Compilation error[object java.lang.ProcessBuilder.Redirect is not a value]
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:34)
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:34)
at scala.Option.map(Option.scala:146)
at play.sbt.run.PlayReload$.$anonfun$taskFailureHandler$1(PlayReload.scala:33)
at scala.Option.map(Option.scala:146)
at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:28)
at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:24)
at play.sbt.run.PlayReload$.$anonfun$compile$3(PlayReload.scala:51)
at scala.util.Either$LeftProjection.map(Either.scala:573)
at play.sbt.run.PlayReload$.compile(PlayReload.scala:51)
Lets look at the Redirect definition:
/**
* Generates a redirect simple result.
*
* #param url the URL to redirect to
* #param status HTTP status
*/
def Redirect(url: String, status: Int): Result = Redirect(url, Map.empty, status)
So your Redirect should be:
Redirect("/books")
Update
Ok, after you added the error, you error seems to be because of bookForm.bindFromRequest.get. So, if you look at the form in your html and your defined form:
id needs to be an input of type number and not text, as well as the price.
Ok, so my friend resolve the problem. My mistake was in routes. I forgot to add id:
POST /books/edit/:id controllers.BooksController.update(id: Int)
I am trying to implement filter_by() function of flask. My issue is, when I am trying to use filter for argument, I got the error of:
TypeError: filter_by() takes 1 positional argument but 2 were given
I also attached my code to the question.
Main application source code:
def login():
error = None
form = LoginForm(request.form)
if request.method == 'POST':
user = User.query.filter_by(Email=request.form['email']).first()
password = User.query.filter_by(Password=request.form['password']).first()
group = User.query.filter_by(user).first()
if user is None or password is None :
session['logged_in'] = False
flash('Please write your username password')
else:
session['logged_in'] = True
flash('You were logged in')
if group=="viewer":
return redirect(url_for('viewer'))
elif group=="admin":
return redirect(url_for('admin'))
elif group=="employee":
return redirect(url_for('employee'))
return render_template('login.html', form=form)
The model which I used for my app :
class User(db.Model):
__tablename__ = 'users'
Id = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.String(64), index=True, unique=True)
Email = db.Column(db.String(64), index=True, unique=True)
Password = db.Column(db.String(128), index=True )
Group = db.Column(db.String(30))
Tickets = db.relationship('Request', backref='author', lazy='dynamic')
Login page source code:
<div class="innter-form">
<form class="sa-innate-form" method="post">
{{ form.csrf_token }}
<label>Email Address</label>
<input type="text" name="email" value="{{ request.form.email }}">
<label>Password</label>
<input type="password" name="password" value="{{ request.form.password }}">
<button type="submit" value="submit">Sign In</button>
Forgot Password?
</form>
</div>
filter_by is used for queries on the column names
...
# this returns a user object
user = User.query.filter_by(Email=request.form['email']).first()
# you should query based on the Id of User
group = User.query.filter_by(Id=user.Id).first()
Probably the problem is in the line
group = User.query.filter_by(user).first()
Besides the fact that filter_by accepts only keyword arguments - and you supplied only one positional argument to it, I am guessing you should use something different than User here (maybe Group, not sure since I don't know what models you have defined).
The line I mentioned should look something like
group = Group.query.filter_by(user=user).first()
Thank you all for response:
The eror was in group part as mention in above:
group = User.query.filter_by(user).first()
Instead of this code should be:
group = User.query.filter_by(Email=user).first()