#web-development
2 messages · Page 120 of 1
How can I get exact route in flask?
with specified args
@app.route("/gif/<token>")
def some():
pass
i wan to print exact url
gif/1607010020-3b53bd0be68cd3ab5fe8758df8e89f47a8bf30d7/76d63fb3-58d9-43d2-a2ed-fd7d80a3f315
request.endpoint give name, url_rule give pattern :/
how to make ajax post in flask?
@vestal hound i wanted to get tasks that people in this discord had to do for an interview 🙂 I usually google stuff and ask when i cannot connect the dots 🙂
@native tide Write the ajax code and send it to the path that leads to your backend function with whatever values you need to include.
try #career-advice then
@glacial orchid I don't think it costs anything to upload(transfer). On the Heroku side, it depends. I think they have different levels of prices. They have a developer account which allows you to test stuff that I don't think costs anything, but doesn't have much processing power.
@native tide you can also use this channel
heroku is trash
hello
hi
i have a question
i am building a website in html. but i am using python to transfer the info i get into a csv file
i was going to use local storage
but i figure csv file is easier
i have been asking around but have not been able to get an answer yety
What's the question?
i am not sure how to transfer the info into a csv file
Looking to convert a text file to CSV using Python? If so, I'll show you the steps to convert your file. Tool is also included.
oh yes thank you
It was the first google link.
Not a bother, just try to do some research first and if you have specific problem with your code, we can definitely help.
hello, I am trying to retrieve the avatar url from a server but I cannot understand how this part of the API works, if someone can explain to me https://quart-discord.readthedocs.io/en/latest/api.html#discord-oauth2-client (icon-hash)
Does anyone know why i get a BLOCKED and NS_BINDING_ABORTED when making post through ajax?
not sure if this is the right channel
it is because im using flask
im working on an admin email to automatically send emails for password resets
and im getting a
Hi, can anyone help me fix this error, I got stuck and now am unable to move ahead with my django project 😦
If I used class based views in django to interact with the database does that mean I was using ORM?
what would they be trying to find?
a VPS?
@shadow hornet The good-question page.
Need some help with Django / JSONField. I can unpack the data at the template level w/ stuff like {{channel.json.items.0.snippet.title}} but can't figure out how to prepare it at the view level so that I don't have to resort to this ugly syntax. I would like to have the title as channel.title in context, not channel json items 0 etc.
we used to have an !ask tag, but it was used in toxic ways, so we removed it
Ah
if you do have any suggestions though, feel free to open an issue on https://git.pydis.com/meta or bring it up in #community-meta
Thanks, will do.
FWIW, we do have plans to rewrite and shorten the asking good questions page because as it is now, it is much too long and i would guess that about only 1% of our users would actually read it
I am getting 500 internal server error while deploying my flask app to heroku can anyone help
500 means that you have an error in your project. Can you get the error and show us your applicable code?
I'm not sure how heroku works. Is the 500 error when you try to load your web project in your browser or during the act of deployment?
@timid belfry
my godaddy domain's name servers are set to cloudflare. how can I change my redirect targets? my issue is, when you enter url with https://, it redirects to my website but url with http leads to another website (one of my old websites)
can someone help in #help-mushroom please
Guys, in django
I have a model
when I type for example form.model
it gives me the whole model
I only want the data of that model
https://gyazo.com/81425561532d1f2e1d885b378ac8c55f thats how it looks now
yo
if any1 here good with webscraping
why does beautifulsoup return a empty list with the find_all() function?
u tryna make a dork parser
guys
im having a stroke
why I cant get my data shown in the button?
def home_view(request):
context = {}
form = GeeksForm(request.POST or None)
context['form']= form
if request.POST:
if form.is_valid():
temp = form.cleaned_data.get("geeks_field")
print(int(temp))
return render( request, "blog/weight.html", context)
that is the views.py
<input type="submit" value="Submit">
<p class="btn btn-outline-secondary btn-sm mt-1 mb-1">{{ form.temp }}</p><br>
that is the weight.html
form.temp is not working
idk why
context = {'form': form,}
because you're not passing form.temp in the context
Hi Nut, hows it going?
going fine, how about you? 🙂
Same 🙂 Bit tired but friday is comming 😄
google chrome
and whatever backend technology u use
you can take a look at this https://developer.mozilla.org/en-US/
Anyone able to help with Django stuff?
i can with newbie stuff
hey guys wanna ask about todo app i m doing it with flask. problem is i have dashboard site where u can see lets say all products and there is a button which have u to open add.html where u can add product and write there something about it but if u click add product (that button on dashboard page) it show mathod not allowed also eror 405...what should i change?
python manage.py collectstatic seems to be failing for some reason. It can't find any of my static files...
have you configured the static_root ?
hm isnt the root supposed to be different than the static?
Maybe? It was working until I just updated some static/admin files. Then I went to collectstatic again and it failed.
It says specifically:
FileNotFoundError: [Errno 2] No such file or directory: '/mnt/c/Users/Corey/Desktop/work/2. Web Applications/project/app/static/admin/css/vendor/select2/LICENSE-SELECT2.md'
I have no idea what select2 is though...
I think maybe I have a git issue. A bunch of files are saying they're untracked...
Fixed the collectstatic, it was a git issue of some sort...
@halcyon lion But I'm still getting this from the Django admin site when I try to submit a form:
Exception Type: TypeError at /admin/hydracards/card/add/
Exception Value: object of type 'int' has no len()
Any clue what that might be?
@halcyon lion Hah, I'm not using len() it's a part of Django django/forms/models.py...
In django/forms/models.py:
class ModelMultipleChoiceField(ModelChoiceField):
"""A MultipleChoiceField whose choices are a model QuerySet."""
widget = SelectMultiple
hidden_widget = MultipleHiddenInput
default_error_messages = {
'invalid_list': _('Enter a list of values.'),
'invalid_choice': _('Select a valid choice. %(value)s is not one of the'
' available choices.'),
'invalid_pk_value': _('“%(pk)s” is not a valid value.')
}
def has_changed(self, initial, data):
if self.disabled:
return False
if initial is None:
initial = []
if data is None:
data = []
if len(initial) != len(data): # <-- Problem Child
return True
initial_set = {str(value) for value in self.prepare_value(initial)}
data_set = {str(value) for value in data}
return data_set != initial_set
Figured it out!!! It was a stupid ManyToMany field. Bloody hell.
How do people download files when testing their django application using selenium tests?
Also Im randomly getting this django error Requested setting TEMPLATES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
When running unit tests
@trim star you can use file field as a text field and just input path to file to it. it works,
Oh is somebody else working on FilePaths? I am also struggling with it
regarding settings - you should have DJANGO_SETTINGS_MODULE=settings.test ir smth like this
@swift heron what do you mean by file paths?
@peak lotus thanks
For django, I am setting the file path attribute to a model, when that model is ran I have it request the filepath and send that data to the frontend
@peak lotus I ended up using requests.get
@trim star text field of course. fixed a typo
however whenever the frontend request that data I get returned a Not Found: /computer/stream.mp4
so im not sure if my media directory is setup correctly or not
@swift heron check your upload_to or set it explicitly
Oh sorry I meant FIlePathField
@peak lotus but my files are not text though...you said text field? Im not a web dev btw, just a regular software engineer that was tasked to write tests for this web proj
yes, looks like an issue with your media path
the data is already on the backend I just need to send it to the frontend
@trim star i do not remember selenium syntax, but you do the same as with text field. like my_field.send_keys("uploads/my_file.pdf")
@peak lotus thats for uploading files right?
yes, you are right
@swift heron looks like yo are storing relative paths as absolute? i am not sure if you have /computer folder
This is correct I do not have a computer folder, my media file directory from the project directory is ProjectName/media
cool, then i believe smth goes wrong during saving path. it should be computer/stream.mp4, not /computer/stream.mp4
but i am not sure, I did not use this field too often
This is what my field looks like
media_file = models.FilePathField(path=MEDIA_ROOT, default='stream.mp4')
I am not sure if this is correct and this is just for testing as well
okay, I had a similar issue. this is what you can try, not sure if this helps:
ROOT_PATH = Path(__file__).parent.parent # get root path of your project
MEDIA_PATH = ROOT_PATH / "media"
should it be MEDIA_PATH or MEDIA_ROOT?
probably you have to change the first line if you have more nested settings file
@peak lotus also, is there a more efficient way of creating different file types for testing file uploads other than manually creating test files on disk?
Currently I have the following
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'HomeAutomation', 'media')
intresting, thanks for your time
@trim star it is okay to store different files for testing purposes. just store them somewhere in tests/assets
@swift heron i would cross-check that your BASE_DIR is correct though
I did check this and my MEDIA_ROOT seems correct as well maybe I am not grabbing the right value from the FilePathField, currently it is only returning the value of the file name but not the full path, is this correct?
What is selenium?

Not everyone here is a web dev lol
I'm a web-developer...
Im not...I was just tasked to fix some things
I can't keep up with all this stuff. I learn one thing, and then 5 new things pop up.
Thats why im not a web developer lol
You guys are underrated though
at the rate that everything changes @lofty portal idk how ppl keep up other than their whole life is about web dev
That's pretty much how I feel. Which is why I'm still working at 8:20pm...
😦
Im working at 8:20 pm because this is my part time job
in addition to my full time software engineer job
I dont know how you guys do this full time
Yeah, I do software engineering as well working on C# projects. But I also do full-stack web design programming. And I manage servers and AWS stuffs...
I see
I should probably find a job that allows me to focus on one thing.
@lofty portal what would you want to focus on?
Good question. I like python a lot. I went to school for medical and sciences. So, something that allowed me to work with those together would be nice.
Join Neuralink
But front-end web stuff is really rewarding. Really like Vue.js.
Hah
That stuff is kind of scary.
Rewarding as in $$$?
I like how Elon Musk is afraid of AI, but wants to put a computer in your head.
I would rather be happy working, than unhappy getting paid really well.
Ehh I dont want to drag this convo out in here, but I think while scary it has its pros and cons regarding the people it can help or even save
Same, everyone has their own definition of rewarding
I guess there's an amount for everything though. If I got paid a million dollars a year or something, then you could sign me up right now.
True. Plus you can't always be happy with programming. It's overcoming those challenging problems that makes a lot of it rewarding.
Much like climbing a mountain. Can't get that view without some work.
@swift heron You know anyone working at Neuralink?
True
@lofty portal Sadly not but it would be a dream if I could work there someday, will just have to learn alot in the meantime
Is there any reason to not use pipenv? As opposed to just using venv and pip separately?
pipenv im pretty sure just adds onto venv with the abillity of creating locks and grabbing all packages from those locks with specific versions, should be no downside
Yeah, I'm surprised that there aren't more tutorials or people in general using pipenv. Seems like people just use venv and pip.
I have a FilePathField attribute connected to my model, to check that it is working I go into the django admin terminal and look at the specifics of my models, in the FilePathField Dropdown I can see all the files located in my media folder
However when I JsonSerialize the data and send it to the frontend to load the media query I use this code,
function start_stream(video_data) {
let video_path = video_data.media_file;
let video = $('#stream video')[0];
video.src = video_path;
video.load();
video.play();
}
However this returns
Not Found: /computer/stream.mp4
HTTP GET /computer/stream.mp4 404 [0.01, 127.0.0.1:65160]
What can I try? please use the reply feature or just @swift heron
guys which is the best python framework for backend devops?
is it good to start with django?
there are no best framework, there only popular ones that alot of people are using like flask, django, fastapi,...
Django have alot of built in stuffs that you won't understand if you never work with backend framework before, i recommend you start with flask as it's the most basic one
ohk i will look into it
thnks for the info
and
what are the tools for automated python programs?
in which field of automation ? web, script,... ?
no normal like problem solving and making projects
@thin dome you can set default value for it https://stackoverflow.com/questions/5895588/django-multivaluedictkeyerror-error-how-do-i-deal-with-it
you get from the query?
yeah
can you post your code text instead of image?
ok
!codes
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
if request.method == 'POST':
First_name = request.POST['First_name']
Second_name = request.POST['Second_name']
username = request.POST['username']
password1 = request.POST['password']
password2 = request.POST['Confirm_Password']
email = request.POST.get['email']
user = User.objects.create_user(username=username,password=password2,email=email,First_name=First_name,Second_name=Second_name)
user.save();
print('User Created')
return redirect('Home')
else:
return render(request, 'Register.html')```
this is register fun()
seems like request.POST.get['email'] can't get the email from form
.get is not ther in email
in your html form do you set your input name="email" ?
yes
when you click to send the form did you input any email?
show me your html of the form
<form action="Register" method="POST">
{% csrf_token %}
<input type="text" name="First_name" placeholder="First_name"><br>
<input type="text" name="Second_name" placeholder="Second_name"><br>
<input type="text" name="username" placeholder="username"><br>
<input type="email" name="email" placeholder="email"><br>
<input type="password" name="password2" placeholder="password"><br>
<input type="password" name="password1" placeholder="Comfirm Password"><br>
<input type="submit">
</form>
@thin dome firstly you need to fix how you get the email, it's supposed to be
request.POST.get('email')
get can't be use with square bracket
you sure?
ok im trying it
get() is a method in python https://www.w3schools.com/python/ref_dictionary_get.asp
there are no get[]
@thin dome change it and try to register again and tell me if it work, post the error if there an error
@gaunt marlin its giving type error 'QueryDict' object is not callable
mail error is gone
but now its giving for firstname and lastname and thats the last error @gaunt marlin
can you paste the error of it ?
the same
what do you mean the same?
you don't have firstname and lastname in your form though...
i have
What does django secret key actually do ? what is it's purpose ?
@near bison https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-SECRET_KEY it's for cryptographic signing of your authentication, cookies, token
{% csrf_token %}
<input type="text" name="first_name"
placeholder="first_name"><br>
<input type="text" name="last_name"
placeholder="last_name"><br>
<input type="text" name="username" placeholder="username">
<br>
<input type="email" name="email" placeholder="email"><br>
<input type="password" name="password2"
placeholder="password"><br>
<input type="password" name="password1"
placeholder="Comfirm Password"><br>
<input type="submit">
</form>```
that different html from the one you post earlier...
no
@thin dome this one is different with first_name and second_name
you changed in the html, you have to change in your view to
first_name = request.POST['first_name']
last_name = request.POST['last_name']
when you register do you get the same error after changed both?
yes
@thin dome can you post that error? i have a hard time following this
no the full traceback error, not one line
man wait
can someone help me
yes with django?
ok
can you show the code?
{% extends "structure.html" %}
{% block main %}
<h1>This is the homepage</h1>
<form action="/" method="post"
<input placeholder='Username' name="username" type="text">
<input placeholder="Password" name="password" type="password">
<input type="submit">
</form>
<p>{{ message }}</p>
{% endblock main %}
it should be <form action="/" method="post">
and you should not write post you should write POST
@somber fable
okay done
error solved?
show me the updated code
{% extends "structure.html" %}
{% block main %}
<h1>This is the homepage</h1>
<form action="/" method="POST"
<input placeholder='Username' name="username" type="text">
<input placeholder="Password" name="password" type="password">
<input type="submit">
</form>
<p>{{ message }}</p>
{% endblock main %}
in from > is missing
ok
have great day ahead
you too
<div class="star-rating">
<input type="range" class="custom-range" min="0" step="1" max="5"
id="rating-for-{{place.id}}" name="rating"
onchange="window.location.href='{{ url_for('visits.visit', place_id=place.id, rating=2) }}'">
</div>```
anyone got a trick for optional models.DateField() ?
im using flask and using onchange js
i want to send rating how can i achieve that?
url_for('visits.visit', place_id=place.id, rating=2) here rating is hard-coded and how do i pass data with like data-rating
@hollow scaffold like not required on form? if you want to have it optional on form just add blank=True
I am having a rly strange issue
Basically I am redirect to discord OAuth2 link with the following function
@utility.route('/bind_discord')
def bind_discord():
return redirect("https://discord.com/api/oauth2/authorize?client_id=784286221106806864&redirect_uri=http%3A%2F%2F134.122.114.27%3A5000%2Flogin-success&response_type=code&scope=identify%20email%20guilds%20guilds.join")
When the user navigates to /bind_discord they get redirected to the link below and not to the link returned by the function
https://discord.com/oauth2/authorize?client_id=775389403451097097&redirect_uri=http%3A%2F%2F127.0.0.1%3A5000%2Fbind_callback&response_type=code&scope=identify%20guilds.join%20guilds%20email
How is that even possible?? Yes I have clean my browser data/cookies/local storage
The url there is a test server its not my home's ip
Hello can someone help me
import sqlite3
connection = sqlite3.connect('flask_tut.db', check_same_thread = False)
cursor = connection.cursor()
cursor.execute(
"""CREATE TABLE users(
pk INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(16),
password VARCHAR(32),
favorite_color VARCHAR(32)
);"""
)
connection.commit()
cursor.close()
connection.close()
does it matter to my users which region i host my app to
for example my users are in asia. but my database and app is hosted in us east
great thanks @rustic pebble
@rustic pebble
can u help me with this
import sqlite3
connection = sqlite3.connect('flask_tut.db', check_same_thread = False)
cursor = connection.cursor()
cursor.execute(
"""CREATE TABLE users(
pk INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(16),
password VARCHAR(32),
favorite_color VARCHAR(32)
);"""
)
connection.commit()
cursor.close()
connection.close()
what might have gone wrong
@rustic pebble
nvm
i gt it
what would be the right way to create an app that should be available in multiple languages in django ?
Hi, I need some help please. I am using python requests to make an api call and in my payload I have from the year 2010
to 2020. I wish to loop through the years in the payload to gather data from the years seperately (2010, 2011
2012...and so on) but I have no idea how to do this. Can anyone help?
My payload:
payload="{\r\n \"groupBy\": \"BgtOcc\",\r\n \"timePeriod\": {\r\n \"from\": \"2010-01-01T00:00:00\",\r\n \"to\": \"2020-01-01T00:00:00\"\r\n },\r\n \"queryString\": \"([nationwide]: \\\" nationwide \\\") AND ([BgtOccFamily]: \\\"Hospitality, Food, and Tourism\\\")\",\r\n \"geography\": \"US\",\r\n \"includeTotalClassifiedPostings\": true,\r\n \"includeTotalUnclassifiedPostings\": true,\r\n \"offset\": 0,\r\n \"limit\": 1000\r\n}"
What my payload looks like when printed:
{
"groupBy": "BgtOcc",
"timePeriod": {
"from": "2010-01-01T00:00:00",
"to": "2020-01-01T00:00:00"
},
"queryString": "([nationwide]: \" nationwide \") AND ([BgtOccFamily]: \"Hospitality, Food, and Tourism\")",
"geography": "US",
"includeTotalClassifiedPostings": true,
"includeTotalUnclassifiedPostings": true,
"offset": 0,
"limit": 1000
}
hey
I'm using django to create RestAPI
my question is i want regular user to get authenticate using phone number but i don't want super user also to get authenticate using phone number i want it be same as it was
what would be the right way to create an app that should be available in multiple languages in django ?
Pls help me I have this data in views.py django
def home_view(request):
context = {}
form = GeeksForm(request.POST or request.GET)
context['form']= form
if request.POST:
if form.is_valid():
temp = form.cleaned_data.get("geeks_field")
return render( request, "blog/weight.html", context)
how to use temp in weight.html?
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
<p class="btn btn-outline-secondary btn-sm mt-1 mb-1">{{ form.temp }}</p><br>
</form>
</div>
{% endblock content %}
thats how weight.html looks rn
My problem is I cant show the data
it looks like an empty button
hey everyone, i was appending some input values into a <div> so that the page shows it without a refresh. But the problem is that if the user types in some html tags like <h1>, it jst..........
is there a way to mark the string "unsafe", if that is the word? so that if the input is "<h1>hello</h1>" it shows the same thing rather than a huge "hello"
also i don't want to wipe out the html tags.
exactly! it can't be done that way...
Anyone with experience with SQLAlchemy/postgres that canand wants to help me understand some things? DM me. Cheers.
to change my django rest framework database to postgres, would I do
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.path.join(BASE_DIR, 'db.postgresql'),
}
}
``` instead of
```py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
ok
@vernal furnace you're not passing anything in the context... again
https://github.com/bhagyajbijukumar/flask-quick-start working on something like express generator for flask
Btw, why would you use postgres with django? It's still the same ORM, what difference does it make?
Hey everyone im currently looking for a python backend solution to create a API. my requirements are that it should be async and pretty lightweight. My React project is going to talk to the python backend using HTTP requests.
Its not going to be a big API, and i have considered looking into AIOHTTP and fastapi. Anybody have suggestions/tips?
@supple ether I've been using DRF with a react frontend, but I think the other best option is fastapi
Just popularity tbh
@supple ether you can try flask-reastplus too
ooh thank you, going to take that in consider
does it support async? in flask-restplus?
thx
Django has special search filter functionality with postgres, like full text search, makes a lot of stuff way easier.
https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/
https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/search/
Is there a way to filter and grab objects that are next to an object? Like:
the_person_id = 2
prev_neighbor = People.objects.filter(visible=True, id__lt=the_person_id).order_by('-id').first() # should be id=1
next_neighbor = People.objects.filter(visible=True, id__gt=the_person_id).order_by('id').first() # should be id=3
Hi, i heard there was a way to implement pythong code into a flask website, but how
python*
hello?
@normal pivot Hi
hi
You can certainly use python to create a flask website.
Yeah, I can imagine you can. You just need all the requirements in the project as is normal.
@normal pivot Check this out:
https://github.com/pygame/pygameweb
pygame.org website. Python, PostgreSQL, Flask, sqlalchemy, JS. - pygame/pygameweb
Framework to make a pygame in flask.
Perhaps you should experiment with Flask first. Have you used it before?
i don't see anything of pygame in it
nop
`from flask import Flask, redirect, url_for
app = Flask(name)
@app.route("/")
def home():
return "Hello, welcome to my website where u can play Troubleshooters! <h1>HELLO<h1>"
@app.route("/<name>")
def play(name):
return f"Hello {name} glad you want to play my game!"
@app.route("/admin")
def admin():
return redirect(url_for("home"))
if name == "main":
app.run()`
i got that
Yeah, get familiar with Flask and then try running a simple pygame in there.
Well, then don't expect it to work.
You wanted to paste a game into a Flask website.
well u said it was possible
It's not as simple as "just pasting it in".
well, what then
If you want the work to be done for you, then a framework like the one I suggested would get it done a bit quicker for you.
work = programming or "just pasting your game into Flask"
so, make a "bot" that programs for me?
What?
oh, i gtg eat, i'll be bacc in 30 mins
Are you just messing with me?
no, 30 mins i'll be back
Ok i m back
@normal pivot If you want to learn something new and won't put the effort in, you will not achieve your goal.
i don't wanna learn flask
Then you won't achieve your goal
why not?
because you don't know how to.
thats why i m asking ._.
you said "i don't wanna learn flask"
yes
so how are you going to do something if you don't even want to learn it
that doesnt really match with each other?
it really does, can you explain how it doesn't?
Ok, so you want to fly a plane. Are you going to fly a plane without learning?
Ok, you want to try to fly a plane, are you going to try without learning?
I don't understand how you want to make a Flask application without wanting to learn flask. That's flying a plane without knowing how to. And what does that lead to? A crash.
So, an instructor? So you want to learn?
learn while i m doing
well, yeah, but before you "do" anything you need to understand what to actually do. So I'd recommend a youtube tutorial on Flask for beginners.
I already did
Also, implementing your pygame onto the web is probably not achievable. You want to make a web-game using JS and whatnot instead, as this is probably the wrong route.
that was my question
well there's the answer
Then why did u want to take this conversation
hey
i hava little error
TypeError: 'coroutine' object is not subscriptable```
I become a panel for a discord bot
and i want post data for the page
<div class="cache">
<input name="guild-id" id="guild-id" value={{ post.id }}>
</div>
<h1><img src="{{ post.img }}" width=50px" class="server-img"> {{ post.title }}
<button class="server-bouton" onclick="window.location.href = 'http://127.0.0.1:5000/server';" type="submit">Accéder</button></h1>
</form>```
python code
@app.route("/server/", methods=['GET'])
@requires_authorization
async def server():
user = await discord.fetch_user()
posts = []
print(request)
print(request.form['guild-id'])
print(user)
posts.append(
{
'user': user,
'guild_id': id,
},
)
context = {
'posts': posts
}
return await render_template('server.html', context=context)```
What is a good default for datetime fields for django models? (sqlite3)
depends what the field is. Often it's something like timezone.now
Hello
Can ayone help me?
I need to host my code so it runs 24/7
How can I do it?
default=auto_now
default=auto_now_add
default=timezone.now
It depends what type of datetime u wish to use
Tell me what access u wish on your date
I will try to tell you which among them u can use
Or simply use timezone
It will allow you to edit the time whenever and however u wish
@glacial orchid I know those three and use them in another model, but the default I'm looking for is just to populate existing rows.
Having default=auto_now wouldn't make any sense in my case. Shall I just use a random date in the past as default then?
The current behavior of the Django REST Framework is to give the message "Invalid username/password" upon bad authentication credentials to the API.
Any thoughts on how to make the error message more explicit by specifying if was a bad username or password?
I'm looking at the source code for the BasicAuthentication and I can't figure out where the username/password validation is made.
Does anyone know how to override just the create/add view in the Django Admin site?
I see there are ways to override the model list(e.g. - change_list.html) and the update/change(e.g. - change_form.html) views. But can't seem to figure out how to change the add view...
Hello
Can anyone help me?
I need to host my code so it runs 24/7
How can I do it?
@final forum You could use heroku to host your server
or you buy a raspberry pi and run your code on that
Can you help me starting heroku?
I'm sorry but I don't have any actual experience with that, but I guess there are great tutorials out there.
Are you trying to deploy a django project? if so: (https://devcenter.heroku.com/articles/deploying-python)
Selenium
Then I'm not quite sure If heroku would be a good choice
maybe this helps? https://www.pythonanywhere.com/
Host, run, and code Python in the cloud: PythonAnywhere
@native tide Can u comeback
Finally someone replied to me
What should I pass in context = {} ?
Hello
@vernal furnace So your context what is used to pass objects to your template. If you had context = {"counter": count}, where count=5, you would access it in your template as:
{{ counter }} <!-- This will show 5 -->
So you need to pass something in your context to actually show something. Your context is empty.
I need an internship unpaid even, from any small company working with Django
More info: https://stackoverflow.com/questions/20957388/what-is-a-context-in-django @vernal furnace
I need to improve and get experience working with a team
Omg thank you man
I can not tell why my form is not validating
xD
trying to do a password reset
and making sure that the confirm fields are equal
I can't tell either!
iirc print(<something>) doesn't show up in the console for Flask, you need to pass another argument
does anyone know of a function in tweepy to check a users likes?
This https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list works well with PHP.I want to know how can I use it with tweepy or any of the python modules?
Like that?
kinda, I want to make a quick bot to speed through my likes and download all of the videos
Sounds like two steps. Figure out the function to get the likes/download vids and then make a bot do it.
Google shows a number of sites with implementation of a way to get likes if that's what you need first.
Do you have a specific code that's not working currently?
No, but I now have two new problems.
so first problem, I have 200+ likes and the list that is outputted has 20 items.
and next problem, I'm not sure how to check the ID for a video.
items(20), is it supposed to be more than 20?
I'm not 100% sure what problem one is.
Ooh, just noticed that.
I don't use tweepy, so I don't know how to answer on making it do a particular thing. The docs for it should probably have the information.
Yea, like I said, I don't know how the function integrates with Twitter to check if it is a video. The docs should give you that exact info.
alright, thank you!
if ids.video:
do this
what do you guys prefer for Django, class-based or function-based views?
I always used function based
but how it check if it has a video is a specific function in tweepy I'm sure.
I definitely prefer function-based.
To me, I always felt classes should hold data, and functions should affect data.
yeah I'm on the same boat... I was just trying to see what others use because I was getting FOMO if I don't use class-based hehe
I think it's relatively new, so it's something to get used to if anything. It just feels more confusing to me so why bother.
At least new with Django.
So... this is just kicking around an idea at this point, no actual code. More 'exploring' what all would need to be involved before I decide to start down the rabbit hole and find too many surprises.
What all would it take to make a web app (Flask, Django, etc.) into something that an end user could run an .exe file on their local computer, and have it fire up a GUI control that lets them control a small light-duty web app running on either localhost, 0.0.0.0 or the local LAN interface?
If you're at all familiar with the 'out-of-the-box' install of Web2Py from years past, that's pretty close to what I'm thinking of.
It seems like a person would be able to create much the same effect with a simple little GUI using tkinter, PySimpleGUI, etc. to select localhost or other network interface, maybe assign a password, and then start/stop the server. Then the web app (again, Flask, Django, whatever) would be availabe in a local browser window, or from somewhere else on the LAN.
What else would be involved? Some sort of packager, like pyinstaller? For a very small / light application with only a few users, SQLite seems like it should be sufficient. How would one handle the web server part - or would just running the test/dev server inherent to the framework be okay in this scenario?
I realize this is kind of an edge case... but it's one that for some reason or another really interests me. Any constructive comments would be much appreciated.
Particular reason you don't want to just make it a web client?
Or rather, is the reason specifically needing it not to be one?
@timid frost
Looking at a use case where the end user needs to be able to set it up and run it locally, without having to do much in the way of configuration beyond what was mentioned above.
@dense slate maybe I'm not quite clear on what you mean by "make it a web client"
Meaning could the user facing part/client just be online on a webpage
Rather than a downloadable client
Yeah, that's not really what I had in mind.
Right
I'm not well versed in client side installed apps but i know python has significant limitations for that kind of solution
Now I'm curious, if you're willing to share the edge case.
Local/amateur sports league, could use a crud app for tournament registration and scoring. Online (internet) connectivity is not guaranteed. May only one person doing stats (registration, scoring, awards) might be a handful depending on the event. These are volunteers, not IT folks - they need a tool, not something they have to spend time setting up and tending to.
Hi, I'm new to Py Dev with Django any advices ? For a fresh start
anyone here good with html? im trying to create a direct download link where once they click it they will download the folder
does anyone know how to do that
I have a Flask webapp on a Ubuntu vps, on wsgi-apache2. Is it possible for me to host a aiohttp webserver on the same vps as well? @ me when answering, please.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
what i need to do plz
can you guys see my code to find out why it is not printing form data?
def submit(request):
data = request.POST
print(data)
return render(request, 'users/login.html', context={'mode': 'signup', 'data':data})
``` This is `forms.py`
login.html
<form action="{% url 'register' %}" class="sign-up-form" method="POST">
{% csrf_token %}
{{form}}
<h2 class="title">Sign up</h2>
<div class="input-field">
<i class='bx bx-id-card'></i>
<input type="text" placeholder="Full Name" />
</div>
<div class="input-field">
<i class='bx bxs-envelope'></i>
<input type="email" placeholder="Email" />
</div>
<div class="input-field">
<i class='bx bxs-user'></i>
<input type="text" placeholder="Username" />
</div>
<div class="input-field">
<i class='bx bxs-lock-alt'></i>
<input type="password" placeholder="Password" />
</div>
<div class="input-field">
<i class='bx bxs-lock-alt'></i>
<input type="password" placeholder="Confirm Password" />
</div>
<input type="submit" class="btn" value="Sign up" />
<p class="social-text">Or Sign up with social platforms</p>
<div class="social-media">
<a href="#" class="social-icon" id="facebook">
<i class='bx bxl-facebook'></i>
</a>
<a href="#" class="social-icon" id="google">
<i class='bx bxl-google'></i>
</a>
</div>
</form>
Hello
how to create a todo list?
for each and every user who login must have his own todo list
you can by Session
this might be more appropriate for this question. I have a flask app that listens for events, i need a function or separate script to do polling to send data to the flask app. Is this better to just handle in the flask app altogether or should these be kept separate?
how do i download Django
https://github.com/bhagyajbijukumar/flask-quick-start working on framework over flask
hoping to make flask as powerful as django
Refused to apply style from 'http://127.0.0.1:8000/assets/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
im trying to submit my registeration form usng ajax , i keep getting this error ,im doing a django project
Solved
How tough is it to create a Flask app with authentication/user management, subscription management with Stripe/PayPal and a way control which pages can be viewed?
anyone ever get Not allowed to load local resource when sending data from django backend to frontend?
In this case I am trying to load a video from media folder
Got it figured out
<div class="cat-news">
<div class="container">
<div class="row">
<h2>Резултати:</h2>
<div class="row cn-slider">
{% for r in queryset %}
<div class="col-md-4">
<div class="cn-img center-cropped">
<img class='center-cropped' src="{{ r.image_url }}"/>
<div class="cn-title">
<a href="{% url 'recipe' r.id %}">{{ r.title }}</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
Can someone help me fix this so when its only 1 or 2 results the html doesnt look shitty 😄
can someone provide best practices for flask app dev?
hi anyone knows bs4 and selenium?
I can't extract data from one website, bs4 doesn't prettify whole document, I cannot get certain divs, they are sent to website via JS need help
for flask, where do you put objects that i want to use across routes and within the app itself?
hey can someone help me with django 3.1 I want user not to go back to login page after logged in once. Thanks in Advance.
just pass on the view that it should redirect to wherver u want it to go
return redirect('current user profile')
something like that
Hello
I want to make something clear
So the html files should only be in this route
Projectfolder/appfolder/Templates/.html files
Right?
And the css and js fils should be in
Projectfolder/Statics/ css and js
Right?
Oh im talking about Django
static
nope 🙂
Is the rest right?
but thats just a convention
yes
you can put em wherever you want and make it work
Ok thanks
if you have multiple apps in the project
you can put em wherever you want and make it work
@halcyon lion i did but the destination after the href="" in the html file but it didn't load the css files idk why
the templates should have a sub folder with the app name
the templates should have a sub folder with the app name
@halcyon lion oh thanks
in settings there is a link to ur static folder
and when u load i goes to that path
but use {% static 'path to ur css' %}
hello
i need help
that's how 174ms
size 255bayt but 174ms
this django framework
and when u load i goes to that path
@halcyon lion it said invalid syntax when i typed this in the settings file
copy the code
Where?
So i don't needto touch the settings.py file?
nope
Ok I'll try this
<link href="{% static 'css/style.css' %}" rel="stylesheet">
this is what it looks like for my project
Ok
db
@dark sorrel
What is dv ?
db *
Db*
database
Im new but u see in the settings.py file it is sqlite3
I didn't have the chance yet to see what is it actually
Im still at the beginning with html and css stuff
It is bootstrap
ohok
Are you advanced?
i try to help u
Ye thank you
explain me you'r prob
How much does it take building a website?
explain me you'r prob
@dark sorrel
Tge project doesn't load the css file idk what is the problem
time ?
@dark sorrel ye
I got some things to try that @halcyon lion said
ok
what is you'r website project ?
@dark sorrel lol im still learning walking with a tutorial
What do you think i should build after learning so i get a carrer
good
you need to learn
and when you learn something
you retry to do code with not tuto
^^
Ye
do you know python ?
good luck ^^
then it should be easy to get into django
then it should be easy to get into django
@halcyon lion i hope it will
I've been trying to make this work with django-cms but I couldn't figure it out: Make certain parts of the webpage (about, mission statement, etc...) editable by the admin.
hello
Am trying to deploy my project to Heroku, everything works okay, but when I turn Debug to False, I get an internal server error. Am using Whitenoise for static, I have gone through the most solution on StackOverFlow but none is working for me. The logs keep giving me a ValueError: Missing staticfiles manifest entry for 'css/animate.css' i have run heroku run python manage.py collectstatic, I have added a STATIC_ROOT, STATIC_URL, STATICFILES_DIR and STATICFILES_STORAGE I do not know what else to debug. Can anyone please help me with this issue?
hello i have doubt
Has anyone used DRF parsers?
I'm using the parser_class @parser_classes([MultiPartParser]) because my request has the header Content-Type: multipart/form-data but if I use it or not - it makes no difference, and it still works, and the request/response is the same.
What's the use case for it?
@somber fable so what's your doubt
can anyone help me with repl.it I am getting errors on my imports ping me if you respond.
@elder nest have you installed the modules first
yes
so what's the error
hmmm...
did repl.it produce that dependency file, or did you?
also are you getting any errors hovering over the modules in your .py file?
repl made that file
I dont get any errors in my code
its under packager files which is where I think it stores the packages because it uses a weird package thing
@native tide
hmm I'm not sure. If you have installed the modules (and the versions of the dependencies match the versions of the modules) I don't see why there should be an issue. Was there an action which led to the errors showing?
no I was able to start it once without adding in my code. It started after I added it in, but I took back out my code and am still getting the errors
Which is better Back End in python??
Django has a lot of stuff pre-built, so choose that if you want that. Use Flask if you want to have less constraints and freedom
Im just learning python and this isn't working ```py
from flask import Flask, redirect, url_for
app = Flask(name)
@app.route("/")
def home():
return "Hello! this is the main page <h1>HELLO<h1>"
@app.route("</name>")
def user(name):
return f"Hello {name}!"
@app.route("/admin")
def admin():
return redirect(url_for("home"))
if name == "main":
app.run()```
Does there appear to be anythin wrong?
What's a restful API??
Im following a tutorial
What's not working?
nevermind
I got rid of the app.route("</name>")
I wasn't gonna make anything out of it, it was just a example in the tutorial im watching
Yeah </name> doesn't look right to me. It should be along the lines of /<name> @native tide
Best resources to learn django??
If anyone of you can help with very basic flask #help-orange
I learnt it from Corey Schafers tut
Its amaing
Thx
Am trying to deploy my project to Heroku, everything works okay, but when I turn Debug to False, I get an internal server error. Am using Whitenoise for static, I have gone through the most solution on StackOverFlow but none is working for me. The logs keep giving me a
ValueError: Missing staticfiles manifest entry for 'css/animate.css'i have runheroku run python manage.py collectstatic, I have added aSTATIC_ROOT, STATIC_URL, STATICFILES_DIR and STATICFILES_STORAGEI do not know what else to debug. Can anyone please help me with this issue?
@twin sable I just needed to create static n staticfiles at the root directory in production
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
whats the best way for me to get web traffic metrics for self hosted site
ubuntu>python>flask>gunicorn
i have cloudflare active, jut not sure if i want to pay $20 for pro if there something else i can set up
Try using Google Analytics
You'll get a js script to add to your html code
Hope this helps
hey so I'm following a tutorial for web development with Django, I've come to the point where I try to run the Django server, but I keep getting a UnicodeDecodeError
I tried looking it up and all for the past hour or so, but I couldn't find anything that related to the issue I was having
I also tried to make a new folder and start a fresh Django project in it, same thing, I try to run the server and I get UnicodeDecodeError, here's the full thing https://pastebin.com/B8Pg5Fnu
would really appreciate some help here
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How can I have flask show a div in html?
Like you click a button, send post to flask, flask sends back to show div
Is there a way to separate django admin (superuser) from normal user?
i want to keep superadmin and regular user authentication different
both have different parameter to authenticate
ohh thats great, thanks! looks promising
@copper lagoon use the if block within your templates... ```jinja
{% if showDiv %}
<!-- show div -->
{% endif %}
wdym
i want to like show an element
like a div
if flask says so
@native tide
Yeah... that's the answer
Yo
What would showdiv be?
A var?
Like how would I update the var live
@native tide
@copper lagoon look up Flask templates to understand the topic more.
You said it yourself, press a button to make a div appear.
ye, but how does the button make showdiv
like how does the button interact with "showdiv?
@native tide
well go on the docs, search flask templates, and you'll understand how.
You'll press a button, that will set a variable (e.g. showDiv) to be true, and since you have an if block in your template, if showDiv is true, it will show you your div.
ok let me explain
so for example: on button click: get flask to make a random number
wait
bad example
I know what you're talking about. You need flask templating and you need to handle form submits.
I need to ask flask if something is true or false and show the div baesed on that
ik
i have that
so for example: i have a box: i want to on submit see if box value is == to something
i have that
and then have flask send back a show div thing
so like if box is 1: show div: green that says this
if box is 2
show div red that says that
@native tide
Have I not already explained how to do that, above?
well no
How not
well i get u can show div depending on a var
but if i have the page loaded
how can i update the var?
By submitting a form
yes, but i need to do stuff to the form
Yes, press a button, which you initially said.
You update the value of your variable, then pass it to the template. As I said above...
if form.validate_on_submit():
# update your variable, let's call it divValue
render(template, divValue=divValue)
Then you can do in your template
{% if divValue == "something" %}
<!-- do something -->
{% endif %}
<!-- add other if/elif statements for whatever you want -->
Yeah like that
hey so I'm following a tutorial for web development with Django, I've come to the point where I try to run the Django server, but I keep getting a UnicodeDecodeError
I tried looking it up and all for the past hour or so, but I couldn't find anything that related to the issue I was having
I also tried to make a new folder and start a fresh Django project in it, same thing, I try to run the server and I get UnicodeDecodeError, here's the full thing https://pastebin.com/epkF9SFz
would really appreciate some help here
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
What did you do before the error appeared? @rugged osprey
try forcing the runserver on an ip and port with python manage.py runserver 127.0.0.1:8000
This is likely caused by something in your computer configuration using non-ASCII characters
Can i put JS cdn scripts in my base.html template ? Would doing this always download the script, or only when prompted too?
didn't solve it, thanks anyway
I'll try to run the server from my other laptop tomorrow to see if that works
hmmm, yeah, this could also be caused if the name of your computer is not ascii, or if you are on linux and do not have a hostname set, or it contains non-ascii characters.
in fact, I am suspicious of that & in your file path, I would not expect this to be the issue, though it may be worth changing
I'll look into it tomorrow, thanks!
[2020-12-06 00:42:49,339] ERROR in app: Exception on request POST /customer/signup
Traceback (most recent call last):
File "C:\Users\bobal\Documents\PlasticTaffsCafe\venv\lib\site-packages\quart\app.py", line 1814, in handle_request
return await self.full_dispatch_request(request_context)
File "C:\Users\bobal\Documents\PlasticTaffsCafe\venv\lib\site-packages\quart\app.py", line 1836, in full_dispatch_request
result = await self.handle_user_exception(error)
File "C:\Users\bobal\Documents\PlasticTaffsCafe\venv\lib\site-packages\quart\app.py", line 1076, in handle_user_exception
raise error
File "C:\Users\bobal\Documents\PlasticTaffsCafe\venv\lib\site-packages\quart\app.py", line 1834, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "C:\Users\bobal\Documents\PlasticTaffsCafe\venv\lib\site-packages\quart\app.py", line 1882, in dispatch_request
return await handler(**request_.view_args)
File "C:\Users\bobal\Documents\PlasticTaffsCafe\main.py", line 70, in customer_register
email = (await request.form)['Email']
File "C:\Users\bobal\Documents\PlasticTaffsCafe\venv\lib\site-packages\werkzeug\datastructures.py", line 442, in __getitem__
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.```
<form method="POST">
<input type="input" name="firstname" placeholder="First name">
<input type="input" name="lastname" placeholder="Last name">
<input type="password" name="password" placeholder="Password">
<input type="email" name="email" placeholder="email@youremail.com">
<input type="submit" name="Signup" value="Sign up">
</form>```
i cant work this error out
What is the best library for scarping information from face-market into an sql database?
I think it might be you capitalize the email in your request post form
ah alright
[FOR HIRE] [FRONT END] [REMOTE] [FULL TIME]
Hey Everyone My Name Will,
I'm here today to let you all know that I will be giving away my services for free!! I have been a web-developer for 6-8 months and are happy to do anything for you as long as you have an idea!! In these 8 months I have made countless sites!!!
So.... What are you waiting for? Shoot me a DM and lets get coding your dreams!
Thanks for your time,
Will
What languages should I learn if I want to get into React, flash, and django
Because currently I only know python..
Which database is better for django??
not sure if this is the right place to be posting the question, do let me know if i should post it elsewhere instead.
I'm trying to write a web-scraper/script to automatically download images onto my computer.
So far, my script essentially downloads images by going to incrementing the page num, then appending it to the end of the url to go to the next page.
page_num += 1
driver.get(chapter_url + "/" + str(page_num))
page = requests.get(chapter_url + "/" + str(page_num))
I'm trying to stop incrementing whenever i reach an invalid url (e.g i reach page 27 when the chapter only has 26 pages).
I'm trying to do this by viewing the status code, and terminating the loop whenever the status_code != 200.
However, on the website im scraping, whenever an invalid url is passed, it brings me to the last page. I tried looking at the chrome dev tools, and i see that i do get a 302 status code, but whenever i print it out, the status code i receive is 200.
Why is this so?
My code, if it helps 😅
for chapter_url in chapter_urls:
# create chapter folder
chapter_num = chapter_url.split("/")[-1]
chapter_folder = manga_folder + "/" + str(chapter_num)
if not os.path.exists(chapter_folder):
os.makedirs(chapter_folder)
is_chapter_finished = False
page_num = 1
page_url = chapter_url
while not is_chapter_finished:
if page_num == 1:
# save the file and append page num onto url to access next page
try:
driver.get(chapter_url)
page = requests.get(chapter_url)
except Exception as e:
print(e)
if page.status_code == 200:
img_src = MangaReader.get_img_src(driver)
MangaReader.save_page(img_src,page_num)
else:
is_chapter_finished = True
break
page_num += 1
driver.get(chapter_url + "/" + str(page_num))
page = requests.get(chapter_url + "/" + str(page_num))
Hey, so I have a React Context to hold the firebase user, and a PrivateRoute component that redirects to login if the user is not logged in. However the route seems to redirect the user even if they are logged in.
This seems to be because private route fires off before the user is actually loaded into the object. How can I fix this? I have already tried a loading state but it doesn't work
I'm using reach router, gatsby, react, and firebase
When you spend 2 hours trying to find out why your cookie doesn’t work , only to realize that Chrome doesn’t allow Local Cookies 😓🤬
https://github.com/offthedial/site/blob/firebase/src/components/PrivateRoute.js this is the private route code
https://www.github.com/offthedial/site/tree/firebase/src%2Fservices%2Ffirebase%2Fauth%2Findex.js
This is the auth provider code
The auth context code is also in here
Hey guys so im doing react native navigation and its going downhill for me. You see I made this Touchable Opacity component: <TouchableOpacity style={styles.course}> <Text style={styles.titleCourse}>{props.name}</Text> </TouchableOpacity>
and then when I apply it(as clickable), it won't let me redirect to that "Screen":
<Clickable name={"Mathematics"} onPress={() => navigation.navigate('Mathematics')} />
--
<NavigationContainer>
<Stack.Navigator initialRouteName="Subjects">
<Stack.Screen
name="Subjects"
options={{ title: 'LearnJuan' }}
component={Subjects}
/>
<Stack.Screen
name="Mathematics"
component={MathModules}
options={{ title: 'LearnJuan' }}
/>
</Stack.Navigator>
</NavigationContainer>
frick react native i will go flutter
yeah I don't think we have enough people in this channel who do React Native
but if you head over to Reactiflux I'm positive there is someone who can help you with that @native tide
Thx
So, I'm trying to render my React landing page on localhost:8000, and this sort of works (kinda). I just don't understand why I can't use render(request, PATH_TO_FILE), why do I have to read the file then return a HttpResponse of it?
def index(request):
with open(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f:
return HttpResponse(f.read())
This is the error, but my template does exist at that route
(when I use render(request, path_to_file))
Also anyone a fan on React + Django? Do you guys use anything other than token auth? I've always been using that but I've heard you can integrate the two so they use Django's session auth, I don't know how to do that though...
@native tide have you built a portfolio yet?
Not yet, but I have done a few projects
is this allowed in django?
#stuff
text="woah"
return redirect("teacher",{'text':text})```
teacher is another function that renders a page
yeah you can redirect to another view
or you can use the reverse(url_name) and url_name is the name arguement of your path in urls.py
That'll redirect to your url and your other view will run
@native tide Just starting to learn React and will def use it with Django.
Would like to know how you end up handling auth with it.
I've only used token auth in the past.
guys i am confused between using REACTJS or VUEJS which should i go for learning and creating stuff ? SOMEONE HELP ME
Guys, i am using LoginView from the django auth system and i have no idea how to pass the form to my login template
I have 1 form that comes from the base template called "form" and it seems to not work as it should 😄
a really simple example
https://github.com/ms85py/django-jobservice/blob/2068177c106038c91702d4b0ff3e8ffd27e7e91c/menu/views.py#L27-L32
https://github.com/ms85py/django-jobservice/blob/master/menu/templates/menu/login.html
(please don't bully my django skills :<)
I used DRF token auth... On signup, I save the user within my model and assign each user a token. That token is returned in the response and is stored as a cookie. Then on every request that cookie is used to identify the user.
I didn't know the difference between session-auth and token-auth, they're eerily similar.
And it's good practice to not use JWTs as they're short-lived
I think that's the main way people handle auth between Django / React
and it has worked for me. But it would be much simpler if all the auth could be managed by Django, and I'm sure there's a way to do that
@pure thistle Both are good. I like React, but you won't go wrong with either
anyone know how i can actually register a domain name? im not really sure where to go to actually do it without getting scammed lol
Hello all 🙂
please tell me how can i hide Model name left side of input :X
it is from (forms.ModelForm)
can someone help me with a favicon
I tried this but I get alot of errors on my /about
def about():
app.add_url_rule('./images/favicon/favicon.ico', redirect_to=url_for('static', filename='./images/favicon/favicon.ico'))
return "<h1 style='color: red;'>I'm a red H1 heading!</h1>"```
I just started coding web stuff in python / flask so my /about is really simple
and I am just guessing on my favicon thing because I cant find anything about it
./ <<< is it correct path? in django it is like {% static 'images/fav.ico' %}
it is the right path I am trying this
try:
with open(file,"rb") as f:
data = f.read()
f.close()
return make_response(data)
except FileNotFoundError: return make_response("")
@app.route("/favicon.ico")
def favicon():
response = GetFile("./images/favicon/favicon.ico")
response.mimetype = "image/x-icon"
return response```
@snow sierra
./ means at any start
sorry don;t know flask as good as django :x
ok
quick question, don't know how to google it... when I load a page with requests that has some images in it (with img src tag), are these images already loaded somewhere to grab or do I have to request the img src again to really load & save the image to disk?
How does one make chat applications with Django and Flask?
Between Flask and Django which one is more suited for making real-time chat apps?
hello, I have a problem with python, I created a mini api for my discord bot (for a dashboard) which allows to see the list of server id, when I enter the url of the API directly in the browser works but when I make a request in my program it loads indefinitely
my python code
ListeId = requests.get("http://127.0.0.1:5000/Guild_Id")```
@app.route("/Guild_Id")
async def show_guilds():
guild_count = await bot.request("get_guild_id")
return guild_count```
in Master.py
and in my bot
from discord.ext.dashboard import Server
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_dash_ready(self):
print("Dash ready")
async def on_ready(self):
print("Bot ready")
dashboard = Server(bot, "localhost", 5001, "secret_key")
@dashboard.route()
async def get_guild_count(data):
return len(bot.guilds)
@dashboard.route()
async def get_guild_id(data):
ListeId = []
for guild in bot.guilds:
ListeId.append(guild.id)
return ListeId
if __name__ == "__main__":
dashboard.start()
bot.run(token)```
@woeful atlas When your page is loading indefinitely, have you checked the console? It can give you the status code of your request, and it may give you information whether it's being blocked by CORS or something similar
I'm building a Quiz application but am having an issue creating a "Next Question" button. My URL is using int:question_id/. So I want my url to go from question to results, then have a button for next question on the results page. I have tried a few things like "function forforward() { window.history.forward()", "<a href="details" class="next">Next Question</a>, as well as pageinator but nothing has worked so far. An suggestions?
@native tide When your page is loading indefinitely, have you checked the console? It can give you the status code of your request, and it may give you information whether it's being blocked by CORS or something similar
and I have no error
what is your response status code for your request?
in your console, which you checked, you should check the response status code of your request. (e.g. it's 200 if it's OK, etc.)
ah okay
the console hangs on demand
not sure on what that means.
[2020-12-06 22:35:14,407] Running on http://127.0.0.1:5000 (CTRL + C to quit)
[2020-12-06 22:35:25,143] 127.0.0.1:60016 GET / 1.1 200 1939 25585
[2020-12-06 22:35:27,324] 127.0.0.1:60016 GET /login/ 1.1 302 739 17581
[2020-12-06 22:35:32,715] 127.0.0.1:60086 GET /callback 1.1 308 587 12115
[2020-12-06 22:35:32,992] 127.0.0.1:60086 GET /callback/ 1.1 302 145 254699
>>>requet
That helps, can you elaborate on what you mean by "the console hangs on demand"?
Also, by the "console" I also mean the console in your browser. When your page is infinitely loading, Inspect Element and check the "console" there to see if it says anything
But if the logs tell you anything, it's that you should be looking at your callback route
the console sends a message when an action is performed, it sends a message just before processing the "request" and does not send a message afterwards (probably because it@native tide is still busy with this task)
console of the browser
there is no error in the browser console if I do the direct path (without going through login, I am already connecting
@native tide its good^^
Ok, well since the last response is from callback, I'd check that route
and
you know how to make python know it's a list?
because
[733727867195621499, 757231923507626037, 768410147835084820]
with for in
[
7
3
3
7
2
7
8
6
7
1
9
5
6
2
1
4
9
9
,
...]
not sure what your question is
that is a valid list
if you have a nested for loop you'd get that output
separate the elements of the list
python takes it like "[733727867195621499, 757231923507626037, 768410147835084820]''
and not a list
if i try:
type(ListeId1)
str
ListeId1 = "[733727867195621499, 757231923507626037, 768410147835084820]''
because
@dashboard.route()
async def get_guild_id(data):
ListeId = []
for guild in bot.guilds:
ListeId.append(guild.id)
return ListeId
to be precise
ListeId1 = await bot.request("get_guild_id")
well yeah, because you have " around your brackets, making it a str
no lol
and get_guild
async def get_guild_id(data):
ListeId = []
for guild in bot.guilds:
ListeId.append(guild.id)
return ListeId```
which gives me
ListeId1 = "[733727867195621499, 757231923507626037, 768410147835084820]''
ListeId1 = "[733727867195621499, 757231923507626037, 768410147835084820]''
This is what you told me. That's not a list, that's a str, so what is the question?
I get the list of servers with "ListId1 = await bot.request (" get_guild_id ")", which gives me a text and not a list, what I would like to know is how to get a list?@native tide
knowing that "get_guild_id" is "
async def get_guild_id (data):
ListId = []
for guild in bot.guilds:
ListId.append (guild.id)
return ListId "```
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
okay, sorry
that is quite strange
I don't know why it would do that, unless bot.request is tampering with the output. Are you able to call get_guid_id directly without bot.request?
maybe you could make your ListeId a global variable
then check out its type to try to pinpoint where its going wrong
i have do
for i in ListeId1:
text=i.replace('[','')
text=text.replace(']','')
text=text.replace(",","")
ListeId.append(int(text))```
Hey guys, how would I upload a file using a Flask API?
I'm working on a tool using flash where when a button is pushed on the frontend flask downloads a file on the backend to a directory on the server, how can I make a progress bar to show the download status? The progress needs to be shown when the 'install' or 'uninstall' button is pressed
function divideArray(nums) {
var evenNums = [];
var oddNums = [];
for (var i = 0; i < nums.length; i++) {
if (nums[i] % 2 === 0) {
evenNums.push(nums[i]);
} else {
oddNums.push(nums[i]);
}
}
//Tests the odd and even numbers
evenNums.sort();
oddNums.sort();
//Prints out even numbers
console.log("Even numbers:");
//Checking the array length
if(evenNums.length > 0) {
//If evenNums has even numbers, then print them
for (var i = 0; i < evenNums.length; i++) {
console.log(evenNums[i]);
}
} else {
console.log("None.");
}
//Prints out odd numbers
console.log("Odd numbers:");
//Checking the array length
if(oddNums.length > 0) {
//If oddNums has odd numbers, then print them
for (var i = 0; i < oddNums.length; i++) {
console.log(oddNums[i]);
}
} else {
console.log("None.");
}
}```
having an issue with the output
it seems to be reading the "1" before "13" or "15" and putting that as a number lower than "2", or for the even numbers "10, 14" before "2"
NVM figured it out, should have used function(a, b) to sort ascending order
Why are static files called static? is it becuase they cant be updated at runtime?
I tried adding videos to the static files directory and they wont seem to load on the website until the next restart of the server? Different approach I can use?
Feel free to @swift heron any responses, thanks
@swift heron you could make a route that forwards stuff like
@app.route('/staticalias/<path:subpath>')
def send_static(subpath):
return sendfile(os.path.join("app/static/", subpath))
hey guys, someone experience with flask right now? i have a question
I have basic knowledge but might be able to help
cool, so heres the thing (im just gonna copy paste it)
Im making a blog site with flask, and im using Sqlite to store all my writtings and images (just a string of where the image is stored) on a blog.db file, that is currently on the root of my project, but is that safe/a good practice?, once i deployed the site on a hosting site (this is my first big webdev project), will my database be safe?, in addition to this, im gonna set up an admin page which whole purpose is going to be to delete post and edit them, so i dont need to handle more users other than an admin one,so i could only enter the admin page with a password, is sqlalchemy safe for this?, adding to my oroginal worry
in short, i have hardcoded the path to my .db on app.py
surely thats not the best practice, i dont think thats even safe
and i have the db on root
I have no idea about database best practices sorry
I get the file loaded fine, but it wont actually display the video until after I reset the server
Do I perhaps need to use a media folder instead of static?
It's possible, I know there is a something you can configure to when you initialize the app that prevents file caching like that, it might be worth a go
Hey. i am new to all of this and in need of some help. is anyone aware of how to scan for eddystone url beacon from a windows laptop?
?help
i waant help
i want to do is 'if user login succesfully then i want a bot on top of my website' how cant i do that?[in django]
what you want to do with that bot?
Hi, I hope someone can help. I have a payload dict and there is one value I wish to replace by iterating though a list. For example I have "from\": \"2020-01-01T00:00:00\" and I want to replace the value of "from" with in turn, each item in the list called year_from. Below is my code so far but I get the error message of replace() argument 2 must be str, not list. Which makes sense but I don't know how to fix it.
payload="{\r\n \"groupBy\": \"BgtOcc\",\r\n \"timePeriod\": {\r\n \"from\": \"2010-01-01T00:00:00\",\r\n \"to\": \"2020-01-01T00:00:00\"\r\n },\r\n \"queryString\": \"([nationwide]: \\\" nationwide \\\") AND ([BgtOccFamily]: \\\"Hospitality, Food, and Tourism\\\")\",\r\n \"geography\": \"US\",\r\n \"includeTotalClassifiedPostings\": true,\r\n \"includeTotalUnclassifiedPostings\": true,\r\n \"offset\": 0,\r\n \"limit\": 1000\r\n}"
for "2010-01-01T00:00:00" in payload:
for year in year_from:
payload = payload.replace('2010-01-01T00:00:00', year_from)
i can help you @plush heart
ok describe you problem
hidden input not hide input
it is store in your html
show me ur view
form too
plsss go on https://www.w3schools.com/tags/att_input_type_hidden.asp it will clear you problem what is hidden input
@plush heart jst be qick, aint got much time
@plush heart does link solve your problem
like u dont want ratings as an input field?
i am also doing django this time
okay, now i get it...
this first day in this server i like it
add submit button and it will hide
when it click
usually avoid using {{ form.as_p }}
define the inputs on your own
or use a for loop, it makes the form more customized
good luck 👍
I need help with node.js, I wanna know if there is a way to use a server variable in the javascript for a ejs page. Thank you
Hey guys i have a question, Can i build a website using only python / how can i start learning to build websites?
..
Where can I learn?
this statement is spam
there r so many wesites
do i have to use django-rest-framework to implement AJAX request from a django web app with vue
https://sourcedexter.com/python-rest-api-flask/ this was a very helpful blog post to understand and get started with flask @mental prawn
I created a site in Python and for some reason I can only see the site on a computer I tried on the phone and it does not let me know why?
Someone?
Hey guys, I am working on flask project in which I have templates folder which have several html pages.
one of them is services.html and another of them is subscription.html
there is a button on services.html, on clicking that button the user should be redirected to subscription.html
How should I achieve this functionality??
I tried enclosing that button tag with anchor tag but what should I write in href?? does url_for works? if yes how?
@near bison Nope. I use ajax without it.
Just use the ajax like any other javascript and point it at an url/path, which will go to a specific function.
I created a site in Python and for some reason I can only see the site on a computer I tried on the phone and it does not let me know why?
@native tide please help
I realy need answer
did you deployed the site?
And return json like normal right? @Demi is there any issues that i should be aware of ? Security issues maybe
I don't know, if this is your first site then there are services that don't ask to pay for the first site
Then.... how to deployed?
@near bison Returns whatever the function returns. You can import JSONResponse to return JSON.
I am not the best person to ask about vulnerabilities.
I don't know, if this is your first site then there are services that don't ask to pay for the first site
@hoary marlin who
heroku
@native tide Also pythonanywhere.com
well try watching CODY SCAFER's, and did you use django or flask or deno for creating your website?
same here,right now I am creating one
wait I think you can use github pages to host too, if it's a static site
well try watching CODY SCAFER's, and did you use django or flask or deno for creating your website?
@hoary marlin its good...
@native tide because if you haven't hosted your site, you can only view it on the machine it's running locally on.
Which module u prefer to use to make a basic website for a beginner?
Pls ping me if u know, would be much appreciated
@native tide because if you haven't hosted your site, you can only view it on the machine it's running locally on.
@native tide oh thx
to be honest, if you are just beginning to develop a full fleged site, I would suggest django, you can use flask too if that's a static site. personally I won't recommend flask for big projects as you have to make your own project structure.
I would suggest Django if you want to keep doing that hobby and later turn that into your career, if that's not the case then go for flask
Oh ok thanks. Well seems like django is better in functionality also and overall also, so I will just go with django then
Wait, isn't flask used for managing web request?
In repl.it
I don't think so. well it is easier to manage project structure in django but since my team already chose flask because is easier to learn we are making our project with flask.
Oh
Then umm, u prefer me to go with flask if I want to learn easy and do some cool stuff fast
But django if I wanna learn it all and do the stuff slowly?
@paper moon I love Django and it was really quite easy to pickup.
Just like anything, there's a learning curve but overall Django was really fun to learn.
Lot of good libraries for it as well.
I am trying to make a discord.py bot dashboard website should I use flask or django I am hosting it on repl.it
Honestly it's just a framework. Use whatever you want to learn. Both will get you there.
Django has more built-in features but may take a bit longer to learn (though I doubt it).
Yea meaning Django has a lot of features included.
So you just import them without having to install extra libraries and get them working.
ok
def OAuth():
try:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(token_key,token_secret)
return auth
except Exception as e:
print(e)
return None
oauth = OAuth()
api = tweepy.API(oauth)
#^^^Auth setup^^^
like = api.favorites(screen_name='@NormalLadd',count=278) #grabs all of my liked tweets
media_files = set()
for status in like:
media = status.entities.get('media', [])
if(len(media) > 0):
media_files.add(media[0]['media_url'])
for media_file in media_files:#downloads the media
wget.download(media_file, out='G:\Grab Downloads')``` So I got the code to download something but it's JPG's and i'm stuck on how to make it a video format like MP4/MOV
Has anyone tackled pre-rendering with Django?
What approach did you use to implement it?
how does django model automatically include the sqlalchemy session?
does fastapi count as web development here?
So, I've deployed my website to gcloud, and my API requests were previously routed to localhost:8000/api/.... Now that it's deployed, how can I know the routes of my API requests?
I think I just had a brainfart. Localhost should be replaced by my domain name
would it be possibly to run selenium on a webserver so that it can do searches and give me results of stuff back on my website?
fastapi is a web framework so yes
yes but if the server is command line based you'll need to run it in headless mode
Django doesnt use alchemy iirc but the session themselves are due to a global state (just a global var)
i dont mind running in headless mode. currently i have a tkinter app that runs in headless and does a search of a website for me and returns a link and formats a response... long story short IT didn't like that so im researching how to make it into a website...
Its pretty simple, just setup like you would normally with selenium
and then for Firefox there's a Options class which you can specify headless=True and then set options=options in the driver
okay thanks. ive already got it running headless so ive got all that taken care of currently just have to research how to get it running in my webserver. i paided for interserver.net if you have any tips on that. im learning most of this from scratch
It should be pretty simple but make sure you're using an actual VPS otherwise you wont be able todo it as the default webhosting style systems dont give you enough control