#web-development
2 messages Β· Page 25 of 1
is it possible to create a jdango website wihout
using templates
like the html css and javascript is seperate from it
I cant put navigation bars in my django can someone help
everytime it says page not found
With django rest framework, can I map different request methods of the same resource to different URLs? e.g
if I have something like this ```py
class User(APIView):
def get(self, request, user_id):
# return data
def post(self, request):
# handle post data```and map User.get to ``/users/<int:user_id>`` while User.post is mapped to ``/users/create``?
I know I could separate them in different views but this would help keep things organized if possible
Guys
I wanted to ask about flask
I am making like similar website to this one http://www.visaok.in/jobs/post-a-job/, and i was wondering how would i allow styling in the description.
Like styling the text, with bold, italic, etc...
Is there already made functions for this or i have to write them myself?
hello I'm doing flask
I did a flask project earlier on pycharm
and created new files a whole separate project
and when I run that flask project
it has all the stuff from my other project
when i don't even have it open
@floral seal I'm sure you can, but that way you'd be violating the REST principles
POST is intrinsically a create
is that not what's happening? as i understand it, the post is creating a user
hi guys so i'm just practicing creating a system where there are servers for people to join it in django and i am trying to establish a many to many relationshiop between the user and the server. I have the client login and give them the option to make a server, once they make a server by typing in a name, how can i add that user to that specific server to establish a many to many relationship between them?
I am implementing graphql on my Django project. So i chose ariadne instead of graphene-django. Now i already created types and resolvers which was very fun at the start. Real problem arises when the data comes in. I need pagination and cache stuffs. So as long as my front-end is using Reactjs anyway i decided to implement Relay on top of ariadne. However i could not find any tutorial or blogpost about implementing graphql-relay-py on ariadne or django. Like how ???, its a whole new thing for me though, so even a little help would be appreciated. Please guys, give me some clue
what's the proper way to keep the database models out of the main .py file in a flask app?
yeah that is what I was trying to do
I have two databases with a bind
the models only get created in both databases correctly if they are in the main.py so far
db1.create_all()
db2.create_all()```
Can anyone make sense of gunicorn's --log-config-dict option?
It keeps telling me the dictionary is not valid
I looked at the source of how it parses it
It does checks isinstance(value, dict)
I don't see where the conversion from string to dict is happening
Obviously I can only pass strings through CLI
What does cli have to do with gunicorn tho
I am launching the app via the gunicorn cli command
And no I am not using JSON. I know it is meant to be a Python dictionary literal rather than JSON
I tried with a very simple dictionary --log-config-dict '{\"formatters\":{}}'
Error: Value is not a dictionary: {"formatters":{}}
I mean I know it is a valid dictionary, but the issue seems to be that gunicorn doesn't convert it from a string to a dict
I'm not sure if I am missing something or if this is an oversight on their end
Basically they never intended for this option to be used via CLI
cool π
has anyone worked with Azure before? I have a simple web app hosted on Azure and I'm using the Azure Active Directory Authentication
but i have no idea how to pull the logged in user's profile to display their name and position once they authenticate and reach the landing
is there something faster than django available for python?
flask
There are other microframeworks as well, such as Falcon, bottle, and I always forget the name of the other one that's usually mentioned.
Pyramid?
Or tornado? Gosh I donβt donβt either.
Iβm probably just saying random nouns hah.
How can i set server headers when using torando + flask?
The following example throws an error:
TypeError: unbound method set_header() must be called with RequestHandler instance as first argument (got str instance instead)
import tornado.wsgi
import tornado.httpserver
from tornado.web import RequestHandler
def start_tornado(app, port=5000):
http_server = tornado.httpserver.HTTPServer(
tornado.wsgi.WSGIContainer(app))
http_server.listen(port)
RequestHandler.set_header('Access-Control-Allow-Origin', '*')
RequestHandler().set_header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS')
RequestHandler().set_header('Access-Control-Max-Age', 1000)
RequestHandler().set_header('Server', 'Not Tornado')
print("Tornado server starting on port {}".format(port))
tornado.ioloop.IOLoop.instance().start()
if __name__=='__main__':
from main import app
start_tornado(app, 80)
Stackoverflow doesn't really help much here
On mobile but t sounds like set_header expects another RequestHandler as the argument where you give it a string.
The examples that use RequestHandler use it differently without wsgi and the httpserver, essentially it's it own server which I don't think I want?
The docs don't have much either
hi somewonw can help me w/ Flask and HTML
ask your question and see
how i can python duplicate a table for the servers you are own
on discord
Hello
?????
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.
Also have patience. We're all volunteers here and do this in our free time.
@primal minnow
What do you mean duplicate the table
Using the same db with 2 apps?
no
like this
let me see a exemple
like thar
i dont know if i go ban
so
i risk the image
@vagrant adder
@gloomy canopy I found the tutorial in the official docs to be an excellent starting point.
anyone have any good tuts for using vue with django? every one i've found has been a giant pain with lots of workarounds
getting to the point where it seems like it would be a good idea to develop the front end and backend independently
@primal minnow what is that
Hey all. Quick question: how does one handle file upload in Flask? Specifically many files that are larger then that can fit in session cookies?
for submission in reddit.subreddit('webdev').top('day', limit=1):
thread = submission
driver.get(submission.url)
content.append(submission.title)
for comment in thread.comments:
print(comment.body)
print(comment.permalink)
element = driver.find_element_by_class_name("t1_%s" % comment.id)
location = element.location
print(str(location))
size = element.size
x = location['x']
y = location['y']
width = location['x'] + size['width']
height = location['y'] + size['height']
driver.execute_script("window.scrollTo(0, %s)" % str(y + height))
driver.save_screenshot("full.png")
im = Image.open('full.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('element.png')
print(comment.id)```
So I am using Selenium to access a subreddit and take a screenshot of each comment from the thread. This is my code. I've tried searching **everywhere**. It just leaves a white, empty screenshot.
@cursive cairn gonna have to actually store them as files in the filesystem
@deft ore add a 5 second delay after driver.get
Still nothing @autumn bobcat
try loading the submission and then taking a screenshot before doing anything else
Anyone more clever than me know how to run a function when starting up a flask server via gunicorn / wsgi?
I tried putting in ```python
if name == "main":
modules.db.db_init()
logging.info("db initialized from wsgi")
modules.social.telegram_set_webhook()
app.run(host='0.0.0.0')
but no luck
it runs if I run it just through flask though
Hi! Maybe any of you could recommend a good read or good example of a principle of booking funcionality? I have everything planned already but I'm wondering what is the best way to enable booking through 2-3 steps. For example first you choose a service, then available date/time for that service and in the last step you input your contact details. I had this done with django+drf+react, but now I need this with pure django without a js frontend. What would you use? Session variables? The users which will be booking time will not be registered users. Thanks!
would it be smart to create a unique session variable for the user and store his info in the database and double check the db with each step using his unique session var id? It will not be a user heavy app so I'm not worried about speed/scalability/etc.
how would i go about implementing a search bar on my flask app that is able to search a dictionary
honestly don't know where to start + cant find any example's online
@native tide if you can't use js at all... session data it is! take your pick -- store the session state on the client itself, or retrieve the state from somewhere else for the session identifier
@timber dove just flask? or will you be using javascript on the frontend? doing this purely in flask/python would require a page load to POST the search input text and get back a result. not ideal. also how large is this dictionary? shouldnt be necessary really to "search" through it unless it's massive or youre doing partial matches or something
meanwhile it's rather simple to get this working in a nice intuitive way (filtering results on each keystroke, etc) with some js
im happy to learn the js required to do it if needed
the dict has over 3k keys so there is quite alot of data to sift through
@junior cloak I mean I have nothing against js, but my frontend will be 99% django templates, not some js framework. So I really don't want to do any ajax requests and so on.
My idea is that session variables are easily manipulated and I'd have to do a lot of double checking on each page load/each step to see if it hasn't changed, if it still points to valid services and valid free times. Now if I only use some unique session id variable - the problem kinda goes away, right? Or maybe I'm not seeing something?
@timber dove if you are passing your dictionary to a template in flask, then you should search for info on passing your python dictionary to js. And after that there are a lot of examples of simple js search functionality.
oh alright i'll look into that
thanks
well my dict is pulled straight from a JSON anyway, so i hope it's not too hard
another option is to create an endpoint in flask that would return json data and use ajax request in the frontend to get the data to js directly
yeah i'd have it hit an endpoint on every keystroke and return the updated search results that will autofill on the client
or if the file size of the dict isnt crazy just send the whole thing to the client. you can do live filtering with something like vuejs in minutes
hmm, this might be abit out of my knowledge area. Any idea's on where to start?
(or fetch it from endpoint on first search, etc. i'd use an api endpoint but some dont like the load on the server for doing it on keystroke like that and it may be more complex if there isnt actually that much data to sift through)
yeah if there isn't too much data - just send the whole thing and filter with each key stroke
- endpoint in flask that returns json data
- js function that fetches data by hitting that endpoint
- js function that filters your data set with each key stroke
There a a lot of examples for any of these tasks π
in your situation yes, in the coresponding template
right thanks
@timber dove here's an example of vuejs searching through 4000 items as you type with <30 lines of js: https://jsfiddle.net/dkhollister/d52c3zyt/22/
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
(this is currently fetching the json file up front -- about 250k -- but could just as easily be an endpoint that returns the search results if its complicated enough)
thanks appreciate it
@native tide js just allows use of localstorage, which is great for storing state. otherwise you can store the entire state in a session cookie. the data will be encrypted on the client and not easily manipulated at all
assuming it can easily fit in a little dictionary or whatever structure
@junior cloak sorry to bother you, but i cannot wrap my head around your jsfiddle, ive tried to figure it out
i even tried loading another json file into it and trying to change a few variables, but im lost
any chance you could change some of the variables, so i could follow a bit eeasier. For eg the phrase "videos" is in it alot
ty in advanced if you could
@junior cloak a session cookie is something to think about. Thank you!
@timber dove method fetchVideos performs the request of getting the data and puts its results in a variable called videos. It's your data set
if you don't know any js, then it will be really hard to understand what is going on
yeah i dont, i'll keep trying to understand it thanks
trying to figure out return this.videos.filter(v => v.title.toLowerCase().indexOf(this.query) >= 0)
part
this.videos is our data set, right? Basicaly a list of song titles and such. So we perform a filter on it which checks if the song title contains what you entered in the search bar. indexOf returns the index of the string in a title. Let's say you have a title HELLO and input B in the search bar. B is not part of HELLO string, so the result will be -1 (if I recall correctly) or "not found" in human words. If you search for H the result will be 0 (first element in the string) and so on.
You should really learn the basics of js and after that learn a bit about vuejs.
it will come in handy anyway, you can't run away from JS in todays world π
yeah true, thanks
no problem π it can really be very hard to wrap your head around many concepts in web dev when you are a beginner. It's very important to fully understand your problem so you can narrow it down to small steps.
yeah vue is easier than alternatives but if you have done very little js at all it would be tricky. i just gave it as an example, since that type of ui/experience is more what users expect from search these days. it could similarly be done with plain js or jquery or anything
and yeah in my dataset it was just a big array of youtube data, objects with keys "id" and "title" and the function just searched the titles
(you can also ignore all of this and do it purely in python and not bother with js -- itll just require page loads to return results and such)
or you could look at something like List.js
but then again, with no understanding of js it will be hard to start
yes
@timber dove if this is all too much for this for now, you can set the js aside, do it static with python. form with text input that makes a GET/POST to flask, get the value from the text input, search through your dict however you want, return the rendered results in a template
thanks, i'll try and work out this js
anyone know of any js markdown renderers that allow for custom syntax?
can someone possibly help me who understands chrome webdriver
depends on your question
that sounds like it'd probably be breaking terms of service, sorry
@autumn bobcat it dosent break the tos of yandex
Nothing says that creating box wont do anything
in django, is it bad practice to import models from other apps? they are supposed to be independent right?
wouldve sworn i saw a channels question here a sec ago
@zealous igloo there are definitely times when you need to do this, and it's fine. just don't overdo it or have circular imports. you can use get_model if you need a model from another app that's causing you issues to import
oh okay thakns that makes sense. I did have a channels questions yesterday here but i think i figured it out i want to try out this one method
i'd probably avoid saving them to the db immediately
oh how come?
channels are asynchronous, fast, and lightweight
the django orm is... not
if you need to save messages from channels, do it in batches, or in a different thread, something like that
store them locally and then every few min flush them to the db in the background or something
(or just use redis)
i think if you want to save tons of your channels messages you may be using the wrong thing
oh yeah id dint think about how the DJango ORM is slow
so would makin a messages model be inefficeint?
what is your use-case here
i kidna am trying to work on something inspired by discord and i want to have the same mulitple server and channels wehre u can message functionality
i'm only understanding part of that
you can have a lot of different things react in response to a channel message
without needing to save anything
but i want hte user to be able to go back and see the messages
oh i think i get it, you want to have chat rooms that are different
yes
ahhh okay
yeyeye
so yeah, you can do this, but you have to be careful because of performance and i'm not sure how well-seasoned you are with async programming
this is really new to me i knwo multithreading and the whole time i thought they similar but not really
yeah they are not the same
so to access the database at all from inside channels context, you need to run all db commands through the helper function database_sync_to_async()
So would it be efficient if I did create models for messages but waited after certain amount of time to store them in the DB?
Oh so that letβs me store data asynchronosuly?
it lets you run django model commands while in something that is async
you wrap the function you would've done normally inside that helper
it doesnt magically make everything async, but it does a very common way of getting around this issue, which is running the non-async stuff in a separate thread so that it doesnt block the current thread
so you can do that.
so you want the chat history to be stored forever?
well i havent planned that far yet but obivsuoly if that channel is deleted i would wanna remove the caht history or maybe i would do a system where after a year it is deleted i don't know exactly yet
probably forever unless the channel is deleted
so, channels does have a background task / worker implementation
in channel layers.
that may be a good place to store the messages
oh okay yeah im reading on it now
eh, it's probably better to just store them in-place without blocking using that sync_to_async function
oh so not doing the layers might be better?
i mean youll want to use channel layers in general to communicate between stuff
but you dont necessarily need to save the messages by sending them to the background worker. saving them to the db async should be alright. test performance out
oh okay i will
i dont know how much you know about redis
oh yeah i dont even get the point of it, does it just store the messages while teh two people are interacting and once both users leave the page redis flushes out all the messages?
is redis something that can be used in productoin?
as far as im concerned it just seems like anotehr nosql database
redis is used in production in pretty much everything these days, for something
thast what it seems like i thoguth it was only used because it is easy to implement and they wanted to do it for hte sake of hte tutorial
or multiple things. it's what controls most websocket/chat room type stuff, it's likely where your user session is stored for some site youre logged into, cached content
which tutorial? i was talking about redis just as an alternative to the db as a place to store messages
@sudden yoke creating bots is almost universally against the ToS for a site, so i'd rather not take chances, sorry
oh the django channelss tutorail
oh yeah i see it now. great
so u would suggest using redis to permanently store the messages?
not the postgresql i am using
redis can save/retreive things far faster than anything else can. not even close
milllions of things per second
it does this because initially it isnt persistent. redis data is stored in memory and persists to disk every few minutes or whenever it can
so if you reboot the machine it's possible to lose a couple min of data if you didnt tell it to persist first
also you dont want to save so much data that it cant fit in memory at once because redis needs to be able to do that
so eventually would i have to delet some messageS?
and also just so in my consumer file where i receive the messages would i use some commands that interact with the redis database and i tell it to store the messages?
well, probably not. depends on how many
on one of my things i'm storing 11 million redis keys currently and total memory usage is around 1.5gb
holy heck thats good
but actually
for your purposes you could just try storing the messages in the db and see how it does
if you use the async helper properly it shouldnt block, so it would only become a potential issue if you are getting swamped with messages
if your thing becomes super popular or whatever haha
lol that would be a nice problem to have
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
username = text_data_json['user']
messageMod = Message(content=message, author=username)
messageMod.save()
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
but using those helpers (theres docs on db access in the channels documentation)
does this look like i am on the write path?
i forogt to establish a many to one relatinoship between the channel and messages but i just wanted to knwo if this general strucutre seems liek it'll work
well that isnt wrapped in the sync_to_async i mentioned
oh yeah i was going to add the sync to async i did this before we were talking
i'll work on implementing that now
thank you for taking the time to answer my quetsions
@zealous igloo so if you wanted to save them from your consumer, youd do something like this: ```python
class YourConsumer:
@database_sync_to_async
def store_message(self, **data):
record = Message(**data)
record.save()
async def receive(self, text_data):
msg_data = json.loads(text_data)
await self.store_message(**msg_data)
dont do the actual saving in your receive function. make a method for it in your consumer, with the async helper
then execute it from receive and be sure to await it
(also i would definitely save the messages after you have sent them to the group)
oh okay so after
just cuiours i think i kinda have an idea of the async await but im wondering how come store_messages isn't asynchronous?
the decorator above it is making it asynchronous
this is a weird thing and this isnt how that many things will work
the django orm is not asynchronous
so you cant execute its commands async. but you can wrap the entire function where it does whatever it needs to do in that helper and itll run it in a separate thread
as far as your django models are concerned, they have no idea, and it runs synchronously still
but it does so in a separate thread, i.e. it wont block your thread. and that trick makes it think it's actually async so you need to await it
this is all just hilarious tooling to help us through the awkward period we're in now where async is so awesome but tons of major things you need dont support it
haha yeahhh i see what u mean
under the hood, database_sync_to_async is likely taking the entire function underneath it and running it inside asyncio's loop.run_in_executor()
which is the de facto way to run blocking/sync tasks in another thread while not blocking and while making asyncio thing it's async
so yeah it should work fine, reevaluate things as you grow or whatever
for the store_message(**msg_data) i see that you have it accept keyword arguments but at what point am i supposed to code input the arugments like author=joe, content=message kinda thing?
i just wrote the function that way
dont worry about that part, do whatever you were doing
it could just as easily be store_message(author, content)
oh oh okay i see
**kwargs is just nice to use sometimes to save work if youre just using a dict with the same structure
oh okay so thats when u use it i see
just cuirous this is a little unrelated but still kinda, i was looking for hosting providers to potentially host this site but so many just either don't support or have a lot more complications when it comes to the django ASGI application, what do u use?
if you have a dict d = {"user": "dkh", "message": "hello!"} and you pass it to a function via some_function(**d), that's equivalent to if you had done some_function(user="dkh", message="hello")
ohhoh so kwargs can be for passing dictionaries with the parameters equal to hte value
yes
as well as the reverse, turning a bunch of keyword arguments into a single dictionary
you can also define a functions arguments like def some_func(name, *, user, message)
the * before user and message means that user and message must be keyword arguments and not be misinterpretted as positional arguments
ohhh must be keywrod okay i see
so you can't accidentally just pass some_func('some name', 'i passed in', 'the wrong data'). without the * then user would now equal "i passed in", message would be "the wrong data" etc
oh yeah it would all be mixed up
putting a * beforehand makes that mistake not possible
the only positional argument is 'name' and the other 2 arguemnts must be keyword args
anwyays this should be good
oh hosting. uhh
for peace of mind and ease, i say heroku
their free tier will get you django, postgres, and redis working while you build this thing
and no server nonsense, you just push to heroku with git push
oh yeah i was thinking heroku but just for like produion just curious waht would u do?
what do u use i mean
once you go live youll have to pay like $7 for a production worker
whats aproduction worker?
haha well, im not running django anywhere actually. tons of python though and especially async python
i use heroku during development and then just pay for it if the thing is pretty low-volume
for the big thing i work on it's on many aws servers and many containers, scaling up and down all the time
not recommended for this
heroku is fantastic, the only problem with heroku is it can get really expensive if you build a really big thing on it
a production worker is just... when you use the heroku free tier, the worker its using to run django is slower and has less memory and also spins down if it hasnt been used for i think an hour
paying them $7 is the first tier to remove limitations and be more comfortable letting it loose to the public
but the free tier is great for during dev. it's really just that 'idle time' thing that gets annoying enough that you cant actually deploy it to the world
it would be fast enough otherwise. and seriously theres nothing nicer than just running git push heroku master and having your app get built and deployed. otherwise you have to deal with setting up the ubuntu servers and nginx and gunicorn and monitoring them and securing them and creating some deploy scripts or something
one day you can leave heroku and do it the complicated ways if you need to but youll have time to grow and learn those things
oh wow yeah that makes lotta sense
i have several things that live on heroku in produciton permanently
it is by no means a poor system, it's great, it just gets costly if you stay there forever and now have a massive project
so liek with the channels i always have to use this command $ docker run -p 6379:6379 -d redis:2.8
with heroku would i not have to do that?
you are just doing that because you dont have redis on your computer otherwise
i pip installed channels_redis so wouldn't i have it?
you probably do that for postgres too
no not for postgres
what do you use to manage your pip requirements?
pipenv? just a requirements.txt file?
idk what u mean by manage sorry i just do pip3 install whatever
do you not use a virtual environment
oh i do sometimes like the visual studio starts it for me but not everytime, is it that important?
extremely.
one of the most important things to figure out when doing any python apps
if you just pip3 install whatever on your computer it's likely installing it system-wide
you have no idea what pip dependencies are needed for just your app
you can find out what pip packages you have installed py running pip freeze but you will see if you do this that it has tons of stuff unrelated to your app. system stuff, stuff that was already installed, stuff for other python apps you have, etc
at one point i had to use auto-py-to-exe to create python executables and it was a pain finding tthose libraries i pip installed, would virutal evnrinometns save me a lot of headache iwith stuf like that?
oh
this is a totally separate thing
this is just
so your django app that youre doing now, if you had to move it to another computer and just run it
how would you know which pip packages to install? you dont really. unless you basically just remember them in you rhead because it's just django and a couple things haha
oh yeah i just run the thing like a coupel of times and it'll say u are missing this librayr or that library
so after a couple of pip installs i am ready to run
lol yeah not a good solution
so when starting a new project, always make a new virtualenv
python3 -m venv venv inside the folder where you are going to have your app
that runs the venv command and creates an environment called venv in that folder
then you do source venv/bin/activate when you work on your project and you will be working in a clean slate
oh okay clean slate that sounds great
(to make all this less annoying you can install pipenv globally and then use that from then on)
if you use pipenv, it'll spit out a file called Pipfile whenever you install dependencies. itll keep track of what your app needs. when you push to heroku, heroku reads that file to know what to install
you can do the same thing manually with the venv but the command there is pip freeze > requirements.txt, which spits out a requirements.txt file that includes all your pip packages
(thus you really want it to just spit out the ones your app needs, not that are on your computer.) likewise heroku will read that file if it exists and install those packages for you
oh wow okay so heroku is that convenient, i see why now a virtualenv so important
thanks man i appreiciate all this
How could I create a user account for django via a 3rd party
3rd party application ^
application as in library?
No, itβs a java application
Also using djongo for mongodb
Rather. I could create a view that takes a token and allows the user to set the password/email
but I would still need a way to talk between applications
Rather. I could create a view that takes a token and allows the user to set the password/email
is that not the exact solution you want? java app sends an http request to an api endpoint which is recieved by the django app
Yeah idk I just kinda reworded it
How could I go about this?
I'm not very experienced with apis
I got http://127.0.0.1:8000/api/v1 to work, but how can i block so only post requests can see the page
How do you get Django to work on Atom Text editor?? And do you need Python 2 to run Django?
Django works perfect with python 3, python 2 is at its end of life so you should not make anything new with it.
what do you mean by getting it to work with atom? @frail yew ?
@frail yew you just do the normal django start project thing and it creates a direcotyr and on atom u just add that direcotyr as a proejct folder and u ye
Just open your django project folder with atom and that's it @frail yew
So i recently found out that u can use python for backend, what would be the best way to kick things off
I know a fair bit of html & css
If you hate yourself, use flask
otherwise, if you hate yourself, use Django
Learn Django in this video by following along as I show you how to build a simple hello world app and then a guestbook app that uses the templates, models, a...
it's a start
And if you don't hate yourself, use language that has tools and community based around web dev
I'd start with django for starting out
then move into flask or web2py
as much as I hate javascript, I'd rather use node.js than ever touch django or flask again
For real?
Yes.
But i'd rather learn python in general, i do have some experience with python
Then use django
Why not flask?
in flask you reinvent the wheel
^
but if you want to build your own webserver
then use flask I guess
depends on how low you want to go
django has some stuff pre installed
like database managment
Which is better for a guy just getting into backend
Django
I'd say django. It gets you right into backend
You can build something
not having to worry about other stuff
and if you care how it works, then you learn about it as you go
It's great for making REST APIs and database stuff
This is what a mate quoted about flask
Hmm ok
What are you trying to do with backend?
Just learn it for full stack? or make something specific
That's a good question, and in fact, I'd say, if you want to build something serious, as opposed to learning about backend and Python
just pick another language, honestly
If he wants to use python, let him
I haven't tried Erlang but it sounds fun
maybe he doesn't know js good enough
Yeah i dont
Python is fine for backend
I've used it numerous times
Alright then stay on Python for now
Later on, don't limit yourself to "I don't know x language if I want to do y"
Its for fullstack i guess
Learn x language.
I've got html & css down
Thats a start.
Mhm
Django docs are great
And im gonna continue python in general in future
So i thought backend with python would lend me more experience
In a general perspective
Do you know enough python for basic apps
If you have a decent knowledge of python django should be easy
Oh and I mean, there's nothing wrong with it, it just is slightly more painful as less people work with Python for that kinda thing
part of discord backend is in Python
Ah cool
Ok so
Isnt it the same afterall no matter what framework u use
I mean isnt the code structure and functionalities the same for either framework
A little, but django has a different way of handling things
I was literally just reading that article xD
lol
flask is awesome
web2py
i have been using flask and i have to say i am more than satisfied
very lightweight
flask projects are like legos
you can build whatever you want and you can add stuff as you progress
what are some good flask tutorials ? know only of the two flask mega tutroial books
corey schafer has good youtube tutorial series
@rotund lake I also recommend Flask for simplicity; I have no webdev experience but I needed to use it to set up a Slack bot and it went very smoothly
The fact that it's a little less "compartmentalized" for lack of a better term than Django was something I liked
is webpack absolute garbage, or am i just using it wrong?
i feel like if everyone likes it, i must be using it wrong
@native tide they asked what people recommended, so people are giving recommendations
Hi all! Is there someone who might have the chance to help me with an issue using docker, django, and some failed migrations that only happen in the container
Any Django bakery users? Trying to figure out how to get the build to append the md5 hash.
I think it works just fine. I had a sass preprocessor that wasn't running (had a script that was manually calling it that I forgot about) and once I ran that things were fine. (Hit some Windows path issues that I don't believe are easily resolvable but that's another story)
In Django, i have a charfield with a 50 characters maximum length.
I want it to write second line after the 25th character.
How can do i that?
By second line do you mean just you always want a \n in character 25 ?
I feel like more info of what you're trying to do is needed.
@deft aurora
Similar to this i guess.
Assume i have a commet section, i want it to write second line after the end of the first line.
But end of the line is 25th character
I guess it depends on a lot of factors. But for a comment section in how I'm thinking, I would probably do the wrapping on the client
Depends on how the form (or however data is coming in) is structured
But to directly answer, you can implement one of the clean methods on your Model and force it by overriding save()
But my kneejerk says that's probably not what you want
@deft aurora
I wrote it more clearly:
In Django, i have aCharField named as mini_content
mini_content = models.CharField(max_length=50)
It takes 50 characters, i want to show this field in somewhere in my website.
However i want it to be shown as:
NdjfjfΔ±dΔ±eoeodΔ±dndndΔ± KdjdjdkdoekenejeΔ±
Instead of:
jfjdjdnendldpdpemwnkspspsnejs
Oh okay. So you don't want to persist it with the newline?
What are you using for display? Django template or something else?
Django template
In html code, i can show it with:
{{ mini_count}}
But just in the same line
yeah. Splitting on characters in general gets really tricky.
Multibyte characters make that complicated.
If it's really just something to improve aesthetics, i would consider using css to limit the width of the element rendered.
Is the actual 25th character important? (Sorry for 100 questions :))
No i don't know the limit yet, i have to try π
I thing this will work:
if len(result) > 25: result = result[:25] + "<br>" + result[25:]
Hmm yeah that may work. Assuming single byte chars
If you're rendering the template from a view, you can do your splitting in the view function/class and then provide two lines to the template
But I would really consider doing a little css. <div style="max-width: 20%;"> {{ your_string }}</div>
Css will allow you also to specify if you want to break on a word or absolutely.
I don't know any CSS unfortunely
Well if you are willing to try it, I would take as a starter just opening dev tools in your browser, finding your element and then hacking at the css with max-width until you're happy. Then you just set that on some style attribute of your <div> (or whatever html element). That would probably still be easier than trying to find a safe way to split a python string which is utf8 by default.
About what jaycle said, I suggest making a css file apart from the HTML code, linking it in the head by using:
<link rel="stylesheet" href="syle.css"/>
```then add a class or id to your div ```html
<div id="optional_id" class="optional_class"></div>
```Then configure your class at the CSS file :
```css
#optional_id.optional_class {
max-width=x;
}
Yeah totally. But if Engineer's looking for shortest path to wrapping a long line...
I know it might be too much if you are only modifying it once. Just if he wants to make more webpages that share a similar style, one CSS file can be linked more than once so it helps
+π―
if i wanna be a django developer and know how to use the ORM prety well is there even any point in learning SQL?
I'd say so. For most jobs even at entry level it will end up coming up in an interview. But beyond that, I think it comes in handy as you need to look at your data from different view points. You won't always be doing greenfield development and understanding some complex model relationships sometimes just gets easier when doing some JOIN and WHERE statements.
Now I would say you can get away without a deep knowledge for a while, but it's a hole that I think is worth filling in once you have the time. All abstractions leak and knowing how a queryset becomes a query and then translates into an execution plan and the implications will one day be valuable. But "one day" may not be today.
ohh okay yeah i see what u mean thanks
so its kinda like how with programming langauges it's good to just knwo the lower level stuff just so u knwo what's going on even if u don't necessarly plan on using it
How to put a navigation bar on my django website which connects to another page like When user press on "about" it goes to about page
Every time i put a navigation bar on my django project it gives an error
you could start by telling us what the error says
Py user = models.OneToOneField('User', on_delete=models.CASCADE)
so I'm trying to makemigrate this, but I get this error
ERRORS:
personal.accounts.user: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract.
personal.accounts.user: (fields.E307) The field personal.accounts.user was declared with a lazy reference to 'personal.user', but app 'personal' doesn't provide model 'user'.
it is django btw
From memory here, but I think you need to import the django auth user model
then reference it not by string
from django.contrib.auth.models import User ?
(unless you are using your own User model?
remove string reference?
Py user = models.OneToOneField(User, on_delete=models.CASCADE) # no string
Now that's what is called experience
Can I run a python script on a web host?
depends on the host
Did you do the official tutorial?
I mean it tells you what a model is, shows you a few field types, etc. After that you can browse the official documentation and learn more.
@rigid rover which host
@vagrant adder AwardHost
vm or vps
Working with django, wondering if there's a good way to extend a models.Model class in another program, without requiring that the new child class be associated with an app_label
my use case is a bit strange here, but basically I have a django model that stores variables for objects that can be create/read/update/delete in a separate game program
help
im pretty much starting off with django
and i keep getting this goddamn error
TypeError: __init__() takes 1 positional argument but 2 were given
i pretty much follow this: https://docs.djangoproject.com/en/2.2/intro/tutorial01/
but i keep getting it
@native tide it does π But I know that learning from official documentation can be too hard if you are a beginner. If that is the case, there are a lot of project tutorials out there both in text and/or video format. They usually show more sophisticated models, usualy with relationships etc.
it's easy to find tutorials when you are a beginner. It gets harder when you are not a total beginner any more but far from an advanced user. You are on your own then π
Traceback (most recent call last):
File "web.py", line 2, in <module>
from flask_login import *
ModuleNotFoundError: No module named 'flask_login.0'
@tough star just a guess, but is there any chance that the package is not installed or installed in a wrong environment?
I'm on windows, i have installed the module with pip install flask_login
@tough star did you try importing only what you need, not *?
sorry, I don't have much experience with flask. Are you following a tutorial? Are you sure LoginForm is a part of flask-login in a version you are using?
I'm following this: https://flask-login.readthedocs.io/en/latest/#installation
@tough star as I understand, the LoginForm is not a part of flask-login, but of WTForms
"# Here we use a class of some kind to represent and validate our
# client-side form data. For example, WTForms is a library that will
# handle this for us, and we use a custom LoginForm to validate."
but I might be wrong, so probably wait for smarter people
Anyone that can help me with a quick question on Flask.
I've set up a nginx server which runs a flask framework, but I can't seem to make a folder on the "ftp" server and just downloading the files from that folder through http, because flask thinks of "folders" as app.route. Any solutions for this?
you want static files
http://flask.pocoo.org/docs/1.0/tutorial/static/
you could also use app.route to proxy the correct directory using os.path
Is there any full Django course pdf?
I recommend the official tutorial first; it's excellent (the documentation of Django is very good), but I'm not aware of any totally free pdf-books about Django that serve as a full introduction course
Could someone help me with css
my navbar keeps updating like https://gyazo.com/59e74de350ac86deabd9324bdc35bda2
fixed it
@native tide Can you elaborate as to how you fixed it so others with the same issue can know how?
tbh
idk
i just recoded it all
can someone explain to me what Progressive Enhancement? I know somewhat.......
The whole idea
Like
I don't understand why that is necessery
I mean everysingle web browser understands css
now days
and I don't understand what it really does.
like does it remove java script or what?
like what I dont understand why would a webbrowser, not understand some css?
it's not about anything in particular
WHat is it then?
Consider a website with a lot of bells and whistles, images, interactive elements, scripts, videos
It would need a lot of bandwidth and probably a lot of browser support as well
Instead of serving it all at once, quite possibly overwhelming low-bandwidth users or users on restricted (mobile?) browsers, you start with a "base layer" with the bare essentials
After that, you add on the more advanced, but heavier layers
This means that even a text-based browser (or a search-engine spider/crawler) can understand the basic website and more complete browsers can get the full functionality with all the nice details, graphics, and so on
basicaly
@patent cobalt it is like a game
There are low medium high adanced
graphic
if you have a bad graphic card
then
it is low graphic
the better connection or computer you have the better detail will you get of the website
Yes, but instead of relying on settings you communicate upfront, you always start with the basic structure/content (html) and the bare necessary functionality (js/css). In addition, you provide more advanced functionality and/or layout by including them using external files/links. The basic content/usage must not rely on these external resources so that if they were disabled (for whatever reason), the basic usage of the page still works.
ok I get it
but
somedude said I can use that for button
So the thing is I use ajax for my like button. and whenever I like the button I have to reload to get unlike button and some dude said I can use that to fix it
something seriously ugly is going on with the top borders of that image to the left
this is most certainly the reason
but i dont know how to fix it
maybe if i wrap img.imagething
nvm margin helped, i asked this chat just to find it out faster, sorry ^^
Why this code gives an error
<a class="navbar-brand mr-4" href="{% url 'core-index' %}">OverLoad</a>
it says ```
Reverse for 'core-index' not found. 'core-index' is not a valid view function or pattern name.
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="{% url 'core-index' %}">OverLoad</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'core-index' %}">Home</a>
<a class="nav-item nav-link" href="{% url 'core-about' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
<a class="nav-item nav-link" href="#">Login</a>
<a class="nav-item nav-link" href="#">Register</a>
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% block content %}{% endblock %}
</div>
</div>
</div>
</div>
</main>
Here is the code
Please mention me if someone have a solution
with flask i realise you can have a custom url using the @app.route("/<x>"), is there a way to parse a value from the html page itself (like a search result becomes that value)
@late gale Try replace href="{% url 'core-index' %}" with href="{{url_for('route function name')}}"
@tough star
Could not parse the remainder: '('route function name')' from 'url_for('route function name')'
You need to replace "route function name" with the name of the @app.route('/example') function
@late gale
Could not parse the remainder: '('core-index')' from 'redirect('core-index')'
@tough star
oh wait
@deft aurora
Thanks for the suggestion you made here
But I would really consider doing a little css. <div style="max-width: 20%;"> {{ your_string }}</div> ```
Well it works however when i minimize the screen it doesn't work correctly.
How can i fix it
This is because when i minimize the screen, max width also changes.
So it disables bootstrap and the objects does not seem as they should be
You can set a min-width by pixels if you wanted to
like <div style="max-width: 20%; min-width: 100px"> or something
It seems like i solved it by writing:
width:250px
if i have a react app and a flask api that serves data for the react app, what do i need to do to have them running on the same server and able to communicate?
would that be nginx configuration?
when i make the api call i get a CORS error which makes sense but ive never done this so not sure how to configure it correctly..
@solid cave Are you do doing this in dev?
yes
So you've got two dev servers
one dev server
Not running flask in dev?
sorry, thought you meant a dev environment in general
one host, two dev servers
npm run start for the react app and flask run [options] for the flask api
cool. Yeah if you're using CRA you can specify the proxy to the backend
then you can reach your api with relative paths
didnt use CRA, i guess unfortunately
Nah, it's still possible. I just can't remember the config
would it be a plugin for webpack?
just look up proxy for webpack dev server
You bet.
I'm guessing you had somethign like localhost:8000/api/resource in your react fetch call?
yep
i see it here
gonna try this out
damn i keep getting err_connection_refused on my request
GET http://localhost:1234/api/tld-expirations is the request, this is how I call it in the component
const url = 'http://localhost:1234/api/tld-expirations';
const [result, error, state] = usePromise(
() => fetch(url).then(response => console.log(response)),
[url]
);
then this is the webpack config
proxy: {
'/api': {
target: 'http://localhost:1234',
pathRewrite: { '^/api': ''}
}
}
oof
i think i know why
was hoping it was because it was sending as FETCH but adding that as an acceptable method didnt fix the issue.. sad
In Django, how can i use a custom Log In theme, without using crispy_forms?
For Example, i want to use this login theme:
https://bootsnipp.com/snippets/vl4R7
I can take the html code but how can i log in?
High quality Bootstrap 4.1.1 Snippet by SamimOnline. Share yours today!
I couldn't find any information on that neither did i understand
<div class="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="posts.html">Posts</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
It gives an error
everytime i click on any of them it says this
admin/
about/ [name='About Page']
posts/ [name='Posts']
contact/ [name='Contact']
The current path, index.html, didn't match any of these
Anyone?
I just want to add navigation bar in Django but I can't
I am using Django btw
I see the paths admin/. about/ and so on
so i dont want Flask answers
urlpatterns = [
path('', views.index, name=''),
path('about/', views.about, name = 'About Page'),
path('posts/', views.posts, name = 'Posts'),
path('contact/', views.contact, name = 'Contact'),
]
There
There's no /index.html path in there
but i want index.html to be the main page without typing example.com/index
You've set the root path to the views.index
So, try it just with the root of the website, not with any specific file after it
You don't type in the actual name of the template, but Django will serve the rendered template if you enter the specified path
You already did:
path('', views.index, name=''),
yes
i am actually running on the local server
with python manage.py runserver?
yup
um actually nothing is solved
i actually did
Did you follow the official tutorial?
def index(request):
return render(request , "Core/index.html")
@native tide
then make a url path for /
path('', views.home, name='home'),
@patent cobalt Every tutorial is using differ version of Django
What version are you using
You can select the version you want in the official documentation
2.X or 1.1
Try to go to localhost:8000
What does it say
Same error
Copy and paste it
It's just about/ not about.html
^
You've created an url pattern for about/
you don't need the file extensions
wait what -,-
Did you hardcode your links into your file?
how to do so then
for hrefs you can do {% url 'about page' %}
i will check now
Yes, let Django handle the URLs
new type of error
About Page
Yes
I wrote page instead of Page
Finally It works
I tried 2 days
Thank you!
You too @patent cobalt
if you ever want to change the path django makes it easy to handle urls
Yes
I also think the official tutorial in the docs is very good: https://docs.djangoproject.com/en/2.2/intro/
I still go back to it every now and then because I don't use Django a lot
actually try Django, I enjoy the support of the framework. Its so friendly
I don't really have a need for it, other than the back-end of PyDis
Yeah. It has a lot of useful features built directly into it
nice
@solid cave did you figure your issue out?
I think the issue (at least one of them) is you should be using fetch with relative url
If anyone has experience with Flask, i posted a question in help-5 that i'd be super appreciative to get some help on
with flask i realise you can have a custom url using the @app.route("/<x>"), is there a way to parse a value from the html page itself (like a search result becomes that value)
Yes, make the search box use a get request
sorry what do you mean by that
you can get http params from the request
from flask import request
request.args.get("query", "")
@timber dove
get request is an HTTP GET request
http has different types of requests that you can make to a server
GET and POST are the simplest
as their names suggest, GET gets something from the server and POST posts something to the server
in practice, they are quite similar, but the main difference is that you are allowed to send data with your request if you use POST whereas you cannot if you use GET
but GET will work in this case because you can encode parameters into the url
if im remembering my html right something like this should work
<form method="GET" action="/search">
<input type="text" name="q" placeholder="Enter search terms">
<input type="submit">
</form>
thanks, alrigjt i think im partially following, but have no idea on how id implement this
it will send something like url/search?q=some+search+terms
yeah its confusing at first how they connect together
the form will handle the url building thing for you automatically
when you press submit it will send this stuff to /search automatically
from flask you can do
from flask import request
@app.route("/search")
def search():
search_terms = request.args.get("q")
hmm, what exactly is the request.args.get("q") doing
request.args is a dictionary containing all the arguments that are in the URL
like /search?q=hello will make a dict like {"q": "hello"}
get is a method that you can do on dictionaries instead of the normal get syntax so you can handle the case where the key does not exist
right, so you also dont need to do @app.route("/<>") stuff
just "search" is proficient?
/search sorry, mb
my current search uses jquery and doesnt have a submit button (as it minimises results as i type), so i would like the page to be loaded when i click on the result
you get make a get request with jquery ajax
to simulate the submit button press
wait so once the user clicks something the result is already determined?
well for example there are a list of items, that as i search the list becomes smaller, then when the user clicks on one of the item's on the list i would like it to take you to a page dedicated to that item
ok so you dont actually need a search then?
possibly im looking at it wrong then, maybe
are you trying to make the dropdown search right now?
not exactly, that's pretty much sorted, currently im just trying to figure out how to have a dedicated page per item, without setting up a physical page per item
like where i use a basic item.html page and pass in the data specific to that item
oh probably jinja/flask templates
jinja is absolutely incredible
you can do programming inside of an html page, like with loops, if statements, etc
yeah i have used jinja a bit, its just the idea of passing a result back to the python script so it know's what to set the url to
for some reason when i click each result it just takes me to /q or /a or /(random letter)
@app.route("/<product_name>")
def product_details(product_name):
return render_template('products.html', products = products, price_data = price_data, product_name ='x' )
{% for key, item in names.items()%}
<div class=divv>
<li ><a href="/{{ item }}" class='icons'>{{key}} </a></li>
</div>
{% endfor %}
is the jinja for displaying all the items in the list, where i wanted the key to be whats displayed and the value to be the href
but i feel like that @ app.route above is useless as these two dont coincide at all
lol this poor guy named app keeps getting pinged
haha yea
ok well you passed the product_name as "x" in the return statement, was that intentional
well i didnt know what to put there
since i dont know how to get the value that jinja passes back to there
im confused, i assume you meant to say product_name=product_name?
i dont know for sure though
i guess, but wouldnt product_name need to be defined in the py script?
it was passed to the function as a parameter right
and i define product_name in jinja?
well ive got it loading the right /product
but i dont have an @ app.route for it
Welcome to the Django Interview Video series! Start your interview process here (Hopefully, you can figure it out): https://cryptopotluck.com/post/post/41/ C...
anyone using gmail api
managed to get pubsub working with gcp
but trying to figure out how to get the recent messages
using historyid
Welcome to the Django Interview Video series! Start your interview process here (Hopefully, you can figure it out): https://cryptopotluck.com/post/post/41/ C...
when deploying django to production, forcing https broke my ajax post requests?
anyone ever experience this? been searching for reference to this with little result.
@native tide what error are you getting?
500
i mean obv if i run in debug mode i'd get more detailed error, but its returning a 500, so it worked with http, now its not working when i force https in production
and now my ajax throwing error
at Object.complete (main.min.js:7)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith (jquery-1.11.0.min.js:2)
at x (jquery-1.11.0.min.js:4)
at XMLHttpRequest.b (jquery-1.11.0.min.js:4)```
not really sure what i did to other than force https, so i'm assuming thats causing the issue here
wait wut?
i'm not sure how tunneling is relevant here? this is an ajax post to django on the same server, i've got nginx with reverse proxy setup, the app is deployed with gunicorn
my issue has been resolved, was completely unrelated to ssl π
my logging wasnt outputting properly, once i adjusted that, i was able to pin point the issue and it was db related opposed to secure sockets
@deft aurora yes, the issue was with the url, needed to just be '/api/<addr>'
proxy worked correctly too, now just trying to figure out something unrelated and I should be able to link it up and wire 3 parts together
the exciting part is one step away
This may not be the right channel, but does anyone know if beutiful soup can parse out multiple pages of a website by links?
Page
RandomLinkA
RandomLinkB
...
Pagination << >>
Hello, little question, with Django, we need Python, HTML5 that's it ? I mean, any additional ?
if you want css
Thank you for the return
the minimum you need for django is python. html will structure your sites, css will make them pretty, js will make them interactive, and if you want, you can learn SQL (although django doesn't require that, and will handle it for you)
Django is python. Django just need python. A website based on django needs python, django, css, html, js(?), a wsgi server and a http server
Hi, In Django, can the session cookie be configured to exclude some url paths, I got an Angular app on base root of the domain and have /admin and /api endpoints, but when admin user is signed through Django admin, it messes my angular app token login :(.
Basically I need /api and / to be excluded from cookie based session
if the token is registered in js (local storage), it should be fine
@red condor you are referring to my cookie problem , right π ?
@tight shadow yep
@red condor ok then, well it's not working, if the admin user is signed, the authentication class is setting request.user the admin user when calling any /api view calls
Ol, so you can use the token authentication for the django part ?
Or, i think yiu can configure the js request (with axios or other) to not send the cookie session
(Sry about my bad english)
The token is authenticating fine, but if for some reason admin tries to login via /admin, and then goes back to the angular app, it's chaotic
@red condor so, you are suggesting to solve this on the frontend
@tight shadow yes it s a way
ok, I can remove the cookie in the request injector then
interceptor*
but that's one client π
@tight shadow when you have to request the api part, don t send the cookie session
I dont know about angular, but in vue.js, I have a session token saved in js (LocalStorage object). I just have to send the token in the header with axios
You can also configure your django rest framework authentication to only cache tokens (what is you django rest framework settings ?)
@red condor If I remove rest_framework.authentication.SessionAuthentication, I will not be able to use the API browser π
@tight shadow I recommend you to use the tokenAuthentication instead of SessionAuthentication https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
Django, API, REST, Authentication
but in fact, what is your app token login if you don t use the token authentication ?
@red condor If I remove it I can't login with API browser
@tight shadow You can, i only use the token authentication from my django rest framework backend
But you have to configure your login: the login should return the session cookie and the token in a context object or anything else. Or you have to create a specific login for the API
This doesn't solve your problem but it's a work around
@red condor ok I think this is needed : path('api-auth/', include('rest_framework.urls')), which activates login system and I disabled session logins
I think only in development login will be used, so this solves the issue
Any idea why my Javascript request with fetch ```js
const user = {
email: "test@hotmail.com",
username: "tester",
password: "password1"
}
const createPoint = "http://localhost:5000/user/register";
async function getToken() {
const res = await fetch(createPoint, {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(user)
})
return res
}
const promise = getToken();``` fails with `Response { type: "cors", url: "https://localhost:5001/user/register", redirected: true, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
Whiteboard.svelte:3:12
`
While my Postman request ```http
POST http://localhost:5000/user/register
Content-Type: application/json
{
"Email": "test@bob.com",
"Username": "bob123",
"Password": "bob123"
}``` works just fine?
what does python do in web development
backend
server side
soooo basically javascript
no not at all
βPython can be used to build server-side web applications. While a web framework is not required to build web apps, it's rare that developers would not use existing open source libraries to speed up their progress in getting their application working. ... Projects such as pyjs can compile from Python to JavaScript.β
javascript is usually frontend
can you set() a list within jinja?
I feel like two thirds of the problems I experience are due to syntax haha
This language needs double quotes only, this markup needs environment variables like {$this} while some need it like ${this}. Some can't have any space separations. Some need colons and some need equal signs. Some can't have dashes and some can't have hyphens.
@autumn bobcat node.js would like a word
@olive wharf i don't know JavaScript but are you missing semi colons
After const user and the async function
@wheat trellis re-read what i wrote
Usually implies normally,
But node.js isn't unusual or uncommon
It's like saying usually people drive on the left
@wheat trellis Javascript has implicit semicolons, works 90% of the time, but no it wasn't that.
Not quite sure what it was, but I got it working after tinkering with the server side cors settings and switching to Axios as the js lib to request
Tbh it's mostly the same as using : in python when using an ok editor
as it auto fill the closing bracket and you just press enter like in python
I love how people go "Python is stupid I can't see scope"
Then format their code exactly like python for readability except now they also have
{
}
;{{
;}
}
;{}
};{}
}{}; everywhere
:D
I need to do some deep learning on HTTP
I've been trying to learn a few different reverse proxies and I'm getting slammed by all this header stuff
CORS, X-forwarded*, trust this and that
Not intuitive stuff but devastating to get wrong when there's secrets behind it
I've given up on traefik though, it just seems poorly documented
I would argue most js is frontend
Welcome to the Django Interview Video series! Start your interview process here (Hopefully, you can figure it out): https://cryptopotluck.com/post/post/41/ C...
@wheat trellis good point about the {}
guys
Sup
Hi, how do I switch the email backend in Django to another backend when needed ? - For instance I got gmail and mailgun backend, in one API I want to send via the first and to later via the second backend.
ok, found it, need to pass the connection=backend
Welcome to the Django Interview Video series! Start your interview process here (Hopefully, you can figure it out): https://cryptopotluck.com/post/post/41/ C...
I have a flask site with a flask login's mail confirmation authentication. When I click on the link in the confirmation email, it says 404 Not Found
How I can fix?
show how are you mapping your URLs and how is the link sent to the confirmation email
@strong laurel Sorry, I didn't see the message, this is my code: https://paste.pythondiscord.com/qopunibowa.py
I haven't fix that yet.
what's the link that gets sent in the email?
Anyone decent with Javascript?
Maybe, depends on the question
What do you guys use for apollo ? is it graphene-django or ariadne ?
Hello mentors, me again need you help :)
I try find this answer a full week.
How i can get right url path in Django if i have next structure
a) /cat/subcat/prod
and
b) /cat/prod
if category include subcategory me need have get: a path
if category not include subcategory me need get: b path
I have def get_slug_list(self) and this give me right mapping in template
I use mptt if it is necessary to specify
models.py
from django.db import models
from ckeditor.fields import RichTextField
from mptt.models import MPTTModel, TreeForeignKey
import mptt
# Category
class Category(MPTTModel):
text_description = RichTextField(default='Underground')
name = models.CharField(unique=True, max_length=30, blank=None, null=False, default=None)
parent = TreeForeignKey('self', on_delete=models.PROTECT, null=True, blank=True, related_name='children' )
is_active = models.BooleanField(default=True)
slug = models.SlugField(unique=None, blank=None, default='')
class MPTTMeta:
order_insertion_by = ['name']
def get_slug_list(self):
try:
ancestors = self.get_ancestors(include_self=True)
except:
ancestors = []
else:
ancestors = [i.slug for i in ancestors]
slugs = []
for i in range(len(ancestors)):
slugs.append('/'.join(ancestors[:i + 1]))
return slugs
mptt.register(Category, order_insertion_by=['name'])
# Product
class Product(models.Model):
name = models.CharField(unique=True, max_length=30, blank=True, null=True, default=None)
price = models.DecimalField(max_digits=10, decimal_places=0, default=0)
category = models.ForeignKey(Category, blank=True, null=True, default=None, on_delete=models.PROTECT, related_name='cat')
But i don't have idea how i can get this url's in my views controller
example what me need, but this not work
def product(request, category_slug, product_slug):
prod = get_object_or_404(Product.objects.filter(is_active=True), slug=product_slug)
cat = get_object_or_404(Category.objects.filter(is_active=True), slug=category_slug)
return render(request, 'products/product_page/mangal_page.html', locals())
Because my urls.py get 3 parameter if urls as follow cat/subcat/prod
How i can create current path?
example:
path('<category_slug>/<product_slug>/', views.product, name='product')
and views.py i fetch only example, but i 100 times change this and this time i realize this like that:
urls.py
path('product/<slug:sluga>/<slug>/', views.product, name='product_url')
views.py
def product(request, sluga, slug):
prod = get_object_or_404(Product.objects.filter(is_active=True), slug=slug)
subcat = get_object_or_404(Category.objects.filter( is_active=True, children__isnull=True), slug=sluga)
cat = Category.objects.filter(is_active=True, slug=sluga).get_descendants(include_self=False)
and i have urls:
product/cat/prod - if category not include subcategory
and
product/subcat/prod - if category include subcategory
but I don't really like it.
I cut out from the examples a part of the code, which in my opinion cannot influence the solution of the problem, so as not to spam, if additional information is needed, I will provide it.
please help, I will be very grateful
Is there any way to download a template and connect it to my django project
Hello
@late gale may i help u? ΩΩΩΩΩΩΩΩΩΩΩΩΩ
I believe that pages like search results page is using Java script to retrieve the search result and view them
and the js script Tells the server: "Hey server , i want the search results, give me them", server:"Ok ,take them"(like api)
my question is ,how to know the way the js script is requesting the data from the server
so my software can get it and parse it directly (instead of webscrapping and facing js rendered pages problem)
?
is anyone trying FULL apollo integration on top of python?
I'm having an issue with my flask app, it uses two database connections (flask sql alchemy), one of them through an ssh tunnel, this one is getting disconnected after a while with the following error: "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0".
Any ideas?
anyone from Ariadne ? how to do pagination in ariadne?
r u using flask or django? @gleaming herald
Any php devs
Having issue with install script and licence key developer is no longer active and the key seems to no longer work on the install?
this is python server XD
this is web-development though
But must be related to python π
In general, yes. Questions must be related to Python directly or, for topical channels, to related technologies used in a Python project. That's why html, css, and JS are in the list, because they are often used together with a Python web back-end like django or flask.
Questions unrelated to Python projects can be asked in off-topic, but there's probably more expertise in servers for that specific language and/or a general programming server
Fixed
does anyone know of a good web framework that doenst suck ass like Sanic or Flask
django?
Flask is awesome what are you talking about
Hi good people! Could anyone give me some feedback on this figure? Does it make sense to you? π
so I'm looking to put together a python mvc webapp, and have a gearbox quickstart project that runs on 127.0.0.1... but this isn't 2003, I'm doing the work on a DO droplet, and need to listen on an actual address. All the doc I've read says I can specify this in dev.cfg, and everyone has one... ...except me, heh. What gives?
I'd actually love to use flask to do this because it's obviously more flexible, but the lack of a uniform set of current and complete instructions to cross the finish line in possession of a skeletal mvc app with simple user auth really is keeping the learning curve steep
is anyone actually here? I heard this place was busy af with lots of cluefull people around...
The topical chat channels always move slower, since they're watch by a subset of our users and not everyone has invested in all topics/subfields of Python
one would expect a significant portion of those to be invested in web app dev?
anyway
know anything about python mvc frameworks?
@hushed kindle This channel is not meant for memes.
By the way, I've never used gearbox, but the documentation states that gearbox serve servers based on the configurations in the development.ini file, not a dev.cfg file
when restoring the session, do you just need to check the cookie or are there other things to check for? I'm using Sanic framework for python and this restores the session for now, but if I change the value of the cookie the session object is reinitialized so it breaks the code since request['session']['user'] dictionary isnt defined anymore
if request.cookies.get('session'): # Check if the cookie exists.
cursor = db.cursor()
cursor.execute("SELECT client_id FROM Sessions WHERE session_id='"+str(request.cookies['session'] + "'"))
result = cursor.fetchall()
if len(result) == 0: # If the session ID does not exist in the DB, then the cookie was cleared or it expired.
print("USER SESSION DOES NOT EXIST")
cursor.execute("INSERT INTO Sessions VALUES('{}', {})".format(str(request.cookies['session']), str(request['session']['user']['id'])))
print('saved.')
return response.json(request['session'])
else: # If the session ID exists in the table,
# Found the Session, Restore the User.
user_id = result[0][0]
cursor.execute("SELECT * FROM Users WHERE client_id=" + str(user_id))
result = cursor.fetchall()
cursor.close()
print(result)
if request['session']:
print('session exists.')
else:
print('no session exists.')
request['session']['user'] = {
'id': result[0][0],
'username':result[0][1],
'discrimnator':result[0][2]
}
return response.json(request['session'])```
i havent looked into OAUTH libraries yet but I just wanted to do this myself to see how everything works under the hood
Mentors somebody can help me with my questions on top?
How do I pass my user name from a request in "python socila auth" so that when the facebook complete is called to be able to use it my custom pipes ? My goal is in the SPA frontend to call python social connect url, using a token to authorize with my API, then API sets the request.user based on the token, but after that I want to send facebook in extra_data my current username or email, so that when auth_complete is called to have the username/email back, this way I can associate the user who needs account linking.
@patent cobalt sorry for the meme then ;)
FYI I ditched gearbox and revisited and debugged the issue I was encountering with the flask server.
I'm back to lurk and see if I can provide some assistance of the sort I was unable to obtain here yesterday π
Anyone had any experience with highcharts?
im trying to pass data from a dictionary, and im successfully doing it with a jinja for loop. but the chart only displays the data from the last loop. not each
@timber dove try to get your chart generation code inside the innermost of your loops (they are nested, amirite)
{% for key, value in products.items() %}
{% if value[0] == product_name %}
{% if value[1] == deat %}
{% set chart_sku = key %}
{% set chart_data = price_data[key]%}
{% set chart_brand = (value[0] + ' - ' + value[1]) %}
<div id="chart"></div>
{%endif%}
{%endif%}
{%endfor%}
followed by the script highcharts script
where the div should be calling the script right?
well as the script starts with
Highcharts.chart('chart', {
title: {```