#web-development
2 messages · Page 7 of 1
This is the best monkey patch I can come up with but again I have no idea how databases work
lol
Oh you do migrate it and this would be a problem when you migrate it yeah my bad
Welp sorry for the ping then
if i make a subdomain i.example.com point to example.com/directory can i do i.example.com/file.png where file.png is example.com/directory/file.png
that's known as a rewrite
although it depends what webserver you're using
anyway, yeah just set the root of the domain to start with
that's probably all you need
see i don't have a webserver yet
i'm planning to use digitalocean 5$ droplet and install a preferred webserver on it
I usually recommend nginx
ok and would the above be possible with nginx
Yup
Great, thank you ;')
Is it possible to use Pelican / ISSO with Github Pages? Or do I need a VPS for that?
You may not, Github Pages are for static sites only.
Based on this tutorial, it seems like there is a service that needs to be run
oops, no markdown?
Discord sadly only supports a subset of Markdown
better than irc
github pages only supports static content iirc
What VPS is recommended for something simple like a Pelican blog with comments. AWS? Are there any other options? I just want to set up a personal blog.
pelican generates static content right? i'm not too familiar
DigitalOcean has a 5/month plan
it's pretty good
pelican generates static pages, but the comment plugins I guess are not static.
@hearty birch That does sound pretty good. I will have to give them a try. Thanks.
I have a question
bot.tags["ask"]
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving
• Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
@quartz maple
I was going to continue
I want to make a script - with flask that acts like a job card.
You input your values and it goes to a db. There's a place where the job cards can be viewed.
Is there any basw code for this?
base code
Code
MySql
ew
Ew
Ew
for mysql you have to types of libs either an ORM lib like sqlalchemy (allows you to write classes which represent your db inside your code) or a lib where you directly write the sql on your own like PyMYSQL
up to you
Not that i knew
Based on my
do you know sql?
as a language
well then either go for sqlalchemy or learn sql first
(i recommend learning it)
Okay....
Well
I don't really have the time
I really just want to make a job card system for my small business
And I might have to use php anyway since its a cPanel system
Okay but I
Possibly couldn't even run a flask script
On
CP system
No ssh access unless the host allows it
flask shell?
but whats flaask shell
ooo
it helps you build stuff without importing over and over
it opens a python shell with your Flask App environment giving it a push
yes but what is it, link? code ? pix?
so you'll start from there
on your terminal write flask shell in a flask project
it's like flask run, etc ...
terminal commands
why would you use a shell to develop persistent code?
it's a mean to test your code quickly
and whats your problem with it
I've manipulated the shell to have extra stuff imported in it on launch
it's not working properly
how have you manipulated it
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Post': Post}```
db, User, Post are imported in the py file. I can then call db for example in the terminal and directly have it in there
in shell> db
> returns the db object```
Idk why but i feel like my env variables aren't being set.
(venv) PS C:\Users\Thunder\Documents\microblog> set FLASK_ENV=development
(venv) PS C:\Users\Thunder\Documents\microblog> flask run
* Environment: production```
and i can't seem to find a file in venv concerning the env variables 🤔
are you using pipenv or just a venv on its own?
pipenv (and I think flask cli as well) supports dotenv
i am using venv
i am following simply the guide, and then i research after each post on stuff
but this one broke ... If at least I can see the flask environment variables ...
so you make a file named .env and put your env vars in it
but I'm not 100% sure if you can do that without pipenv
i'll have a look at it
the ugly thing is that I can't see in any place a thing on env variables for flask. Like where they're stored, or why they are not being set, etc.
i found for linux, but am on windows
same to windows!
idk where i fucked up (or my pc isn't working with me)
i've checked over and over what am doin
doing that only sets it for the single command
lemme check
you have to do it all at the same time if you do it like that
but maybe look at dotenv
alternatively run your app from an IDE instead
on windows nuh, doesn't work
im sure miguel will be using dotenv later on in the blog
i'll have a look at it after i check why it's tripping
i want to know what's going on
what's a recommended database library for simple small-scale projects with flask?
You'll need a database server regardless of size because of flask workers
We use rethinkdb
yeah alright, i'll see what i can do ^^
@brave mantle i've created a new venv in a new directory. Tried setting environments and running it. They didn't affect shit as well 
Is this shit normal yo?
or you don't have much to tell me on this case specifically?
icic
I followed this solution: https://stackoverflow.com/a/40852895
I am trying to follow the flask documentation on my windows machine given at the following link:
http://flask.pocoo.org/docs/0.11/quickstart/#debug-mode
Firstly I wrote the code below in a python ...
worked
god i've been searching for 2 hours for this
the title of that SO question is so fucking bad!!!
how do you phrase that you built something with flask and python
flask over python? python over flask? flask with python? python with flask?
something like, python with the flask library maybe?
"a flask app"
"i made this thing with the python language and i also used this thing called flask which is a library for the python language what makes it easier to make websites with a good object oriented style rather than just writing to a file with html tags", should sum it up quite nice for anyone wanting to know quickly what you've made. 
@stiff vessel on our website, when faced with the same question, we simply went for "Python and Flask." as in "This website uses Python and Flask, and was developed collaboratively on GitHub."
-- Hey, I made a website!
- Oh, nice what tool did you use?
-- I coded it myself.
- Nice, which language?
-- Python.
- Oh, what framework did you use?
-- Flask.
So in essence you only say you made a website with python if they don't ask any further :D
normally I'd hit with "what'd you use?", first, and expect "Flask"
if I'm interested enough to ask about its implementation I want to know more than the language it was implemented in
if you mock up a WordPress site you shouldn't say you made it in PHP and HTML
"Python ft. Flask"
maybe not @neat nest but you hardly have to write any PHP to get a wordpress page running
most people will never write a single line
you certainly do have to write some python for a flask app though
WordPress may have been a poor example. my point was not so much to exclude the language used, but rather that the language in which you wrote something says very little about it and the framework that you used is probably what someone's interested in
assuming that you did, in fact, use a framework
yeah
They can always Google the framework and figure out the language
Need some help with Django, Redis and websockets. It works fine locally, but when I run it on my server it 404's to socket routing.
Should log
[2018/05/22 20:52:29] WebSocket HANDSHAKING /socket/tictactoe/ [127.0.0.1:53658]
[2018/05/22 20:52:29] WebSocket CONNECT /socket/tictactoe/ [127.0.0.1:53658]
But on the server
Not Found: /socket/tictactoe/
[22/May/2018 20:54:52] "GET /socket/tictactoe/ HTTP/1.1" 404 4332
application = ProtocolTypeRouter({
"websocket": AuthMiddlewareStack(
URLRouter([
path("socket/tictactoe/", TicTacToeConsumer),
]),
),
})
The rest of the website works perfectly, just not sockets.
Yo, someone here is using Plesk ? I have a plesk server on top of a Ubuntu on Google Cloud Compute Engine. Everything is working well, but im afraid.
I want to host multiple companies. I build websites with Django and Flask. Is Plesk secure ? I host Django app so I use passenger_wsgi and NGINX. I want to make sure all my clients are isolated at maximum.
Anyone know of a free dictionary api or text file version that is free to use?
Just checking if a word exists
personally I'm partial to https://www.oxforddictionaries.com for my definition needs
free tier API access is 3,000 requests per month, 60 calls per minute
Does anyone know how to add groups into a django rest api? I found https://github.com/bennylope/django-organizations but I'm not sure if this works with my rest api, does anyone know a great Django groups framework?
@lucy Thanks!
hey guys
im having problem with flask and sqlit
sqlite*
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post('{self.title}', '{self.date_posted}')"```
my code (classes as models for db)
when i add a user,like user_1 = User(username='Rohan' , email='rog@blog.com' , password = 'password')
from cmd
and then db.session.commit() , it gives an error calledsqlite3.IntegrityError: NOT NULL constraint failed: user.id
Help plz
that is what he did in the video
Corey Schafer
i deleted my code (which i typed seeing the video thinking that i might have done some error) and got the code from his github and still the same error
he is like it will be the id of the user who wrote the post
ill delete the db ,make a new one and try again
hmm, well I can't speak for what does or doesn't work for Corey Schafer, unfortunately
I just know what I read in SQLAlchemy docs http://docs.sqlalchemy.org/en/latest/orm/backref.html
oh
your PK should have autoincrement=True if you want it to be generated.
isn't that the case by default?
so what should i do to make it work @neat nest
Ah, you are right lucy
well I assume the name passed as backref ought to have meaning. is 'author.id' the proper foreign key?
I honest to goodness have never used SQLAlchemy before so I'm flying in the dark
even in the docs he used user.id in the address class
right but the backref is also 'user' there
unless you mean what Corey Schafer did and again I can't speak for why that might work
oh,should it be same?
This is a reduced example of what I have in some of my code:
class Client(db.Model):
__tablename__ = 'clients'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
amounts = db.relationship("Amount", back_populates="client", lazy=True)
class Amount(db.Model):
__tablename__ = 'amounts'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
client_id = db.Column(db.Integer, db.ForeignKey('clients.id'))
client = db.relationship('Client', back_populates='amounts', lazy=True)
so i change author to user
your back_populates needs to be the name of the db.relationship attribute in the other class
so for me it will be
user = db.relationship('User', back_populates = 'post', lazy=True)```
and for user_id ,it will be user_id= db.Column(db.Integer, db.ForeignKey('user.id'))
right?
'posts' instead of 'post'.
okay
btw im using flask-sqlalchemy
in the docs
same thing what i did,why isnt it working 🤔
not the same thing what you did!
once again, you've got a backref='author', but the name "author" never shows up anywhere else!
it does have a backref=person in the docs which doesn't exist. I didn't know that was possible.
something is weared with my code,lemme check for some spelling mistakes if any
your error is sqlite3.IntegrityError: NOT NULL constraint failed: user.id, user.id does not exist, I'm reasonably certain you ought to either change your backref or use the name you specified for your backref in defining the foreign key
could you show what tables it made in the DB?
--just FYI, with backref you don't need to define the relationship on both classes https://stackoverflow.com/questions/39869793/when-do-i-need-to-use-sqlalchemy-back-populates --
im using flask-sqlalchemy
I know, it's the same though.
i dint declare relationship on 2nd table
sending img,insted of code,tought it would be more clear without word wrap
can you type .schema user in sqlite console (assuming user is the tablename sqlalchemy generates)
in cmd,i type python
There is no sqlite repl with the sqlite module
And sqlalchemy will not allow you to directly manipulate the database like that
If you want to inspect your database, find a tool online for it
i used metadata.tables.keys() and it came
dict_keys(['user', 'post'])```
@deep prism
best thing to do is change my database to flask-MySQLdb
sqlalchemy is giving me a headache
Then take a break
yea ,gonna take a break after i set up mysqldb
best thing in it is i dont have to write models (classes) in flask ,i can do it directly from mysql shell or workbench 😁
That's missing the point
Yeah, and then you still have to write your queries manually.
(I was pulled in a meeting)
Let's see if you feel the same way when you're writing inner joins yourself
I'd first try to just change the DB url to mysql and see what happens.
I still don't believe your PK was set to auto-increment. Did you, ever, write the model definition without setting the id column as primary key, or did you never delete the DB and retry?
Hell, just comment the Post class and the relations and see if you can create a User without relations.
Yeah, sqla isn't going to update the schema for you
You need to write migrations for that, using eg alembic
And in the case of setting up the first database, as you are doing. It's a matter of deleting the database - Which for sqlite is deleting the file i think - and db.create_all() after all DB models are imported.
i did db.create_all() stuff n all
i followed the video exactly
and this error starting popping up
the error which i posted up
im just commenting the sqlalchemy,will see abt it later
Hey everyone, I've been getting into some Flask and Gunicorn-based web development recently and have a question. Currently, I'm running a Discord bot with an OAuth 2.0 flow that requires a website, and these run independently from each other. Ideally I would like to have some sort of communication between the bot script and website, so I wanted to test out running the website as a cog within the bot. Only issue there is, I don't know how to execute gunicorn from within a .py file. Is there a way to do it?
@dry portal No, there is not. They must be separate.
You might consider writing a REST API for the bot to use, or websockets
I saw something about using multiprocessing to pass information over separate scripts but I could never get it to work
fwiw, this is how you run a flask app with gunicorn with python:
from gunicorn.app import base
from gunicorn.six import iteritems
from xxx import application
from xxx.common import config
CFG = config.CFG
class xxxApplication(base.BaseApplication):
def __init__(self, options=None):
self.options = options or {}
super(xxxApplication, self).__init__()
self.application = application.app
def load_config(self):
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == '__main__':
application.init()
options = {
'bind': '%s:%s' % ('0.0.0.0', CFG.app.port),
'workers': CFG.app.workers,
'threads': CFG.app.threads,
'preload': True
}
xxxApplication(options=options).run()
Sometimes you have to do this if you want custom config.
It's mostly from somewhere in the gunicorn docs
Running gunicorn with python: No reason not to
Running a website in a discord bot: Kinda weird to do. A discord bot is a discord bot, and a website is a website...
you can't really embed much into a discord bot
aiohttp, maybe
but you definitely won't be using gunicorn
Gotcha. In that case I might go a different route then. Thanks again for the help to both of you 😄
Anyone have any experience with Flask + SQLAlchemy? I'm trying to figure out a way to filter an error in jinja2.
I'm trying to render a user profile on a webapplication and one of the database entries is a team_id. If they have a team_id in the DB, the profile page of the user renders.
If the value of team_id=NULL I get File "/Users/scott/PycharmProjects/agoge/app/routes.py", line 145, in user return render_template('user.html', user=user, team=team.team_name, posts=posts.items, AttributeError: 'NoneType' object has no attribute 'team_name'
and my route looks like this
@app.route('/team/<team_name>') @login_required def team(team_name): team = Team.query.filter_by(team_name=team_name).first_or_404() return render_template('team.html', team=team)
thats a different route
woops you're right.
One sec.
@app.route('/user/<username>') @login_required def user(username): user = User.query.filter_by(username=username).first_or_404() team = Team.query.filter_by(id=user.team_id).first() page = request.args.get('page', 1, type=int) posts = user.posts.order_by(Post.timestamp.desc()).paginate( page, app.config['POSTS_PER_PAGE'], False) next_url = url_for('user', username=user.username, page=posts.next_num) \ if posts.has_next else None prev_url = url_for('user', username=user.username, page=posts.prev_num) \ if posts.has_prev else None return render_template('user.html', user=user, team=team.team_name, posts=posts.items, next_url=next_url, prev_url=prev_url)
I think the way to go is put an if statement in the jinja template
but it doesn't seem to work.
well, your error is in your python code, not template
pseduo it would be... - if team == None do X
you can use something like team.team_name if team is not None else None or if you're lazy getattr(team, 'team_name', None) to pass None if the team does not exist
or just pass the team itself, and do that is not none checking in your template
You're talking about in the route render_template function?
or in the user function
because the user function displays just fine if there is a value in the database
you've got team=team.team_name. your error is telling you that team doesn't have a team_name attribute because it is None
Oh I see, so its erroring in the render_template function and never returns values to display.
erroring in your user function because it can't call render_template with something that doesn't exist, but you've got basically the right idea
yup, that's essentially what Volcyy recommended
although he gave you snippets for doing it inline
what you proposed works as well
Right I was trying to figure that part. Sorry, pretty beginner. I'm doing the miguel grinberg tutorial for flask and trying to expand on it now.
that's awesome! let us know if you have questions with anything else
awesome. getattr() worked. Time to learn a new function 😃
turns out there are stock photo sites that license under the CC0 license
free images, no attribution whatsoever
I just found https://www.pexels.com/
Yoink. 📸
:>
then you didn't read the site properly did you
you went to their partner
free stuff first, then there's a break where it says "look at this premium stuff from our partner"
Aah right, Sorry, no pictures found! Here are some search tips: and then there's Sponsored Photos
yep
{% if form.email.errors %}
<div class="uk-inline">
<span class="uk-form-icon uk-form-icon" data-uk-icon="icon: user"></span>
{% for error in form.email.errors %}
{{ form.email( **{ 'class': 'uk-input uk-form-large uk-form-danger', 'placeholder': 'Email Address', 'uk-tooltip': {{ error }} } )}}
{% endfor %}
</div>
{% else %}
<div class="uk-inline">
<span class="uk-form-icon uk-form-icon" data-uk-icon="icon: user"></span>
{{ form.email(class="uk-input uk-form-large", placeholder='Email Address') }}
</div>
{% endif %}
pretty disgusting but i'm trying to use a tooltip to display the error in a field.. as you can see this is horrible and not working either. any suggestions?
Is that django or jinja
Hmm I don't know much about jinja but in django
After you open a {{
You don't need an inner one to enter variables
{{ error }} } )}}
Like this
Don't know if it is related
You just write error
Worked? :D
Nice :D
that is great actually, fixes a lot of problems I had
can I do something like
'uk-tooltip': error + '; pos: right;'
In django yes
Don't know about jinja but probably
But the whole thing needs to be in {{}}
wait what
you're applying this to a tag in your template surely
<div uk-tooltip="title: {{ error }}; pos: right;">
...
</div>
They were using multiple variables so I think {{ var + 'foo' + var2 + 'bar' + var3}} is better than 3 {{}}
About?
what gdude's talking about
I don't know anything about wtforms but that is the usual way how jinja works
Like it is the exact way of using jinja for a single variable
ive got a problem somewhere in my website on the backend. im using the dash python framework (which allows interactive graphs) which itself is built on flask. when the dash callback finishes (this is code i have written to respond to a button being pressed), the data is sent from the flask backend through gunicorn, which is then proxied through nginx. however, somewhere in the line, my large set of data being sent via a post request is getting delayed. the data consists of 8MB of json data. the callback in python finishes in 15 seconds, but my browser does not start receiving data until 60 seconds after the button press. any ideas on where to look for the delay. other callback which send small amounts of data (a few KB or so) are instant and have no problems
the callback starts at algo parse stats and finishes at callback timer stats
ok im pretty sure this is a problem with gunicorn in some way now
gunicorn is regestering connection closed (debug mode enabled) 45 seconds after the callback function is finished
def register(request):
if request.method == 'POST':
form = forms.RegisterForm(data=request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
basic_password = form.cleaned_data.get('password1')
user = authenticate(request, username=username, password=basic_password)
login(request, user)
return redirect('home')
else:
form = forms.RegisterForm()
return render(request, 'register.html', {'form': form})
I'm using Django, and here's a register form. On submit, post, you create a new account.
But when I double-click on the register button, sending two requests at the same time, it crashes on form.save(). User is not unique.
So my guess is that in sending two requests quickly, it tries to create the user twice, which creates a IntegrityError: UNIQUE constraint failed: auth_user.username
How can I solve this?
just a quick question, is there a way to select a random string from a list in jinja.. or should I be handling that in python itself
You can probably add functiona in Jinja just like in Django templates
@hearty birch
Search for template tags jinja2
Yup write the function in python
Use them in jinja
yeah I know how to do it in python, just thinking if it’s better to write it in jinja or python
Like list|function_that_returns_random
I just want to randomise a legend for my login
I am explaining how to do it in jinja
was answering Lord Greyweather
Oh
sorry i am a bit tired but go on how would I do it in jinja?
because it is something small so idk if it’s worth me writing it in python - but then again it’d probably look ugly in jinja
Apparently jinja and Django templates are a bit different here
Here is how you register a function for jinja templates
i think they’re called macros or something right
I see a flask specific answer
pretty complicated for what i’m trying to do but probably the best way I guess, thanks ^^
You already should be using your view if possible
There are some things that incredibly hard to do in view and sent to the html
Use template functions only then
Anyone familiar with RedisChannelLayer?
woah didnt see this channel
maybe thane knows about redischannellayer. pretty sure he's worked with redis. @still briar @safe python
he's probably busy at work right now though
Got to work 5 minutes ago. My stuff is on redis. I do not know what redis channel layer is.
If I had the time, I'd move to another database solution
The AsyncJsonWebsocketConsumer (BaseConsumer) requires a channel_layer, which is set in settings.
I dunno, the redis solution works. We wanted something more light weight with expiries?
It's just that the consumer has only access to a "channel_layer" which is some blob using redis, and it only really supports group_add and send_group stuff.
If it work, use it. I wasn't saying not to. I want to use different DBs for sake of experience.
True true.
I also want 48 hours in a day, though
Oh definitely.
Then I just have double work every other day
So anyhow, it seems we managed to connect to the channel_layer's redis by using ```python
index = self.channel_layer.consistent_hash(table.id)
return self.channel_layer.connection(index)
Problem shuffled
Where the returned value is an redis object that has get, set, delete, etc. Feels like I'm playing with cookies.
Although I noticed only today that the consistent hash is only necessary if you have multiple hosts which I think there's only one of in my django settings, so the index always ends up at 0.
So whoops, the redis database was global for the entire project, which caused some problems. 💦
Hello!
Well, we wanted it specific per table, so a solution is to just add the table id to the cookie key. redis.get(str(table.id) + 'gameinfo') ish
I barely know any redis. Are you supposed to use it just with get set delete? What other cool stuff are there?
Lmao redis #databases have a whole bunch of other commands. Get, set, and delete work with single string items. There's sets, lists, hashes (equivalent roughly to dicts, a key val mapping), and sorted sets with scores
Have you been through the docs for redis.StrictRedis?
I'll check it out!
As of now I guess I've done everything in strings. Json dumping the game data, getting/setting it.
Redis values don't have layers, like, you can't directly map multi level dicts/JSON to it, but it does have namespaces
I think the default separator is a semicolon
Get yourself Redis Desktop and play around with it on a local database. You'll get a feel for what redis can do real quick.
Right right.
Cross-platform redis desktop manager - desktop management GUI for mac os x, windows, debian and ubuntu.
This really needs to be in #databases unless it relates back to #web-development
What kind of data can I store in a session? Integers? Strings? lists?
What can the lists contain? Can I store objects, or their references in a session? Not that I ever would, just wondering
Sessions basically just store strings
Although it depends on the framework
Flask sessions are encrypted JSON
(for example)
I see
In Django, is there a way to tell the difference between two sessions/requests of the same client?
If I'm logged in and open a new tab, I'm still logged in, and the request.user is the same.
When it comes to http requests I suppose it doesn't matter. I'm playing around with sockets and consumers though. You can reach that same user object with self.scope["user"]
But I'm trying to make a user list where when someone joins, they're added, and removed when they leave.
And the problem is when you join with a second tab and leave, the first one is kicked out as well.
Oh hello.
self.scope['cookies'] -> {'sessionid': 'rth25htmrbhmfoit0wnsew8xgd0n5640' ...
Actually I got access to both sessionid csrftoken, which are both really long strings?
Anyone awake in web-dev have a second? I have a few questions that are probably pretty dumb
Bonus points if familiar with Wordpress
I guess mostly the issue is im not exactly sure what the correct question is
I dont have much of a computer background but have done some simple hobby coding for years. I recently put up a personal website using AWS EC2 and have some questions about how to integrate data from simple scripts ive written in python to my webserver
aha
Like
well what's your website running on now?
Bitnami image of wordpress
is it wordpress? since you mentioned that
I see.
Like
Basically
Im trying to document my process of learning to code
so it would be nice to be able to realize and understand capabilities of displaying my data
wordpress has alot of tools to import data, I have successfully used many of them in the past
it might be that wordpress is a bad choice for this. what you're asking is theoretically possible, though.
or do I / can I run flask next to my WP site
Like WP for blog and ease of use and a flask app next to it
if possible
but you rely on third party tools, and they might break when you update WP
technically your flask app could be a page on your WP site.
Can I use the same hostname for that etc
Yeah Ive kinda seen what you mean @sturdy sapphire
Am I able to just write a flask app and use the same domain to point to it?
yes absolutely
Would be easier to integrate python
i had a WP api that i could communicate with, getting data in and out from an android and IOS app, but it broke after a year...
I have also an flask app at work that have been running for 2 years without issue
I would personally recommend that you do that. because trying to execute and fetch data from python scripts from a wordpress site is.. icky.
suboptimal
but you can definitely point part of your blog at the flask app
I just dont know enough about web dev to know how to configure all that
it's quite trivial to do so
we can help with it
the obvious way is to just set up a subdomain
and point that at the flask app
and then make a menu item or whatever in your WP app that points at that subdomain
so you can have like scripts.mypage.com or something pointed at your server
and in your apache or nginx or whatever you're using, you can tell that subdomain to load your flask
and then on wordpress you just add a menu item that points at that
that makes sense
and on the flask app, you add menu items that point back at wordpress
maybe have the same sort of navbar
and it will all look like one page
be quite seamless.
tyvm
np, let us know if you get stuck on any step :)
in the long run, you might wanna just use flask for your blog, too. when you get more confident, perhaps.
Yeah i would like to
it's a good learning project.
Lol
but writing from scratch is sooo satisfying, and you get complete control of every aspect
and WP does kinda suck
and PHP is a crime against humanity
"Bam look at my website" (I did in under 3 hours with minimal experience)
I use WP alot, but for my personal blog it just gets cluttered up and i stop using it..
so i am also thinking about making everything in flask
or django, but i have no experience with django
but the ease of implementation is so tasty
I wanna tackle flask until it frustrates me, then use django but I wanted something up quick because I want a new job yesterday
Is there a reason why flask wouldn’t work as a full web server without Apache or something in the way?
It would but I'm a novice programmer so its easier for me to host WP now and work on a flask app once I feel more confident
My current job is not in the CS industry, it's in the electricalk industry so I'm using the site currently as a pseudo-resume
But I'd like to migrate to IT or similar so I figure work on it now and eventually Ill have something
Sorry. I didn’t mean that directed at you. I just meant in general why does flask say not to use in prod when you start it up. Like what does it lack that Apache has
O lol
flask is not a server. the development server is not fit for production use. there are a great deal of reasons why, but most of them boil down to security and performance.
you'll be exposed to DDOS attacks and it'll all be running on a single worker, which means if more than one person use your web service at the same time, you're gonna run into trouble.
Ah fair. So you need something like Apache to handle load balancing and such in the background but there’s nothing wrong with using flask inside of it to serve the content?
flask is wonderful when used together with something like apache, yes.
personally I use gunicorn and nginx
So as a general web dev question. Let’s say I want a service that acts as a phone book between users and their devices at home. This is kind of a continuation of my doggy cam project in #303934982764625920 just to learn more about stuff.
If I wanted to allow users to sign in and get the feed of their webcam. Would the best way to do that be to store IP/Port of flask app in a database using the username as a key? Or something similar?
to handle logging in and stuff there is an extension for flask that helps
flask_login
but yes, you'd need a database most likely
Or if you want to learn it you may even write the authentication yourself
The thing that I'm too lazy to do
I was probably going to do the authentication in php cuz I’m miles more familiar but I might stick to flask just to learn it more
ew php
It’s the future man
Lol
PHP has 3 letters, python has 6 so you save 3 characters googling
I have a simple flask app that interacts with a database. I'd like to keep checking the database for changes (24/7) and send notifications based on that info. Is it feasible and a good idea to use flask for constantly checking the database? If so, any suggestions on what I should be looking into? celery? Advanced Python Scheduler? something else? Shouldn't use flask?
Thank you very much for the input 😄 wasn't thinking of cron as an option, but I guess I would be fine with checking every few minutes instead of every few seconds.
it can do that too
but you should really consider whether that's an appropriate thing to be doing
depending on the database, reading might lock access to the tables for a moment
slows everything down
I'm just wondering, what are the differences between Flask and Django?
Django is batteries included. It's all the bells and whistles whether you need them or not
Flask is more like a simple base to start but expandable
I've only made a few simple web apps so flask was perfect for me
I imagine if you're building something large and complicated Django would be beneficial
Yeah, I'm going to work on small sites, so I think flask will work for me, thanks
Is it possible to combine them?
You wouldn't want to
How about using Django for security
As far as I know flask can do pretty much anything Django can with extra modules
I feel like if you're using part of Django you may as well use the whole thing
Using 2 frameworks that serve the same purpose seems like an inefficient complication
But I'm a beginner so I could be incorrect
You could go through a blog tutorial in each one pretty quickly then decide
well, django has built-in utilities for pretty much everything and is easily extendable too
just install some thing and add it to INSTALLED_APPS
Anyone have a bit for a voice chat on pycharm/windows/django?
No. We do not provide one-on-one tutoring - you can hire someone locally if you really need that. We also prefer that questions are answered in a public channel as it means that everyone else present is able to learn from them. If you're working with code that you are unable to disclose for any reason, you should try to make your question more general and write a separate, small piece of code to illustrate your problem.
Hello
I was wondering, what is the best way to collect stats in Sanic?
Like
We want to know the amount of requests per ip per day/week/month
What would be the best approach for this?
look into middlewares
have one run on each request
access the request ip and save it somewhere
by the way
sanic is a cool thing but I advise you to read this https://www.reddit.com/r/Python/comments/876msl/sanic_python_web_server_thats_written_to_die_fast/
219 votes and 41 so far on reddit
also asvetlov is an aiohttp team member & python core dev and worked heavily on asyncio iirc. so thats not just coming from some random dude
it is, and the guy didnt even plug aiohttp in the post itself lol
yeah but @meager anchor what would be the best way to store the data
spent ages wondering why CSS wouldn't work
had browser cache enabled
😎
F12 no cache is the only way to go
Ctrl+Shift+R to refresh always no matter what
Why don't you people just turn off the cache on your browser for 127.0.0.1/*
so i have a flask app with a divisional folder structure. in my app/views/main.py file, i have a route and two helper functions defined. is there any better place to put the helper functions rather than in the views script like i have here?
...
main_bp = Blueprint("main", __name__)
def get_access_token():
# code here ...
return as_json
def get_user_info(token):
# more code here ...
return response.json()
@main_bp.route("/")
def index():
user_info = get_user_info(current_token)
return render_template("main/index.html", user=user_info)
ok i need help (@grand badge suggested i post it here). i have a flask app which is running on my website, and one part of it uses the msg. subdomain. however, when i try to view that subdomain, it just sends me straight to the main page (w/o subdomain). i imagine this is because nginx isn't telling the docker container which subdomain is being viewed, though i can't think of why that would be. i've tried loads of different things, but this is what reproduces the outcome i just explained:
server {
server_name codingbykingsley.co.uk www.codingbykingsley.co.uk msg.codingbykingsley.co.uk;
location / {
proxy_pass http://172.17.0.2:5000;
include /etc/nginx/proxy_params;
}
}
i've also tried this, but it just makes all of my subdomains point to a different subdomain of the website which is referenced by a completely different nginx config:
server {
server_name codingbykingsley.co.uk www.codingbykingsley.co.uk;
location / {
proxy_pass http://172.17.0.2:5000;
include /etc/nginx/proxy_params;
}
}
server {
server_name msg.codingbykingsley.co.uk;
location / {
proxy_pass http://172.17.0.2:5000;
include /etc/nginx/proxy_params;
}
}
i think you have to use proxy_set_header
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Request-Start $msec;
in the location block
include /etx/nginx/proxy_params; does most of those lines, but i'll give it a shot ^^
o ok i was looking into my conf's for how dokku handled it
dokku does all this for me automagically
just tested it, got the same as the top code i showed. thanks anyways :D
:D
is the container for msg.domain.tld the same as domain.tld
yes, because they're in the same flask app
i figured it wouldn't be an issue as flask allows you to put subdomains on your routes
what if for X-Forwarded-For you used $proxy_add_x_forwarded_for
eh shit that's not it
weird
i think i can see what is happening, but i have no idea why or how to fix it
ok i have one last thing to to try
proxy_pass http://172.17.0.2:5000$request_uri;
for the subdomain
nope, doesn't work
😦
thanks for trying though ^^
have you checked if msg.subdomain.tld works directly, without the proxy
connecting to the container
how do you mean?
so on that machine you could edit your host file to point that subdomain to the docker ip
then try to accesss it
bypassing the nginx proxy, to see if the problem is flask/docker
yes
that would at least let you focus on one part
ubuntu@ip-172-31-34-189:/etc$ curl msg.codingbykingsley.docker:5000
this returned the HTML for the main page 🤔
hmm
im not expert im just starting out so just a disclaimer
but i would guess that means flask is the problem
do you have SERVER_NAME defined in your flask app?
i believe subdomains can't work without that
well, i'll have a tinker
very well haha
# IMPORTANT! subdomains will not work without the SERVER_NAME config
app.config['SERVER_NAME'] = 'local.com:5000' ```
there we go
yay :D
give that a shit
yup already reverted that
let me know if it works
if my docker container is running on 172.17.0.2:5000, would i also add :5000to the SERVER_NAME?
i was wondering if you were going to ask that because honestly i don't know
but my guess is yes
well that's making all of my pages return 404 so let's see if it works without port
oh hey, it works now :D
sweet
thanks a lot ^^
no problem
one downside though, rip CSS haha
first step which we skipped in the beginning should always be test things seperately
make the problem smaller
yeah, that's a good technique
because we might have still been fiddling with nginx all night for no reason
i usually do that but it's 4AM and i feel like my brain has come out of a blender
and just so you know i used almost no prior knowledge to help you it was pretty much all google lol
well i already tried google but apparently i'm not good enough :D
well time for bed for me im glad it works
Gn fam
goodnight ^^
{{ form.picture(class='uk-button uk-button-default', type='button', tabindex='-1') }}
Getting an error on this line in Jinja2
TypeError: html_params() got multiple values for keyword argument 'type'
<button class="uk-button uk-button-default" type="button" tabindex="-1">Select</button>
using Flask and WTForms
or
probably a better question,
which class would I use in UIKit to allow WTForms to access File Upload
I know in bootstrap it is form-control-file, I would like something similar
excuse the poor terminology ^^
ohh I understand the error now
I think the WTForms already says that type='file so I was trying to overwrite it when specifying a type, thus giving the TypeError
<div uk-form-custom="target: true">
{{ form.picture() }}
<input class="uk-input uk-form-width-medium" type="text" placeholder="{{ form.picture.label.text }}" disabled>
</div>
<button class="uk-button uk-button-default">Submit</button>
I just did something like this and it kinda works
Anyone familiar with flask-upload? I'm trying to create a form that has several fields with a file upload button but I want uploading a file optional
and it seems like flask-upload requires a file. I can't figure out how to except the None type.
if I add a file everything works perfectly fine.
anyone good at django REST framework? im trying to figure out how to generate docs for function-based views. i want to be able to specify things like parameters, etc, in the comment and have them show up in the docs
Hello. Anyone know how to create your own Register/Login/Logout form in django?
the easiest way is to use the built in auth views with your own template
from django.contrib.auth import views as auth_views
path('accounts/login/', auth_views.LoginView.as_view(template="yourtemplate")),
I don‘t think you even need to make your own view
Overriding the template should suffice
can anyone answer my django question?
anyone good at django REST framework? im trying to figure out how to generate docs for function-based views. i want to be able to specify things like parameters, etc, in the comment and have them show up in the docs
@sick forum in this moment i using this form, but i would like to create my own. Okay, thanks for Your answer.
When do I need to request consent for stuff collected by my website? Simply speaking, the website itself does not collect any data, does not track its users, and does not use any third-party services for analytics or tracking. The only thing it uses is Discord's OAuth, and it uses that when a user logs in. For everyone else that's visiting, that's irrelevant. Do I need to get consent only on the log in view or globally?
Only on login
but you should do it before they actually give you their info
not after
how easy is tracking things such as time spent on a website, and other statistics like these on Flask
@hasty wing you may have more success asking your question here, where users familiar with your problem are more likely to congregate. if you could also review our nickname policy I'd be extremely grateful https://pythondiscord.com/about/rules#nickname-policy
@vestal hinge can you try passing the request to the authenticate call
@neat nest thanks, I'll do that
also, what are your AUTHENTICATION_BACKENDS defined as
Basically, I wanna be able to have a view called "remove" that will remove a quote from favorites when activated. I can't figure out how to make this happen. I'm really bad at queries I guess lol
Can you post your code somewhere online instead, e.g. hastebin, please? Most people will probably not go through the process of downloading a zip file
Yes, thank you
You want to delete a single object, correct?
I wanna delete a single entry in the many to many field, sorry for the late response
@meager anchor So in my many to many there's an id, user_id, and quote_id. I wanna filter and find the user_id and quote_id that match and then delete that entry from the field
But the issue is that you don‘t currently have any ID to reference in the deletion view, right?
I have the reference id but i just have no idea how to make the query
So idk what code to write that would make this work
I don‘t think you need to interact with the manytomanyfield directly
For reference as to what I'm doing. When a user clicks "add to favorites" I'm logging the user's ID and the quote's ID in a many to many field. What I need is a way to get rid of field that I created when I use "remove from favorites"
Just find a Quote with the given ID and delete it: https://docs.djangoproject.com/en/2.0/topics/db/queries/#deleting-objects
From the user‘s quotes, that is
I'm trying to remove the many to many relationsip though not delete the quote outright
Not sure I follow. You want to remove the Quote entry where userid = request user id and quote id = unfavourited quote id, right?
yes! exactly
When i remove it from my many to many relationship it will naturally go back to the "Quotable Quotes" field
What I would do is get quote objects which have user_id=request.user.id and quote_id=the unfavourited quote ID
however, looking at your models, I just noticed that the user ID is stored as a charfield on your quotes
Well, the poster_id
Quote.objects.filter(user=request.session['id']) should give me all the users favorites
So from there I just need to filter it more so I get the favorite with the ID I'm trying to unfavorite, right?
Yeah
Quote.objects.filter(user__quote=id, user=request.session['id']).delete() is what I just tried but that deletes all of a users favorites and deletes them from the whole database. I just want them out of favorites lol
I don‘t understand what the first condition is doing, so maybe its getting ignored or something. The quote should have an id attribute since you didn‘t give it any that you can compare against
"id" is the id of the quote I'm trying to delete. "user__quote" was the way I thought I could call the quote object in user
What I meant was, if you don't specify a field with primary_key=True, Django will (probably) autogenerate an id field as the primary key
Like, in the fave method, you also filter by id:
def fave(self, user_id, quote_id):
self.get(id=quote_id).user.add(User.objects.get(id=user_id))
I see what you mean now. Heres what the many to many looks like in SQLite Viewer btw. How can I query these fields? I'm having trouble with that
Ohhhhhhhhh
God damn sorry, I completely forgot. I kept thinking that the Quote model are the favourited quotes, but you use the manytomanyfield for that, right?
yeah
Let's hope I got everything right..
Quote.objects.get(id=quote_id).user.all()
That should give you all users who favourited the given quote. Then, you should be able to filter by the user ID with ```py
Quote.objects.get(id=quote_id).user.filter(id=request.user.id)
And you can delete that by using `.delete()`
I think something broke when I ran and tested that.
Just deleted it and opened the zip. Old file seems broken beyond repair lol.
Hmm
Quote.objects.get(id=id).user.filter(id=request.session["id"]) will work (it seems) but now I need the delete to work without ruining my entire project lol
Yeah, everytime I use the .delete() everything ends up screwed
What is
Quote.objects.get(id=id).user.filter(id=request.session["id"]).all()
?
It should only be a sequence of favourited quotes by the user
How did you run the .delete()?
added it in the same space where you put .all()
And that deleted all the objects of the ManyToManyField?
It kinda fucks up the entire app, but idk why.
Oh wait, no. I think the issue is that my example is filtering by the ID of the ManyToManyField, not the user ID. try ```py
Quote.objects.get(id=id).user.filter(user_id=request.session["id"]).all()
instead
i'll try
"Cannot resolve keyword 'user_id' into field. Choices are: alias, dob, id, name, password, quote"
what even
but that's the manytomanyfield?
https://cdn.discordapp.com/attachments/366673702533988363/453842696683913216/Screen_Shot_2018-06-06_at_4.46.36_AM.png and this is what the table looks like, right?
That's weird, but the ORM is probably mapping the user objects above it, soo I have another idea, yay... Try the same with user__id. user_id resolves the literal field user_id, and user__id checks user.id
user__id isn't working either. this is so odd...
Same error?
yeah
I think I found the issue.
I've been giving you wrong examples for using the ManyToManyField 🙃
So in your case, I guess that would be:
user = User.objects.get(id=request.session['id'])
quote = Quote.objects.get(id=quote_to_unfavourite_id)
quote.user.remove(user)
Don't thank me, I wasted your past 2 hours because I was looking in the wrong spots :P
Reading that makes me think you should rename the user field to users in the quote class
I'm gonna read that article so I remember this for next time.
@deep prism Yeah I prob should
Is there anybody who didn't know how to create test's in django?xD
I have a problem with this error in my Django project: "'WSGIRequest' object has no attribute 'user_is_authenticated'" . I using Django 2.0 version and i have a optional MIDDLEWARE class. Anybody know how to fix it?
request.user.is_authenticated```
@native tide
Also I've never ever used tests in django nor in python at all if you are talking about unittests
@brittle copper# I have it in my views.py file, I mean request.user.is_authenticated but django show me this error message xD
Anytime
now everything works xD
Nice
Yes i know, i just have second option where was 'user_is_authenticated'
XD
Thank You very much!
Anytime
To edit base colours in a css framework, like UiKit for example, what do you guys do?
what the framework suggests - edit the scss
there are docs for it.
at least in bulma
but it boils down to just overwriting the variables they use for the base variables and then importing the scss - then using that file to generate the css for your page
also scss is awesome and you should learn it anyway.
ah okay, I’ll probably have to try that out
the base colours are nice but get boring :p
@meager anchor wdym
how do you guys deal with memory limits when deploying a website? aws free tier allows 1 GiB memory
Memory isn't really a problem for most sites
@vestal hinge wat
with GDPR, do I need to collect consent for caching static files?
because that would be absolutely awful
seeing as nginx does the caching and i would have to move all of it to django
No I mean
location /static {
expires 1h;
add_header Cache-Control "public";
alias /path/to/static/files/;
}
With the Cache-Control header
That means its saved on the client, iirc
Hello! I have a question about display images in django TEMPLATES. I have one template like 'base.html'. And i would like to display there one of the pictures. What is the simple method to do it? I try with static~but django didn't see my picture.
@native tide, I'm just guessing, but you may have to use the collect static command so Django recognizes the static files
Hey. What is the difference between HTMLPY , Django and Flask?
that question is really googlable
@polar robin Can't find it.
htmlpy is apparently some sort of electron for python
django and flask are web frameworks
django is fairly opinionated (which doesnt have to be a bad thing) and follows the batteries-included approach, while flask gives you more freedom and is rather minimal & customizable
never heard of htmlpy before
o.o
how long should flask's secret key be?
rn im using
import secrets
secrets.token_hex(16)
is that okay?
are you regenerating that on every run?
i guess that works, although i usually aim for 100+ chars with passwords and keys like this
hey guys
I made a flask app
while it runs just fine locally
I'm having problems deploying it on a VPS
everything I do results in a 404
can anyone help me XD
depends on the web server you're using
Ok, so it looks like I am finally going to be entering the wonderful world of web development (and unmuting this channel)
Have a large application that is currently CLI-only
Need to build a stateful long-lived network-accessible API
My current thinking is a REST API with a ORM-wrapped DB backend that maintains the state
The first request of a specific category and unique thing with state will return a state ID, and all future requests to that category require the ID referencing the state for the unique thing
The reason for needing to maintain state is the API is a way to interact with a large number of devices that are connected to the server hosting the API in a variety of ways (vary by protocol and physical interconnect)
Most of you are either web developers or have web experience...what are your thoughts?
Initial research shows this to be promising: http://www.django-rest-framework.org/
Django, API, REST, Home
What are you making?
Yeah
@meager anchor I'm using apache
I'm using flask with flask-socketio and I'm having problems with long-polling connections not upgrading to websockets
I've installed uwsgi
and I'm running my app with this command:
uwsgi --http :5000 --gevent 100 --http-websockets --master --wsgi-file pecho/wsgi.py --callable app
this is my wsgi.py:
python
import os
from pecho import create_app
application = app = create_app(os.environ.get('FLACK_CONFIG', 'development'))
I'm also using gevent
I haven't installed gevent-websocket, because the documentation says I don't need it, if I'm using uwsgi
I have it working now! 😃
Before I initialized my connection on the client side with io()
I had to change that to io('http://localhost:5000', {transports: 'websocket'}
but I'm not there yet, because now my frontend proxy isn't working for websockets
@rigid turtle sounds like a good plan. I'd have gone with flask but ORMs are far easier in Django since it comes with one.
Yeah, that was my thinking
Flask was first choice, but Django is very "batteries included", and I don't have the time or energy to put into assembling my own custom flux capacitor 😛
yeah. I mean, to be clear, I would still have used flask. sqlalchemy ORM with postgres is pretty straight forward and I have no great love for django, but you are right that it is more work to set up.
if you want migrations you need alembic too
This isn't that permanent
but django sounds fine for this.
Think of temporarily setting up a server while stuff is going on, then getting torn down after everything is done
right.
Though it might be used long-term, but persisting the data isn't a huge deal
We'll see how this goes tomorrow
Fridays are nice and quiet so they're the most productive for getting coding done
got my proxy working too 😃
Hey all
Anyone know how to create a simple search bar in django? I have a class with ListView and i don't know how to do it
yes i do @native tide
you will need to override the get_queryset() method in your class
here is an example:
class SearchView(ListView):
model = Post
template_name = 'posts/post_list.html'
context_object_name = 'posts'
def get_queryset(self):
term = self.request.GET.get('term')
posts = self.model.objects.filter(title__icontains=term)
return posts
get_queryset() as the name suggests, gets a queryset based on the data you give it
in your html template, the <input> must have a name attribute and you must supply that name in the get_queryset() method
in my example, i supplied the name in term = self.request.GET.get('term')
because in my html template, the <input> has the name attribute set to term
then what i did next was that i got all the posts and filtered them based on the title and then return the queryset you want
very clean implementation 👍
i've always wondered how you build these dynamic search bars
that like, work on the same site
probably some JS magic
you changed the domain name?
hey my main men
I am trying to fix my html layout that looks like this atm: https://puu.sh/ACWfV/6735d8e061.png
with this code behind it (some jinja) https://pastebin.com/GwDtkGTX
I am trying to figure out why the words underneath each image get sliced after a single word, rather than traveling the entire wa across the image
<ul class="list-inline">
{% for res in search_results %}
<li>
<div class="col-md-1" style="overflow: 'hidden'; padding-left: 0px; padding-top: 10px; padding-right: 0px;">
<div class="col-md-1 container">
<div class="row">
<img style="border-radius: 3px; width: 250px; height: 200px" src="{{ res.file }}">
</div>
<div class="row">
<p>BOGO Dog collar</p>
</div>
</div>
</div>
</li>
{% endfor %}
its wrapped in ul
and it has a class of list-inline which im guessing puts stuff in a list like fassion?
the way i set it up
it the jinja is constructing each part of the list and putting them all side by side
but I suppose I could just utilize the column features bootstrap gives
and not use a list at all
I'll try to refactor this
looks like it worked
Just need to reduce spacing now
@grand badge thanks for your answer! I will check it in one moment
@grand badge It still doesn't work. I do something wrong, and don't know what xD. Can i show you my code in views and templates?
So i have a simple template with BookList, and simple View
#BookList View
class BookList(ListView):
model = Book
template_name = book_list.html'
context_object_name = 'book'
def get_queryset(self):
term = self.request.GET.get('term')
posts = self.model.objects.filter(book_title__icontains=term)
return posts
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print("Hello world!")
```
This will result in the following:
print("Hello world!")
Ou! Okey, sorry
template_name = book_list.html'
you have an extra quote mark at the end of this line
I just forigve to write this in Discord
In my code i have '''template_name = 'plibrary_hearth/book_list.html'''
When i try to move in to my book list in my website i have this error
ValueError at /books/
Cannot use None as a query value
i think is something in my urls
Yeah, probably term is missing
Do you know how can i fix it?;<
It seems like you would have to check whether the value is None or not
I have a button with my book list and there is a search panel. Now, when i add get_queryset method to my BookList view and move in to Book List button in my website i have this error.
Well, you're expecting a term query parameter
so http://your/url/books/?term=whatever
can you show me the current code you have again please? @native tide
Yes, can i send you with pastebin using?
Okay , so at the first - here is my models https://pastebin.com/GNnxPApU
there is a views file https://pastebin.com/9MgtWcyt
There is my book_list template https://pastebin.com/hBLPdsFQ
class SearchView(ListView):
template_name = 'book_list.html'
context_object_name = 'book_title'
def get_queryset(self):
term = self.request.GET.get('term')
books = self.model.objects.filter(book_title__icontains=term)
return books
in the template you sent, is that the template that is meant to have the search bar?
No, my search bar is in base.html template
show base.html please
okay, in this code:
class SearchView(ListView):
template_name = 'book_list.html'
context_object_name = 'book_title'
def get_queryset(self):
term = self.request.GET.get('term')
books = self.model.objects.filter(book_title__icontains=term)
return books
change term = self.request.GET.get('term') to term = self.request.GET.get('search')
Okay, i change it
Nothing. When i try to search something i have only for example http://localhost:8000/books/?search=medaliony
