"TypeError: filter_by()" error returned in flask when I am trying to use filter_by() - forms

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()

Related

Laravel validation of datetime using old()

I have an edit form I need verified with several datetime inputs.
Here is an example of one of the inputs. Can old() be used this way?
<input
type="text"
name="call_timeRecd"
id="call_timeRecd"
class="form-control
form-control-sm"
value="{{ $data->call_timeRecd ? date('Y-m-d H:i', (new DateTime( old($data->call_timeRecd, $data->call_timeRecd) ))->getTimestamp()) : '' }}" />
I'm trying to have invalid inputs return to the form with an error and the invalid input displayed in the input box. However, it is showing the original input rather than the incorrect version when it returns with the error.
$data is a MySql record and call_timeRecd is a timestamp field.

django form to upload file returns error as form not valid

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!

Django2 forms nothing happend when submit post article

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.

error 405 web.py

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.

How to send link/url to confirm user registration and/or password reset/recovery using ASP.Net MVC2?

I see it all over the place, yet, I could not find one example about this (maybe I don't know the proper wording), I am trying to build using ASP .Net MVC2 (but any example on just ASP .Net would be also helpful) a process that will send a link to the user at the end of the registration process to let him confirm his registration. Also, a similar process to let the user to reset his password, with the typical "forgot password" and send a link/url so that the user can click and type a new password. Can someone help me to either find an example or at least to let me know how to "google" it?
Thanks,
Mark
For the forgot password, you can make a view like this
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true)%>
<p><%: ViewData["Error"] %></p>
<p> Have you forgotten you password? No problem!</p>
<div class="editor-label">
<%: Html.Label("Fill in your username") %>
</div>
<div class="editor-field">
<%: Html.TextBox("userName") %>
</div>
<p> and <input type="submit" value="click here" /> to reset your password.</p>
<% } %>
and as a controller (first make an model from the aspnetdb (if you don't see it press the 'show all files' button))
This must be placed right after the controller definition
aspnetdbEntities aspnetdb = new aspnetdbEntities();
Then follows this
public ActionResult ForgottenPassword()
{
return View();
}
[HttpPost]
public ActionResult ForgottenPassword(FormCollection formValue)
{
var userName = formValue["userName"];
try
{
var useraccount = aspnetdb.aspnet_Users.Single(c => c.UserName == userName);
var fromAddress = "put an email-address";
var message = new MailMessage(fromAddress, user.Email)
{
Subject = "",
Body = "a link to a controller that lets the user put in a
new password and then save that password to the aspnetdb."
(that controller will most likley require a username)
"or a link with a new random password in it tht you have put
as his password like this:"
useraccount.aspnet_Membership.Password = "random password";
aspnetdb.SaveChanges;
};
var client = new SmtpClient("smtpServerName");
client.Send(message);
return View();
}
catch
{
ViewData["Error"] = "Please give up an existing username";
return View();
}
}
I hope this answer was helpfull.