#web-development

2 messages Β· Page 25 of 1

vagrant adder
#

can i see your code

#

@ancient zinc

zealous igloo
#

is it possible to create a jdango website wihout
using templates
like the html css and javascript is seperate from it

late gale
#

I cant put navigation bars in my django can someone help

#

everytime it says page not found

floral seal
#

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

opaque vigil
#

Guys

#

I wanted to ask about flask

#

Like styling the text, with bold, italic, etc...

#

Is there already made functions for this or i have to write them myself?

native tide
#

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

queen needle
#

@floral seal I'm sure you can, but that way you'd be violating the REST principles

#

POST is intrinsically a create

odd storm
#

is that not what's happening? as i understand it, the post is creating a user

zealous igloo
#

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?

stiff totem
#

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

north swift
#

what's the proper way to keep the database models out of the main .py file in a flask app?

vagrant adder
north swift
#

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

vagrant adder
#
db1.create_all()
db2.create_all()```
proper hinge
#

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

vagrant adder
#

What does cli have to do with gunicorn tho

native tide
#

are you loading json into it?

#

if so, that's probably your issue

proper hinge
#

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 πŸ‘

hushed burrow
#

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

gray star
#

is there something faster than django available for python?

vagrant adder
#

flask

patent cobalt
#

There are other microframeworks as well, such as Falcon, bottle, and I always forget the name of the other one that's usually mentioned.

rare oar
#

Pyramid?

#

Or tornado? Gosh I don’t don’t either.

#

I’m probably just saying random nouns hah.

vague seal
#

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

rare oar
#

On mobile but t sounds like set_header expects another RequestHandler as the argument where you give it a string.

vague seal
#

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?

See:
https://stackoverflow.com/questions/17011331/how-to-change-tornado-post-header-and-add-into-header-new-data#17011897

#

The docs don't have much either

primal minnow
#

hi somewonw can help me w/ Flask and HTML

marble pulsar
#

ask your question and see

primal minnow
#

how i can python duplicate a table for the servers you are own

#

on discord

#

Hello

#

?????

lavish prismBOT
#
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.

near ridge
#

Also have patience. We're all volunteers here and do this in our free time.

primal minnow
#

ok

#

sorry

vagrant adder
#

@primal minnow
What do you mean duplicate the table

#

Using the same db with 2 apps?

primal minnow
#

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
#

Guys what is the best course to start learning Django with ?

#

@ Me please

tender ice
#

@gloomy canopy I found the tutorial in the official docs to be an excellent starting point.

gloomy canopy
#

I will check it thanks mate

#

If anyone has something else please share

autumn bobcat
#

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

odd storm
#

@primal minnow what is that

primal minnow
#

a dashnoard

#

discord bot

cursive cairn
#

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?

deft ore
#
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.
autumn bobcat
#

@cursive cairn gonna have to actually store them as files in the filesystem

#

@deft ore add a 5 second delay after driver.get

deft ore
#

Still nothing @autumn bobcat

autumn bobcat
#

try loading the submission and then taking a screenshot before doing anything else

gleaming pollen
#

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

native tide
#

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.

timber dove
#

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

junior cloak
#

@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

timber dove
#

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

native tide
#

@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.

timber dove
#

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

native tide
#

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

junior cloak
#

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

timber dove
#

hmm, this might be abit out of my knowledge area. Any idea's on where to start?

junior cloak
#

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

native tide
#

yeah if there isn't too much data - just send the whole thing and filter with each key stroke

#
  1. endpoint in flask that returns json data
  2. js function that fetches data by hitting that endpoint
  3. js function that filters your data set with each key stroke

There a a lot of examples for any of these tasks πŸ˜ƒ

timber dove
#

alright thanks

#

with flask, where do you put the js code

#

in the html?

native tide
#

in your situation yes, in the coresponding template

timber dove
#

right thanks

junior cloak
#

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

timber dove
#

thanks appreciate it

junior cloak
#

@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

timber dove
#

@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

native tide
#

@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

timber dove
#

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

native tide
#

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 πŸ˜„

timber dove
#

yeah true, thanks

native tide
#

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.

junior cloak
#

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)

native tide
#

or you could look at something like List.js

#

but then again, with no understanding of js it will be hard to start

junior cloak
#

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

timber dove
#

thanks, i'll try and work out this js

autumn bobcat
#

anyone know of any js markdown renderers that allow for custom syntax?

native tide
#

redblob can someone possibly help me who understands chrome webdriver

autumn bobcat
#

depends on your question

native tide
#

kinda web based

#

just a account creation bot

#

u know by a chance @autumn bobcat

autumn bobcat
#

that sounds like it'd probably be breaking terms of service, sorry

native tide
#

@autumn bobcat it dosent break the tos of yandex

#

Nothing says that creating box wont do anything

zealous igloo
#

in django, is it bad practice to import models from other apps? they are supposed to be independent right?

junior cloak
#

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

zealous igloo
#

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

junior cloak
#

i'd probably avoid saving them to the db immediately

zealous igloo
#

oh how come?

junior cloak
#

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

zealous igloo
#

oh yeah id dint think about how the DJango ORM is slow

junior cloak
#

and not async

#

the key to channels is that it's async

zealous igloo
#

so would makin a messages model be inefficeint?

junior cloak
#

what is your use-case here

zealous igloo
#

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

junior cloak
#

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

zealous igloo
#

but i want hte user to be able to go back and see the messages

junior cloak
#

oh i think i get it, you want to have chat rooms that are different

zealous igloo
#

yes

junior cloak
#

ahhh okay

zealous igloo
#

yeyeye

junior cloak
#

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

zealous igloo
#

this is really new to me i knwo multithreading and the whole time i thought they similar but not really

junior cloak
#

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

zealous igloo
#

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?

junior cloak
#

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.

zealous igloo
#

hmm i see, thanks i'll look into that

#

it sounds efficeint

junior cloak
#

so you want the chat history to be stored forever?

zealous igloo
#

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

junior cloak
#

so, channels does have a background task / worker implementation

#

in channel layers.

#

that may be a good place to store the messages

zealous igloo
#

oh okay yeah im reading on it now

junior cloak
#

eh, it's probably better to just store them in-place without blocking using that sync_to_async function

zealous igloo
#

oh so not doing the layers might be better?

junior cloak
#

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

zealous igloo
#

oh okay i will

junior cloak
#

i dont know how much you know about redis

zealous igloo
#

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

junior cloak
#

redis is used in production in pretty much everything these days, for something

zealous igloo
#

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

junior cloak
#

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

autumn bobcat
#

@sudden yoke creating bots is almost universally against the ToS for a site, so i'd rather not take chances, sorry

zealous igloo
#

oh the django channelss tutorail

junior cloak
#

oh yeah i see it now. great

zealous igloo
#

so u would suggest using redis to permanently store the messages?

#

not the postgresql i am using

junior cloak
#

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

zealous igloo
#

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?

junior cloak
#

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

zealous igloo
#

holy heck thats good

junior cloak
#

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

zealous igloo
#

lol that would be a nice problem to have

junior cloak
#

until then you wont notice

#

so i'd maybe start with what you wanted to do

zealous igloo
#
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
            }
        )
junior cloak
#

but using those helpers (theres docs on db access in the channels documentation)

zealous igloo
#

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

junior cloak
#

well that isnt wrapped in the sync_to_async i mentioned

zealous igloo
#

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

junior cloak
#

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

zealous igloo
#

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?

junior cloak
#

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

zealous igloo
#

haha yeahhh i see what u mean

junior cloak
#

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

zealous igloo
#

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?

junior cloak
#

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)

zealous igloo
#

oh oh okay i see

junior cloak
#

**kwargs is just nice to use sometimes to save work if youre just using a dict with the same structure

zealous igloo
#

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?

junior cloak
#

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

zealous igloo
#

ohhoh so kwargs can be for passing dictionaries with the parameters equal to hte value

junior cloak
#

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

zealous igloo
#

ohhh must be keywrod okay i see

junior cloak
#

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

zealous igloo
#

oh yeah it would all be mixed up

junior cloak
#

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

zealous igloo
#

oh yeah i was thinking heroku but just for like produion just curious waht would u do?

#

what do u use i mean

junior cloak
#

once you go live youll have to pay like $7 for a production worker

zealous igloo
#

whats aproduction worker?

junior cloak
#

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

zealous igloo
#

oh wow yeah that makes lotta sense

junior cloak
#

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

zealous igloo
#

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?

junior cloak
#

you are just doing that because you dont have redis on your computer otherwise

zealous igloo
#

i pip installed channels_redis so wouldn't i have it?

junior cloak
#

you probably do that for postgres too

zealous igloo
#

no not for postgres

junior cloak
#

what do you use to manage your pip requirements?

#

pipenv? just a requirements.txt file?

zealous igloo
#

idk what u mean by manage sorry i just do pip3 install whatever

junior cloak
#

do you not use a virtual environment

zealous igloo
#

oh i do sometimes like the visual studio starts it for me but not everytime, is it that important?

junior cloak
#

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

zealous igloo
#

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

junior cloak
#

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

zealous igloo
#

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

junior cloak
#

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

zealous igloo
#

oh okay clean slate that sounds great

junior cloak
#

(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

zealous igloo
#

oh wow okay so heroku is that convenient, i see why now a virtualenv so important

#

thanks man i appreiciate all this

native tide
#

How could I create a user account for django via a 3rd party

#

3rd party application ^

zealous igloo
#

application as in library?

native tide
#

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

autumn bobcat
#

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

native tide
#

Yeah idk I just kinda reworded it

#

How could I go about this?

#

I'm not very experienced with apis

native tide
#

Actually

#

so

native tide
frail yew
#

How do you get Django to work on Atom Text editor?? And do you need Python 2 to run Django?

sturdy sapphire
#

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 ?

zealous igloo
#

@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

vagrant adder
#

Just open your django project folder with atom and that's it @frail yew

rotund lake
#

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

native tide
#

If you hate yourself, use flask

#

otherwise, if you hate yourself, use Django

#

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

rotund lake
#

Hmm i heard that flask is more begineer friendly

#

@native tide wdym

native tide
#

as much as I hate javascript, I'd rather use node.js than ever touch django or flask again

rotund lake
#

For real?

native tide
#

Yes.

rotund lake
#

But i'd rather learn python in general, i do have some experience with python

native tide
#

Then use django

rotund lake
#

Why not flask?

native tide
#

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

rotund lake
#

Which is better for a guy just getting into backend

native tide
#

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

rotund lake
#

It's great for making REST APIs and database stuff

#

This is what a mate quoted about flask

native tide
#

I mean I use django for rest apis

#

in fact i made one yesterday

rotund lake
#

Hmm ok

native tide
#

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

rotund lake
#

Yeah i dont

native tide
#

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"

rotund lake
#

Its for fullstack i guess

native tide
#

Learn x language.

rotund lake
#

I've got html & css down

native tide
#

Thats a start.

rotund lake
#

Mhm

native tide
#

Django docs are great

rotund lake
#

And im gonna continue python in general in future

#

So i thought backend with python would lend me more experience

#

In a general perspective

native tide
#

Do you know enough python for basic apps

#

If you have a decent knowledge of python django should be easy

rotund lake
#

Yeah

#

I got decent knowledge

native tide
#

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

rotund lake
#

Ahh nice

#

Ok thanks

native tide
#

That's a great start

#

django website has loads of useful information

rotund lake
#

Isnt it the same afterall no matter what framework u use

#

I mean isnt the code structure and functionalities the same for either framework

native tide
#

A little, but django has a different way of handling things

rotund lake
#

I was literally just reading that article xD

native tide
#

lol

odd storm
#

flask is awesome

native tide
#

web2py

vagrant adder
#

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

marble tulip
#

what are some good flask tutorials ? know only of the two flask mega tutroial books

vagrant adder
#

corey schafer has good youtube tutorial series

grand thicket
#

@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

native tide
#

Let him use what he wants

#

flask and django are both fine

autumn bobcat
#

is webpack absolute garbage, or am i just using it wrong?

#

i feel like if everyone likes it, i must be using it wrong

odd storm
#

@native tide they asked what people recommended, so people are giving recommendations

sudden bramble
#

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

deft aurora
#

Any Django bakery users? Trying to figure out how to get the build to append the md5 hash.

deft aurora
#

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)

barren cypress
#

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?

deft aurora
#

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.

barren cypress
#

@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

deft aurora
#

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

barren cypress
#

@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

deft aurora
#

Oh okay. So you don't want to persist it with the newline?

#

What are you using for display? Django template or something else?

barren cypress
#

Django template

#

In html code, i can show it with:
{{ mini_count}}
But just in the same line

deft aurora
#

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

barren cypress
#

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:]
deft aurora
#

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.

barren cypress
#

I don't know any CSS unfortunely

deft aurora
#

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.

sonic tartan
#

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;
}
deft aurora
#

Yeah totally. But if Engineer's looking for shortest path to wrapping a long line...

sonic tartan
#

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

deft aurora
#

+πŸ’―

zealous igloo
#

if i wanna be a django developer and know how to use the ORM prety well is there even any point in learning SQL?

deft aurora
#

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.

zealous igloo
#

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

late gale
#

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

native tide
#

you could start by telling us what the error says

left lynx
#

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

deft aurora
#

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?

left lynx
#

no I'm using djangos model. IM just trynna extend

deft aurora
#

remove string reference?

#
Py user = models.OneToOneField(User, on_delete=models.CASCADE) # no string
left lynx
#

thanks

#

lol

#

It worked

#

lol

native tide
#

Now that's what is called experience

rigid rover
#

Can I run a python script on a web host?

native tide
#

depends on the host

native tide
#

Did you do the official tutorial?

native tide
#

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.

vagrant adder
#

@rigid rover which host

rigid rover
#

@vagrant adder AwardHost

vagrant adder
#

vm or vps

green badger
#

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

last turtle
#

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

#

but i keep getting it

native tide
#

@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 πŸ˜„

tough star
#
Traceback (most recent call last):
  File "web.py", line 2, in <module>
    from flask_login import *
ModuleNotFoundError: No module named 'flask_login.0'
native tide
#

@tough star just a guess, but is there any chance that the package is not installed or installed in a wrong environment?

tough star
#

I'm on windows, i have installed the module with pip install flask_login

native tide
#

@tough star did you try importing only what you need, not *?

tough star
#

Yes, but it says that can't import the class LoginForm

#

@native tide

native tide
#

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?

tough star
native tide
#

@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

lost surge
#

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?

autumn bobcat
#

you could also use app.route to proxy the correct directory using os.path

late gale
#

Is there any full Django course pdf?

patent cobalt
#

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

native tide
#

Could someone help me with css

native tide
#

fixed it

native tide
#

@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

left lynx
#

can someone explain to me what Progressive Enhancement? I know somewhat.......

rancid creek
#

what is it you're not understandinf

#

about it

left lynx
#

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?

rancid creek
#

it's not about anything in particular

left lynx
#

WHat is it then?

patent cobalt
#

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

left lynx
#

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

patent cobalt
#

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.

left lynx
#

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

bright spindle
#

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 ^^

late gale
#

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

timber dove
#

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)

tough star
#

@late gale Try replace href="{% url 'core-index' %}" with href="{{url_for('route function name')}}"

late gale
#

@tough star

Could not parse the remainder: '('route function name')' from 'url_for('route function name')'
tough star
#

You need to replace "route function name" with the name of the @app.route('/example') function

#

@late gale

late gale
#

What actually the name of that

#

I didn't get it

tough star
#

What framework are you using?

#

@late gale

late gale
#

Django

#

@tough star

tough star
#

Oh

#

Try with {{redirect('core-index')}}

#

@late gale

late gale
#
Could not parse the remainder: '('core-index')' from 'redirect('core-index')'
#

@tough star

#

oh wait

tough star
#

?

#

Maybe I found the solution: {% url 'myapp:mypage' %}

late gale
#

umm

#

it solves nothing

#
'core' is not a registered namespace
tough star
#

I'm sorry, but I haven't experience with Django.

#

I tried to help you πŸ˜ƒ

late gale
#

No problem

#

Thanks anyway

barren cypress
#

@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

deft aurora
#

You can set a min-width by pixels if you wanted to

#

like <div style="max-width: 20%; min-width: 100px"> or something

barren cypress
#

It seems like i solved it by writing:
width:250px

solid cave
#

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..

deft aurora
#

@solid cave Are you do doing this in dev?

solid cave
#

yes

deft aurora
#

So you've got two dev servers

solid cave
#

one dev server

deft aurora
#

Not running flask in dev?

solid cave
#

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

deft aurora
#

cool. Yeah if you're using CRA you can specify the proxy to the backend

#

then you can reach your api with relative paths

solid cave
#

didnt use CRA, i guess unfortunately

deft aurora
#

Nah, it's still possible. I just can't remember the config

solid cave
#

would it be a plugin for webpack?

deft aurora
#

just look up proxy for webpack dev server

solid cave
#

gotcha

#

thanks

deft aurora
#

You bet.

#

I'm guessing you had somethign like localhost:8000/api/resource in your react fetch call?

solid cave
#

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

barren cypress
#

I couldn't find any information on that neither did i understand

late gale
#
 <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

patent cobalt
#

I see the paths admin/. about/ and so on

late gale
#

so i dont want Flask answers

patent cobalt
#

no index.html

#

How did you define your URL patterns?

late gale
#
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

patent cobalt
#

There's no /index.html path in there

late gale
patent cobalt
#

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

late gale
#

and how to set the root path to views.index

#

I am a beginner with Django

patent cobalt
#

You already did:

path('', views.index, name=''),
late gale
#

yes

patent cobalt
#

Are you running in debug mode? with the debug server?

late gale
#

i am actually running on the local server

patent cobalt
#

with python manage.py runserver?

late gale
#

yup

patent cobalt
late gale
#

um actually nothing is solved

native tide
#

okay so

#

make a function to and have to return the render of index.html

late gale
#

i actually did

patent cobalt
#

Did you follow the official tutorial?

late gale
#
def index(request):
    return render(request , "Core/index.html")

@native tide

native tide
#

then make a url path for /

late gale
#

I did

#

oh wait

#

do you mean this "/"

#

it wont solve anything but done

native tide
#

path('', views.home, name='home'),

late gale
#

@patent cobalt Every tutorial is using differ version of Django

native tide
#

What version are you using

patent cobalt
#

You can select the version you want in the official documentation

native tide
#

2.X or 1.1

late gale
#

2.2.2

#

I use the latest one

native tide
#

Try to go to localhost:8000

late gale
#

You are repeating what Ves said

#

-,-

native tide
#

What does it say

late gale
#

Same error

native tide
#

Copy and paste it

late gale
patent cobalt
#

It's just about/ not about.html

native tide
#

^

patent cobalt
#

You've created an url pattern for about/

native tide
#

you don't need the file extensions

patent cobalt
#
    path('about/', views.about, name = 'About Page'),
#

See the 'about/' in tehre?

native tide
#

localhost:8000/about/

#

thats the url

late gale
#

wait what -,-

patent cobalt
#

Did you hardcode your links into your file?

late gale
#

how to do so then

native tide
#

for hrefs you can do {% url 'about page' %}

late gale
#

i will check now

patent cobalt
#

Yes, let Django handle the URLs

native tide
#

<a class="nav-link" href="{% url 'forums' %}">forums</a>

#

thats an example

late gale
#

new type of error

native tide
#

?

#

what is it

late gale
#

Oh i solved it

#

Thanks

native tide
#

About Page

late gale
#

Yes

#

I wrote page instead of Page

#

Finally It works

#

I tried 2 days

#

Thank you!

#

You too @patent cobalt

native tide
#

if you ever want to change the path django makes it easy to handle urls

patent cobalt
#

Yes

#

I still go back to it every now and then because I don't use Django a lot

late gale
#

actually try Django, I enjoy the support of the framework. Its so friendly

patent cobalt
#

I don't really have a need for it, other than the back-end of PyDis

native tide
#

Yeah. It has a lot of useful features built directly into it

late gale
#

True. I am actually building my blog πŸ˜„

#

using Django

native tide
#

nice

deft aurora
#

@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

winged onyx
#

If anyone has experience with Flask, i posted a question in help-5 that i'd be super appreciative to get some help on

timber dove
#

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)

autumn bobcat
#

Yes, make the search box use a get request

timber dove
#

sorry what do you mean by that

odd storm
#

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>
timber dove
#

thanks, alrigjt i think im partially following, but have no idea on how id implement this

odd storm
#

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")
timber dove
#

hmm, what exactly is the request.args.get("q") doing

odd storm
#

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

timber dove
#

right, so you also dont need to do @app.route("/<>") stuff

#

just "search" is proficient?

odd storm
#

/search sorry, mb

timber dove
#

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

odd storm
#

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?

timber dove
#

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

odd storm
#

ok so you dont actually need a search then?

timber dove
#

possibly im looking at it wrong then, maybe

odd storm
#

are you trying to make the dropdown search right now?

timber dove
#

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

odd storm
#

oh probably jinja/flask templates

#

jinja is absolutely incredible

#

you can do programming inside of an html page, like with loops, if statements, etc

timber dove
#

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)

odd storm
#

um

#

id have to know the structure of the webpage, maybe you have some incorrect hrefs?

timber dove
#
@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

odd storm
#

lol this poor guy named app keeps getting pinged

timber dove
#

haha yea

odd storm
#

ok well you passed the product_name as "x" in the return statement, was that intentional

timber dove
#

well i didnt know what to put there

#

since i dont know how to get the value that jinja passes back to there

odd storm
#

im confused, i assume you meant to say product_name=product_name?

#

i dont know for sure though

timber dove
#

i guess, but wouldnt product_name need to be defined in the py script?

odd storm
#

it was passed to the function as a parameter right

timber dove
#

where i do product_name ='x' right

#

id change that to product_name=product_name?

odd storm
#

yeah

#

and then in the jinja template you can use product_name

timber dove
#

and i define product_name in jinja?

#

well ive got it loading the right /product

#

but i dont have an @ app.route for it

timber dove
#

ok think i sorted it

#

thanks fluzz

cursive granite
spring dragon
#

anyone using gmail api

#

managed to get pubsub working with gcp

#

but trying to figure out how to get the recent messages

#

using historyid

cursive granite
native tide
#

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.

cursive granite
#

@native tide what error are you getting?

native tide
#

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

native tide
#

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

solid cave
#

@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

round vapor
#

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 << >>
rain dune
#

Hello, little question, with Django, we need Python, HTML5 that's it ? I mean, any additional ?

native tide
#

if you want css

rain dune
#

Thank you for the return

autumn bobcat
#

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)

red condor
#

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

tight shadow
#

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

red condor
#

if the token is registered in js (local storage), it should be fine

tight shadow
#

@red condor you are referring to my cookie problem , right πŸ˜ƒ ?

red condor
#

@tight shadow yep

tight shadow
#

@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

red condor
#

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)

tight shadow
#

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

red condor
#

@tight shadow yes it s a way

tight shadow
#

ok, I can remove the cookie in the request injector then

#

interceptor*

#

but that's one client πŸ˜„

red condor
#

@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 ?)

tight shadow
#

@red condor If I remove rest_framework.authentication.SessionAuthentication, I will not be able to use the API browser πŸ˜„

red condor
#

but in fact, what is your app token login if you don t use the token authentication ?

tight shadow
#

@red condor If I remove it I can't login with API browser

red condor
#

@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

tight shadow
#

@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

native tide
#

What is this part called?

https://domain.com/example/123
                                                              ^^^```
#

crap

#

the /123

tight shadow
#

detail

#

wait in DRF or django ?

#

in normal URL it's path

#

@native tide

olive wharf
#

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
`

native tide
#

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.”

autumn bobcat
#

javascript is usually frontend

timber dove
#

can you set() a list within jinja?

wheat trellis
#

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

autumn bobcat
#

@wheat trellis re-read what i wrote

wheat trellis
#

Usually implies normally,

#

But node.js isn't unusual or uncommon

#

It's like saying usually people drive on the left

native tide
#

they do here

#

we drive on the left

olive wharf
#

@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

wheat trellis
#

:(

#

Oh man don't get me started on curly braces and semi colons

olive wharf
#

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

wheat trellis
#

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

autumn bobcat
#

I would argue most js is frontend

cursive granite
crystal obsidian
#

@wheat trellis good point about the {}

opaque vigil
#

guys

wheat trellis
#

Sup

tight shadow
#

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

cursive granite
tough star
#

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

tough star
#

How I can fix?

strong laurel
#

show how are you mapping your URLs and how is the link sent to the confirmation email

tough star
tough star
#

I haven't fix that yet.

autumn bobcat
#

what's the link that gets sent in the email?

wintry elbow
#

Anyone decent with Javascript?

autumn bobcat
#

Maybe, depends on the question

stiff totem
#

What do you guys use for apollo ? is it graphene-django or ariadne ?

pale fiber
#

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

late gale
#

Is there any way to download a template and connect it to my django project

spiral cedar
#

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)

#

?

restive tapir
#

is anyone trying FULL apollo integration on top of python?

north swift
#

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?

stiff totem
#

anyone from Ariadne ? how to do pagination in ariadne?

gleaming herald
#

anyone

#

with a simple webpage

#

which stores entries passed in URL

#

in python

spiral cedar
#

r u using flask or django? @gleaming herald

spiral cedar
#

Do i need to have virtual env to use django

#

?

craggy heart
#

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?

spiral cedar
#

this is python server XD

craggy heart
#

this is web-development though

spiral cedar
#

But must be related to python πŸ˜‰

patent cobalt
#

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

craggy heart
#

Fixed

native tide
#

does anyone know of a good web framework that doenst suck ass like Sanic or Flask

rigid rover
#

django?

vagrant adder
#

Flask is awesome what are you talking about

proud turret
#

Hi good people! Could anyone give me some feedback on this figure? Does it make sense to you? πŸ™‚

hushed kindle
#

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?

hushed kindle
#

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...

patent cobalt
#

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

hushed kindle
#

one would expect a significant portion of those to be invested in web app dev?

#

anyway

#

know anything about python mvc frameworks?

patent cobalt
#

@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

native tide
#

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

pale fiber
#

Mentors somebody can help me with my questions on top?

tight shadow
#

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.

hushed kindle
#

@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 πŸ˜ƒ

timber dove
#

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

hushed kindle
#

@timber dove try to get your chart generation code inside the innermost of your loops (they are nested, amirite)

timber dove
#
{% 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: {```
hushed kindle
#

hmmmm, not sure how the wiring is supposed to work (the div invocation)

the devil is in the details though.

#

I guess that part is working, as you get at least one bar πŸ˜‰

#

my next guess would be that your for loop isn't looping over all the products.items

timber dove
#

well i get a fully working graph

#

but only of the last loop