#web-development
2 messages Β· Page 145 of 1
Looking for JS/CSS frontend developers for a Flask project.
Pay may be included, depends on a few things
We have a team already, we're 90% done with the project, its almost ready for launch.
We just need some more people on our team to help.
DM if interested
You'll know the details after u DM
Thanks !!
Can I use Flask to create a chrome web extension, without the need of JS/HTML?
no recruiting please
oh boy, my bad !
any other channel i can use for recruitment?
python discord doesn't allow for recruitment
{for something in iterable}
...
{% endfor %}
search up jinja2 loops
kool thx ...i resolved the problem tho.... thx !!
Do i need to create a database for a sign in page?
Yeah, but it depends on if you want to store your users locally or if you're interacting with 3rd party api
what would be the difference?
hmm ok thx
anyone here use django trans ?
Anyone know how to send multiple html files in the response in NodeJS ?
my heroku app does not recognize my local timezone, it shows local timezone as UTC, how to configure my heroku app to recognize user's timezone??
i am using pytz library of python
I believe that they should be served in different responses
What are you using for backend?
I just found it, thanks π
I have a question about Json Web Tokens:
Is storing access token in memory and refresh token in http only secure cookie would be good solution for frontend authentication?
im sorry backend?
Yep
backend libraries are things like django, flask, or express js which serve as an http server (and when configured correctly can also support non-http)
https://techterms.com/definition/backend
It's hard for me to explain what backend is, so i will just leave it there
The definition of Backend defined and explained in simple language.
You probably need a database and table in it for your users then π
memory like localStorage?
im somwhat familiar with databases but tables are new so ima find what that is
but thank you
Yep, just a variable @vestal hound
uh
thx for help
then if you refresh the page?
You request new token...
It is
yeah I guess that's fine
If you store it in local storage then it would be insecure, right?
So you can't persist refresh or access token
anything that allows execution of untrusted JS
Only thing left is http only cookie, right?
Can't then attacker get access token though? π€
by just making request to an api
in case of xss
@vestal hound I mean i would have to create a way to issue new token
With that cookie
But can't attacker make that request with xss?
To say api/auth/gettoken
or something
Because i have to get that access token in a first place
Because i though that having an endpoint that will issue a new access token based on your cookie with refresh token would be enough π
How can uninstall the dependencies that were installed when I installed python-dev-tools? I've done pip uninstall python-dev-tools, but I can still see A LOT of unwanted packages in requirements.txt π
use pipenv
How could I get data form my api/ send post requests to it locally, for example in my case I serve react through django staticfiles , but it triggers cors
how could I avoid using cors?
use django-corsheaders, your server is blocking requests because they are not from the same origin
how would I go about deploying my project? I'm using redis / celery / django channels, do I need multiple servers for this?
Well I am serving though staticfiles for the core reason to not use cors headers,the issue was that I was requesting from localhost instead of 127.0.0.1
And when I requested from there it started working
hmm, well as long as you are on the same origin, same port, and same http protocol you should bypass it just fine π
heroku has support for django, and if you're using redis, heroku has support for redis to, which is also used by django channels
hi everyone , i want to learn python for webpage with django , anyone know papers for i learn this
There are many good YouTube tutorials.
in terms of difficulty, is it easier to use heroku than AWS? I know learning AWS is a must but i've never properly deployed before (last time it was on gcloud and I followed a tutorial - I didn't learn much)
AWS is really not the hardest part
plus there is way more tutorials/free courses on AWS than there is on heroku
or gcloud
for that matter
so I would say go for AWS
hi!
anyone know how to take a nested list that was made using flask inputs, and use it in another file?
unfortunately, the bigger struggle for beginners is actually logging into the already pre-setup server on AWS/GCloud and setting up the files/server and all the stuff needed for the website
elaborate on and use it in another file?
the variable, i want to use it in the paramter for the function in another python file i have
that other python file
do you want to run it separately
or are you importing the code in that file
to your flask's py file
with import
?
im just using os to run that file if it recieved some data
because it has it's own variables it needs to be run, not only the function
if that file received some data?
or flask application
wait
i think i might have just fixed it
one second
heeey, the data transfer things worked
literally no idea whether you were running 2 files as 2 separate processes at once
or were importing one file into the other
but
doesnt matter anymore i guess
does anyone have experience with django? I need some help regarding static files
for websites?
here is a tutorial if your interested in django web framework
Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.
π»Code: https://github.com/codingforentrepreneurs/Try-Django
βοΈCourse Contents βοΈ
β¨οΈ (0:00:00) 1 - Welcome
β¨οΈ (0:01:14) 2 - Installing to Get ...
@native tide alright - thanks! I'll slowly learn AWS :)
in django?
nope sorry I dont use flask
no html file
basic question
?
pls
how can i know my site like www.mywebsite.com
where is the website
i have the file
and im hosting it
rn
and dont know where is my website
(no html file) built in html code into flask project
dude I only use django sorry I cant help you
can anyone help me then
just wait for a few hours people will reply or just search in stackoverflow
maybe this can help
ModelForm has no model class specified.
email = forms.EmailField()
class meta:
# which model is affected
model = User
# this is fields that we want in order
field_order = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class meta:
model = Profile
field_order =['image']
def profile(request):
u_form = UserUpdateForm()
p_form = ProfileUpdateForm()
context ={
'u_form':u_form,
'p_form':p_form
}
return render(request, 'user/profile.html',context=context)
traceback
Request Method: GET
Request URL: http://192.168.10.112:8000/profile/
Django Version: 3.1.7
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig',
'users.apps.UsersConfig',
'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "E:\django\Django-blog\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "E:\django\Django-blog\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\django\Django-blog\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "E:\django\Django-blog\django_project\users\views.py", line 26, in profile
u_form = UserUpdateForm()
File "E:\django\Django-blog\lib\site-packages\django\forms\models.py", line 287, in __init__
raise ValueError('ModelForm has no model class specified.')
Exception Type: ValueError at /profile/
Exception Value: ModelForm has no model class specified.
can any one help
html
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-button mb-4">Profile Info</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>```
guys may i ask for some docs or some video for displaying or filtering all own uploads of the user?
Is there any way I can get details of the logged in user, like I am checking if the user's designation is xyz then only a particular task should happen (in django)
find a domain hoster
what is a domain hoster
but how to find it
man
u can use github it has a domain and it is for free
i dont know this www.thisthingidontknow.com
wt is wrong with u
its not showen in terminal when i run the code
wtf
i will send a photo
ok
yes
send code
a website
of webserver.py or for the bot?
webserver
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def hone():
return "<h2>Web Server OK, Discord Bot OK</h2>"
def run():
app.run(host="0.0.0.0", port=8080)
def keep_alive():
t = Thread(target=run)
t.start()```
0.0.0.0 means you want your website to be accessible by anyone in your local network and anyone outside your local network (aka internet)
i have a flask app and a bunch of methods like
@bp.route('/somestuff', methods = ['POST'])
def some():
body = ({underscore(k): v for k,v in request.get_json().items()})
@bp.route('/somestuff', methods=['GET'])
def do_something():
result = []
body = ({underscore(k): v for k,
v in request.args.items()})
how does a decorator look like to wrap this "body" var into locals by default so i dont copy-paste this generator over and over again
0.0.0.0 or 127.0.0.1 stands for localhost
meaning it runs on ur machine
and is only available in your local network
127.0.0.1*
if you want it reachable from WAN you either have to NAT it with ur wan ip
or get a hoster and domain
and host it from there
would this port mapping automatically direct http requests to my pc?
thanks, so if i set up a dns would it automatically direct to my port without a port at the end?
no
dns is for domain names
oh i read it wrong yeah
if u have an ip and give it a A record you can reach the ip with ur domain
import time
username = "ddddddd"
password = "gddgdsf"
driver = webdriver.Chrome("C:\Program Files (x86)\chromedriver.exe")
driver.get("https://www.mysdpbc.org/sso/portal")
username_textbox = driver.find_element_by_id("Username")
username_textbox.send_keys(username)
password_textbox = driver.find_element_by_id("Password")
password_textbox.send_keys(password)
login_button = driver.find_element_by_id("login-button")
login_button.submit()
ok_button = driver.find_element_by_id("AUPAccept")
ok_button.submit()``` https://i.imgur.com/cMV3jxC.png and https://i.imgur.com/MjZtb2P.png
A record is just a simple name poiting towards a ip you need the computer or the router to perform DNS lookup witch in result uses a TCP conenction towards teh database and checks for ip with the domain
dicts = []
curr_date = pd.to_datetime(list1[-1])
for i in range(X_FUTURE):
curr_date = curr_date + relativedelta(months=+1)
dicts.append({'Predictions': transform[i], "Month": curr_date})
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values)
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
return response
```
Hi community, I m currently work on time series forecasting model on webpage, my problem is I would like to return my new CSV file with the predicted value and plot graph into the web under 1 function, I m wondering does any other ways can pass 2 different return value in one function in flask python, please share some tips with me! thanks in advance
your Modelform needs the subclass Meta - not the subclass meta. Small spelling mistake there π
Thanks alot man lol π€£π€£π€£ππ
so how to make it production server
buy a vps/dedicated server and deploy it there?
AWS offers a free tier
think heroku also has free tiers for certain requirements
same with azure if im not mistaken
i wanna host it as a production web on my pc
to host a website as a production
you want to rent a web server
and web server is basically another computer but in a cloud
isps give you dynamic ips
correct
the moment you get a new one the setup doesnt work anymore
and udh ave to reconfigure it all the time
there are free tiers like aws, heroku and azure
worst case a small vps is super cheap
I have a flask app and changeable text in html. How would I make it so there is an update button and it updates my mongodb database?
@smoky skiff the only thing I see is putting stuff from in my database into the html
I am not trying to display database info in my website I already am doing that
I am trying to update my database from text boxes in my website
oh
use post and make backend code to intercept any post keys
how would I do that?
you have a form?
You can use FlaskForm to get your user's input. Once the user submits the form, you can access the data within your view:
def your_view():
form = myFlaskForm()
if form.validate_on_submit():
# get form data
# return template with form passed
oh I like that I will try to figure out how to do that thank you
sure π look into flask forms and it'll fix the issue
@opaque rivet I can't figure it out and everything is giving me errors is there a good example that you know of?
what's the error?
RuntimeError: Working outside of application context.```
I deleted the code I had bc every time I fixed one error I got another so I need to work on it again
give me a little bit
@elder nest, welcome to PM me with some code and Iβll run through it with you quickly
Well, before I didn't have Webhooks that I could farm that data...now I do. Django is a beast, but it's good if you take the time to learn it
I feel like Flask is easier to get up and running
yep I've enjoyed using Flask
tried Django when I first played with Python, didn't go great as I sucked
but put me off Django. Sure I'd be fine with it if I tried it again, but Flask has been everything I need so far
Yeah, it's kind of a pain...getting all the middleware working etc
Django Question here:
I have been looking through the docs and haven't found anything about this, though I could just be looking in the wrong place. I am trying to make a form where several fields are repeated based upon the input to a PositiveIntegerField.
If you were to put in 4 in the PositiveIntegerField, 4 pairs of inputs would pop up. I am not sure how to make the fields variable based upon the input, could I just make 100(or some number) of fields and just hide the rest?
Anyone here ever tried beeware?
with Flask I would pass the PositiveIntegerField variable to template, use Jinja2 for loop to generate the input fields required in the HTML file. Likely solutions with JS that I would have no adequate knowledge of.
I don't see a category here for mobile dev so I thought web is the closest one.
I think this is what I need https://docs.djangoproject.com/en/3.1/topics/forms/formsets/ but I am not sure
@royal cove can you take a look at my question in #web-development?
if anyone has any experience with Django and wants to come help me out jump into Code/Help0
Can't vc rn
What is it for? maybe you can do it someother way
I think Formsets are what I need, however I don't really understand them. I am watching a tutorial now but if somebody could walk me through what I am trying to do that would be awesome
it's impractical to have user filling in 100 fields btw
I know, just theoretically.
Could I make 100 fields and then just hide them if they aren't required? I don't think that is the proper way to do this though
Why not just take the list of inputs in a single input field in the form of a list
^^ More user-friendly
for example, if a user wants to order 4 items, he could just type in "mouse, keyboard, monitor, headphones"
instead of typing each in a diff field
ion acc know what you're trying to achieve, but this sounds much more practical
That isn't what I need as these are the inputs for a robots pathing system and all of the inputs are in pairs. Is it possible just to put out 10 inputs(or pairs of inputs) and discard any that aren't used?
holupp
can you join a voice chat and I can stream a purely html mockup of what I am trying to do?
Maybe just DM, ion acc feel like joining a vc atm
will dm you a screenshot
Dmed you
On it
@mortal pike user submits number of fields they want, view parses that number and renders a new template which renders n fields (jinka2 template). What do ya think?
I figured out a way to do it all on one page without refreshing using Jquery now I just have to POST it to the backend using a form but I am not sure how yet
If i cant figure it out I think I will try that
User can just miss a comma or place an extra one
So it would be easier to make a list of fields that you can expand
Ye i DMd him a simpler and more feasible way
User*
Just append input fields using a js 'for loop' oninput event
I mean i wouldn't do that without framework π
You can't just do it from the backend, it'd just make a mess
He's using HTML for the front-end smh
If he's a beginner he can use do it however he thinks is ok
These frameworks can be overwhelming for beginners
Because you would have to learn html/css/js + Frontend Framework + Language you code backend in and backend framework
trying to deploy my flask app to my domain on cpanel using the application manager but i keep getting 503 errors
anyone know how to solve this
the basic code they give doesn't work either
SMH, fam, maybe help him solve the issue first loll
π
Yeah, refreshing the page isn't really an option
But working with jquery is pain π
it was an easy 6 line code sofar
It's not 6 lines
If we're talking about adding items into this form, deleting them and actually sending that to the backend
Was round 6 for the front-end stuff, the oninput, adding input fields and rest
form submission is diff
ive recommended him learning ajax form submission at earliest loll
Just on itself it isn't really useful though
I'm just saying that submitting form via ajax just on itself isn't doing much
It hits a view where you can do anything you want, anything
Ezpz
With the data ofc
I am really confused. About how to link the template with the json to the form rn
Just send the data via ajax to the url
That url hits a view
in which you get the post data and create entries in the Model using that data
Ez af
that doesn't simplify it though
It's just ajax, url and view
You ain't trying to achieve sum simple my guy smh
Put in the efforts, you'll do
Hi all, i am new to pyramid and i am trying to figure out Chameleon. Specifically (coming from jinja) i have something like this in my html file, i need to do this in my .pt template...
base.html
<head>
<title>MyApp - %{block title%} %{ endblock %}
</head>
<body>
{% block content %}
{% endblock %}
</body>
homePage.html
%{ block title %}My Awesome Home Page {% endblock %}
{% block content %}
<h1>Welcome to my Home Page</h1>
<p>This is the home page content blahblahblah</p>
{% endblock %}
Any idea how i can do this in Chameleon?
how is it please tell
whats wrong with this datatable filter query?
{
'if': {
'filter_query': '{trains} contains OBIS'
},
'backgroundColor': 'tomato'
},
{
'if':{
'filter_query': query
},
'backgroundColor': 'rgba(0, 116, 217)'
}
DataTable filtering syntax is invalid for query: local_end_time datestartswith 2021-03-29
is all my console gives me and i cant figure it out. ive been trying for the past hour
filter_time = 'local_end_time'
query = f'{filter_time} datestartswith {time}'
I've been having alot of trouble with a supposedly simple slider input in html/js
I have the element <input type="range" min="1" max="50" value="10" class="slider" id="thickness">
In my js I use var slider = document.getElementById("thickness");
howver the value I get seems to always be "" instead of a number
figured it out after I noticed it on my watch list
any ideas?
I think I am going to do this, it is much simpler. Any tips?
It'd be some real efforts also you'll have to submit the form twice
Neways, peaceout
Having to submit twice isn't really a problem so might as well use what I know
I new to web development , I am thinking of building websites using only html, CSS and JavaScript. Do one know how I can structure thiis challenge iin step
Any template or layout to follow for website design will be resourcesfull. Thanks
A mental model and a high level thinking- the way to think we one is task with building a website
Have one form where the user specifies n items (the number of fields). Once submitted pass this to your view, and render a new template passing down the n variable. Create a for loop within the jinja2 template to render n inputs.
If it has gotten to this stage it's an anti-pattern and it's why python forms are terrible.
What you could do is use Jquery and have some hidden divs within a hidden form on the page.
Take the value from an input (for how many fields is required) and then use jquery to modify the innerHTML of them divs to then show new inputs.
https://api.jquery.com/jquery.map/
I don't use Jquery, but if you used something like React this would be easily overcome (and nice)!
use a framework, e.g. vue / angular / react
I said the same thing, but eliminated a few steps loll
look into node.js for javascript backend libraries, specifically express.js
then integrate it with something like vue.js which is a really good javascript/html/css website combo
I have a Conversation Model which holds a ManyToMany field of the users in the convo
class Conversation(models.Model):
users = models.ManyToManyField(User, blank=True)```I am filtering this to get all the Conversations in which a user belongs to```py
u = User.objects.get(username=request.user.username)
convo = Conversation.objects.filter(users=u)```My problem occurs when trying to obtain a list which contains all the users per convo in which the user belongs to `print(convo.values("users"))` My current solution is ```py
for i in convo:
print(i.users.all().values("username"))``` but is there a better solution in which would not make me loop through a QuerySet thus having to hit the DB an unknown amount of time?
Okay dude thanks for suggesting @opaque rivet @candid meteor
im creating a new django project. i should use a virtual env right?
Yes ofcourse you should @frigid spindle
repl.it is not a replacement for venv though. like you can run your app for development there but when you eventually decide to put it up on production,
you want to have that venv and that requirements.txt
requirements.txt is similar to package.json right?
@frigid spindle kind of. just like package.json contains the dependency requirements, thats all that requirements.txt should have
however package.json also contains where to find scripts and other config files
requirements.txt simply lists all the python packages your project will require
and since python projects have loads of depedencies, this file is essential for big projects like web apps
in django?
okay yes, settings.py is where you store the configuration for the webapp
um i guess express doesn't have much of config or anything, but in django what you usually do is, instead of taking api keys and other values directly from environment, we read them all in the settings itself
advantages are that you get to modify those pythonically, and add other settings which env vars might not be able to hold
and, you get to raise errors if some variable is not present.
but not only that, it also contains setup information for middlewares, and initializers for apps.
basically configuration of the "Django" part of the app.
the "Python" details sit in pyproject.toml and/or requirements.txt, while django-specific details live in settings.py
has anybody here used the django rest's token authentication?
if yes, please ping me, I have some questions on how it works.
do you mean this: {% csrf_token %}
jwt?
hmm not sure, maybe, let me send you from where I am taking this
https://www.django-rest-framework.org/api-guide/authentication/
and where it says TokenAuthentication
Django, API, REST, Authentication
I think that might be what you are saying
sure, whats up?
type python3 in the terminal, or for django, python manage.py shell to interact with your models
well I have retreived the otoken from my auth view in react
but I am not sure how tonow check if Iam logged in in a different view
store the token within a cookie. When you make new requests to your views you need to include the Authorization header with value: Token <user_token>.
If your views have the TokenAuthentication decorator, DRF's middleware will check if the token is valid or not.
Thus checking if a user is authorized / logged in.
guys, why are django are that hard?
This should give you something you can loop through an access the usernames of each object. The statement below is only 2 database queries, and the queryset it returns is cached so looping through it (and just accessing a field like username won't incur extra queries). Hopefully no syntax errors π
conversations = Conversation.objects.filter(users=u).prefetch_related(Prefetch(lookup='users', queryset=Users.objects.values("username"))
Might be useful to have a read of the prefetch_related methods, Prefetch objects and django database caching:
https://docs.djangoproject.com/en/3.1/ref/models/querysets/
https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.Prefetch
https://blog.etianen.com/blog/2013/06/08/django-querysets/
Object Relational Mapping (ORM) systems make interacting with an SQL database much easier, but have a reputation of being inefficient and slower than β¦
it gets easier, just like any skill π
nah
i dont think so
oh alright, thank you very much
I am really very stuck with this. Do I have to use psycopg2 if I am using a Flask-SQLAlchemy?
Will Flask-SQLAlchemy work without psycopg2?
I believe you require it (but I may be wrong here), psycopg2 is just for the setup of your postgreSQL database, you can still interface it via the Flask-SQLAlchemy ORM
Thanks. That is the impression that I have too. Just need to use it to connect to the postgres db by using create_engine
Will try that once I have fixed the gunicorn.service file issue π« feels like one bug after another at the moment.
Is there an efficient way to migrate files from one Django project to another? I started a Django project to learn it, and now I have built most of a website I want to put into production in that same project, and I want to move it to a fresh project.
How make website page same as apple india in AirPods pro page???
Hello everyone, when I update custom user model object, password is not getting hashed, I can see it as plain text via django shell, also this makes log in process impossible as it checks for hashed password... any suggestion
Simple Django Question:
I am trying to make it so that when a button is clicked and a specific choices is selected the choices will change. I can't figure out how to make it so that both of these work at the same time. any help would be great
@opaque rivet ?
hi, i have this webapp running at 0.0.0.0:8080.
in the webpanel of the router i set portfowarding to 192.168.68.104 which is my local ip but when i try to connect via the public ip it doesnt work
hi
see what your ipv4 is https://whatismyipaddress.com/
and then connect to port 8080 there
IP address lookup, location, proxy detection, email tracing, IP hiding tips, blacklist check, speed test, and forums. Find, get, and show my IP address.
ip 0.0.0.0 reffers to the loopback witch is 127.0.0.1 witch means localhost so using public ip (shouldnt happen here unless it's a shitty framework) wont work
what?
0.0.0.0 makes it run for everyone on the network
localhost or 127.0.0.1 means its not accesible on other machines
It's not set to a ip so the router dosn't know where to redirect the traffic, so using 0.0.0.0 will not make it available for tohers you have to set a static ip
just for the lan it's available
You can but shouldn't
what is the django REST framework?
django model's inheritance is good idea? because when i save child model also save parent model
depends on your use case to be quite frank.
you could use jquery. With django templates alone, you can't manipulate the DOM without refreshing the page which is a bummer, leading you to have to learn JS.
library for API development for django
@opaque rivet I want to have 2 types of registration. Teacher and student and different fields. How better to override user model and then create 2 registration model class teacher (User): extra field and class student (User): extra field. or If I have only a User model and have choosefield (is_teacher or is_studen) and when user register then show another model and save its info (there will be different fields)
In that case you can have two seperate models (teacher & student) with both of them inheriting from AbstractUser so that you have access to the User fields and class methods.
ah so how can i fix this?@sterile sphinx
@opaque rivet And another method? For example, after registration, I will display another model form (info model) and connect it with a foreign key and save it.
or inheritance case
Set the ip to your computers ip and forward the port to the machine
just open cmd and write ipconfig adn get the ipv4 ip
Alright
what is best way for a beginner to build a chat bot? is there a library?
I don't mind it having to refresh, though I am stuck on a Urls issue rn
does chat bot use ML?
I think having both inheriting the AbstractUser model for both is the best option, you can add extra info w/ foreign keys as you like.
cool
well, in that case you can have the user submit a form with your inputs, then render a new template with a new form with the updated values.
it's a job for JS
not sure how I would do this though, I am really struggling rn
Depends on the chat bot
cuz to me chat bot need to be intuitive...
Well you can always make a chat bot that learns the common asked questions and imidetly gives the common best answer, shouldn't be too difficult implementing
without a library?
I never use a library but i'm sure there is one for python
What are you struggling with specifically?
By the way, this isn't a good way to do things and is a limitation of Django forms. JS is always the best option here. But, if that isn't an option for you, here is how you would do it:
- Setup 2 forms, one with the initial inputs you want, and another with the modified inputs.
def your_view(request):
# different forms (with different options, whatever they may be)
form_1 = Form1()
form_2 = Form2()
# if form_1 is submitted
if form_1.is_valid():
# render a new template, passing form_2
render_template('yourTemplate', form=form_2)
# then handle form_2 being submitted
else:
render_template('yourTemplate', form=form_1)
cant you build an api using just django?
You can but you don't need django
?
if you want to automate a chat bot without restrictions to what the user can ask, then it will be using ML (NLP) to process a response
yes, Django and DRF
is that a library or is it more than that?
it's a whole area of ML
are you using make_password() for the password hashes?
I used set_password() as suggested here
DRF?
did you save the user object after you performed set_password()?
rn yeap
my problem solved already
oh okay
you can create an api in django with a few simple commands, no?
Thanks a lot for your attention appriciated
π
Django, API, REST, Home
this is a whole separate framework
or is it within django?
does it matter? It's used on top of django.
I think just don't overdo it
is django mvc?
If you have some common fields in some models, like say you might have a Resource model
class Resource:
pk
created_at
updated_at
You could mark it as abstract in it's Meta and inherit from it
It's mvt
model view tempkte
could anyone help me with this? I'm trying to call a function which will wait 60 seconds without blocking my main thread and then perform a specified action.
def get_token(self):
for token, count in self.token_info.items():
# usage count of a token is 0
if count < 5:
# returns token and updates its count +1
self.increase_token_count(token=token)
# < HERE > I want to call a function which will wait 60 seconds (non-blocking) and perform an action
return token
so when I call Instance.get_token(), it will return token but also fire a side effect for 60 seconds.
there is probably a simple async solution, which I'm terrible at. any thoughts?
also are there any advocates for FastAPI? what is the use-case? when you want a fast API and have no need for django features (e.g. ORM / models / etc.)?
more like when you want to choose your own libraries (or roll your own data access layer)
also FastAPI natively supports async
Django REST Framework doesn't
can i use fetch api with python?
oh I see, I was interested in it but I don't like leaving all of django's features behind, thought I could just use it for a few data processing endpoints
Can I learn vuex before vue?
How would i do port forwarding? I have heard of it but have no idea how to do it
Sure, but why?
not familiar with either, saw a project with vuex that I wanted to use and wasn't sure if I can learn vuex before vue
@serene prawn
You would have to learn vue anyway if you want to use vuex
So learn vue first i guess π
ok cool. thanks
How do I make my django longingly page redirect back to the previous page after login? (For example, when the user tries to access a page that requires login, they get redirected to the login page, and then back to the original page.)
use the login_required decorator or the mixin
I believe they redirect the user to the login page and then to the prev page after logging in
I think you also need to set LOGIN_URL in settings.py
Hello. I'm using fastapi for an api server. How can cancel processing a request if the client cancel it, close the browser or switch to another page etc.?
guys how can i make host on my pc as a production server?
Hello their, i have a function name login in my home_views.py and i have a function dashboard in my dashboard_views.py when i'm login, it redirect me on my dashboard. But when i'm on my dashboard, how can i say to programm that my function dashboard inside my dashboard_views.py is the main function now for this page?
I don't use python but i think waht you are looking for is to make the function public so other functions from other files can reach it?
I just want to make sure that when I log in it redirects me to the dashboard function in my dashboard_views.py file
And right now it dosn't?
No look at my login function.
So you have 2 routes on the same host with diffrent functions is taht correct?
Yes ;)
So when you ar eon the dashboard you wish to perform what's on the left but first you wanna do waht's on the right?
Yes exactly
You got 2 options, either put everything inside the same file or remove the @app.route("/dashboard") over the left side and make the function callable in that file.py to the other file where you first called the code so all you do is execute a function on the right side
Hope i understood your question right.
Yes i think, thx :)
hey how can I store a list in flask sqlalchemy
Need help π¦ i run my migrations with the extnd with AbstractUser...
elation "users_customuser" does not exist
settings.py is AUTH_USER_MODEL = 'users.CustomUser'
Solved! π makemigrations 'appname' π
Hello again, i successfull call my function dashboard n my home_views.py but it doesn't change the route access.
Let us know what the issue is, and then maybe... @fair shale
How secure is otken authentication, as I am implementing it I feel like it is very insecure
could someone help me understand some details?
Anyone here that uses Mooshak can help me?! Please.
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'```
I'm getting this error from Django. I don't know how to fix this because I don't have the word "backend" anywhere in my code.
this is my auth.py
```py
from django.contrib.auth.backends import BaseBackend
from .models import DiscordUser
from django.contrib.auth.models import User
class DiscordAuthenticationBackend(BaseBackend):
def authenticate(self, request, user) -> DiscordUser:
find_user = DiscordUser.objects.filter(id=user['id'])
if len(find_user) == 0:
print("User was not found. Saving...")
new_user = DiscordUser.objects.create_new_discord_user
(user)
print(new_user)
return new_user
return find_user
Does anyone know how to fix this?
Traceback (most recent call last):
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view
authenticate(request, user=user)
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'
this is the full traceback
from django.http import HttpResponse, HttpRequest
from django.shortcuts import render
from django.contrib.auth import authenticate, login
import requests
client_id = "707641033210593351"
# Create your views here.
def home_view(request: HttpRequest, *args, **kwargs):
code = request.GET.get("code")
user = exchange_code(code)
authenticate(request, user=user)
return render(request, "home.html", {})
``` This is my views.py
did you specify the authentication backend in settings.py/
yeah
AUTHENTICATION_BACKENDS = [
'home.auth.DiscordAuthenticationBackend'
]
@opaque rivet
this is my file tree
not entirely sure. can you check if users are being created within your database? could it be that authenticate() is returning return find_user which is an empty queryset and not a user instance / None?
serialize it to JSON (it's a string then)
I'm curious in yoru thoguhts about this Strapi and Django mix?
I found most use Strapi as the backend and stuff like Nextjs in the front0end. I'm thinking about incorporating Django as a middleman backend to manage both Starpi and Nextjs.
What are some of your thoguhts?
https://strapi.io/integrations/python-cms
https://strapi.io/integrations/django-cms
The #1 headless CMS to build powerful applications with Python. Strapi is a new generation API-first CMS, made by developers for developers. Get started in minutes with Strapi and Python.
The #1 headless CMS to build powerful applications with Django.
Strapi is a new generation API-first CMS, made by developers for developers. Get started in minutes with Strapi and Django.
Can you elaborate
π₯΄
Hi, we don't allow advertising on this server, as per rule 6.
is there way to make a button that looks like this in django? Or do I need to use CSS/JS on a checkbox?
You can customise it to be like that with css
ok.
As an example https://www.w3schools.com/howto/howto_css_switch.asp
Thanks.
W3schools is hot
i agree
^^
Was making a full stack app using django and react. And i encountered this problem. I have made the index file,its inside the directory. But it is still showing error
This is my index.html
I tried to re "runserver" and it gave me this error
I have added static file in Settings
W3 schools can't get their facts straight, go to Mozilla instead π
json.dumps(your_list).
i don't know how else to elaborate.
Does anyone know how to take the console output and put it to a webpage using flask?
I want this:
To show up in a webpage served by flask, I've got flask handling file uploads and being able to execute commands with subrocess.Popen
So I switched to agsi and hypercorn in django and my static path broke so none of my website assets load. Anyone know why?
https://gist.github.com/PRA7H1K/f7802dad07466e5fb9d08a6ded10fa68 this is my code
Hi, can you suggest a easy to configure http web server for my django web site, Thanks
That's the end of this tutorial on setting up Django apps in production, and also the series of tutorials on working with Django. We hope you've found them useful. You can check out a fully worked-through version of the source code on Github here.
The next step is to read our last few articles, and then complete the assessment task.
Heroku or Pythonanywhere
Thanks
Hi
I've made a django app and deployed it on heroku
in the app the user logs in, i check the input password with the hashed password in db(using the bcrypt module)
this is ok in the local server
but on heroku
it shows this type error
could someone help me with this
(full code here - https://github.com/iameinstein/Djank/tree/deploy)
How are you saving the hash in the db? @ruby summit
using bcrypt as a binary field
And when you try to check the hash are you making sure that the variable that holds the binary hash is converted to hash?
Seems to me like u got a type error
@ruby summit
yes
ya it's a type error only
but
it's only on heroku
Send your code
Local != production environment
What file should I be looking for?
here
this one
@app.route('/database')
def database():
# generate some file name
# save the file in the `database_reports` folder used below
return render_template('database.html', filename=stored_file_name)
@app.route('/database_download/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
84
lol
line 19
Hi community, I m currently deploy machine learning model in web, I m referring the code resource, Does anyone know how to define the stored_file_name ?
I think you are passing wrong values. You are converting the pwd to bytes and the self.password is of type binary
Bytes are not the same as binary
uh ok
but then
y is it running correctly in development server
I donβt know, just trying to understand whats going on from what I am seeing
umm
k
does it have something to do with the db ?
like coz on heroku, im using postgres and locally its sqlite3
Yes obviously hahaha
They save variables differently
In postgres i think you can save a hash as is
It allows for a wider variety of types
You should probably stick with the same database
okay
but sqlite3 aint good for prod..
typo
it's a small scale db
Yea sqlite3 isnt good for production
Thats why you need to stock to postgres
Both locally and on prod
I am guessing you have the postgres server somewhere hosted
Just get the dsn and set it as an env variable
yes
aws
ok sure
i will try that
so will that solve the error ?
or do i need to change models
I mean since the only thing that changes from localhost to server is the database then we can only assume that it is the root of the issue
@app.route('/database')
def database():
# generate some file name
# save the file in the `database_reports` folder used below
return render_template('database.html', filename=stored_file_name)
@app.route('/database_download/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
Hi community, I m currently deploy machine learning model in web, I m referring the code resource that I shared to your guy, Does anyone know how's the stored_file_name will be defined like ?
cause I m getting this errorNameError: name 'stored_file_name' is not defined
The stored_file_name should be put under quotes to make it a string..
ββ
return render_template('database.html', filename='stored_file_name')
yes
ok thnx @rustic pebble
@drifting ore I got this error aganThe requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename='stored_file_name')
##response = make_response(new_data.to_csv(index = True, encoding='utf8'))
##response.headers["Content-Disposition"] = "attachment; filename=result.csv"
##return response
@app.route('/database_download/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
@drifting ore This is my code
π€
First, I was getting this error >> NameError: name 'stored_file_name' is not defined
Dunno actually man! I just know some basics of flask π
I see, anyway thanks for your commend @drifting ore
https://github.com/Discord-Bot-Maker-Mods/DiscordPanel does anyone know how i can get this working i got it hosted but it doesnt seem to work
like once i do the oauth2
it redirects to errors
Hey guys, I was wondering that if I delete a row with a File Field, will the file also get deleted? (In Django)
Hi how do I include pillow to work with django. I tried it and itβs not working. May I know how do I fix it. Please refer to this question to stack overflow for the full question. https://stackoverflow.com/q/66927383/15022111
I tried to include ImageField to my models in models.py of the model Topic. When I tried to migrate the model. It is not working. It says that I need to install pillow (which I did and when I tried...
Which python version are you using ?
Is it 3.6 above ?? If not ,maybe you might have to use a previous version of pillow (as in before 8.2)
I'm not sure anyway.
Thanks
Python 3.9.1
How do I install old versions of pillow.
Do I type pip install pillow8.1?
How do I install old versions of pillow.
Do I type pip install pillow8.1?
Is there any reason to bother with securing token authentication over just using sessions?
Hi how do I uninstall the previous version?
FastAPI issue.
{"detail":[{"loc":["body"],"msg":"field required","type":"value_error.missing"}]
Not sure what this message means, missing a field "body"? Working with Pydantic model with only one field, which I've included in the json body.
Iam starting with flask websockets, can anyone recomend me some good tutorial? Iam trying to build chat app
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
stored_file_name = filename
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)
##response = make_response(new_data.to_csv(index = True, encoding='utf8'))
##response.headers["Content-Disposition"] = "attachment; filename=result.csv"
##return response
@app.route('/graph/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how's the stored_file_name can be defined like? cause I m getting this error >> NameError: name 'stored_file_name' is not defined
cause I would like to store the new_csv_file into directory and retrive back from the download
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
Does anyone know how to solve, please help ~
guys i have one small doubt in jwt , after the successful authentication jwt is returned to the frontend , so imagine that jwt data contains the authenticated user's username ```
{
username : someone,
expires : 162834123
}
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
stored_file_name = filename
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)
@app.route('/graph/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how's the stored_file_name can be defined like? cause I m getting this error >> NameError: name 'stored_file_name' is not defined
cause I would like to store thenew_csv_file into directory and retrive back from the download
where is the stored_from_directory function ? you didnt define it
I have no idea how to define it actually
cause I refer this >> https://stackoverflow.com/questions/34009980/return-a-download-and-rendered-page-in-one-flask-response
but it dint mention how to define the 'stored_file_name'
Hi guys
I am storing binary data in a Postgres database
But when I query it
I get a memoryview type object
Could anyone tell how do I convert this memoryveiw into bytes ?
Python's memoryview has a tobytes()
np
send the whole code
@app.route('/transform', methods=["POST"])
def transform_view():
if request.method == 'POST':
f = request.files['data_file']
if not f:
return "No file"
stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
stream.seek(0)
result = stream.read()
df = pd.read_csv(StringIO(result), usecols=[1])
#extract month value
df2 = pd.read_csv(StringIO(result))
matrix2 = df2[df2.columns[0]].to_numpy()
list1 = matrix2.tolist()
# load the model from disk
model = load_model('model.h5')
dataset = df.values
dataset = dataset.astype('float32')
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
look_back = 1
dataset_look = create_dataset(dataset, look_back)
dataset_look = np.reshape(dataset_look, (dataset_look.shape[0], 1, dataset_look.shape[1]))
predict = model.predict(dataset_look)
transform = scaler.inverse_transform(predict)
X_FUTURE = 12
transform = np.array([])
last = dataset[-1]
for i in range(X_FUTURE):
curr_prediction = model.predict(np.array([last]).reshape(1, look_back, 1))
last = np.concatenate([last[1:], curr_prediction.reshape(-1)])
transform = np.concatenate([transform, curr_prediction[0]])
transform = scaler.inverse_transform([transform])[0]
dicts = []
curr_date = pd.to_datetime(list1[-1])
for i in range(X_FUTURE):
curr_date = curr_date + relativedelta(months=+1)
dicts.append({'Predictions': transform[i], "Month": curr_date})
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
stored_file_name = filename
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)
@app.route('/graph/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
this is the whole code
and the error
NameError: name 'stored_file_name' is not defined
@sage bluff do you have any ideas ? haha
lol idk
but stored_file_name should have the filename right ?
then why dont you ```
stored_file_name = 'somename.format'
hmm sorry, I dont get you, what should I write axactly?
.
nvm wawit for better help , i dont get your question either , sorry
but why do you even wawnt to move the data from one csv file to another ?
oh it is okay, thanks for your reply
how to ?
the new csv file is use to store the predicted value one
I think the stored_file_name is a NoneType here, have you checked its type?
Hey @lusty cloud!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
after creating a secondary application and linking urls, i get this
when i try to run my server
ModuleNotFoundError: No module named 'articles.url'
how did you "link urls"?
What you meant to do here was include('articles.urls') and be sure to register 'articles' in your INSTALLED_APPS
yeah... as I said, your code says include(articles.url). There is no articles.url. It should be include(articles.urls)
pip uninstall pillow
Thanks. Iβll give this a try
Hi, does anyone have website with django which is contain registration and chat? I have one i made by myself but i dont know how to connect between db and the site So if one of you can help me it will be very good too
no, i will chat with u in private
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'```
AUTHENTICATION_BACKENDS = [
'home.auth.DiscordAuthenticationBackend'
]
I'm getting this error from Django. I tried searching for a solution but I can't find one.
https://gist.github.com/PRA7H1K/f7802dad07466e5fb9d08a6ded10fa68 this is my code
Good day to all, me and my team on capstone are planning to make a website that accepts online meeting like zoom. Can someone recommend me what to use or what to embed to our website? (No, we didn't use wordpress so we can't embed zoom)
Hey guys
Someone know how i can make a website without a framework?
to be more specific how develop a back end without framework
Why do you want to do this?
learning purposes
Learning a framework is way more useful long-term though.
I understand your thought, but i like know how programming things really works
Use javascript then I guess. It might be possible to build a python backend without a framework, but it sounds unnecessarily complicated.
Ok, you know some material that explain how to make this with JS or some method?
Google.
What do you mean?
I need PyCharm Professional crack π
Why
there is a comunity edition witch is free.
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'```
AUTHENTICATION_BACKENDS = [
'home.auth.DiscordAuthenticationBackend'
]
I'm getting this error from Django. I tried searching for a solution but I can't find one.
<https://gist.github.com/PRA7H1K/f7802dad07466e5fb9d08a6ded10fa68> this is my code
user.backend is not a thing, remove backend from user.
Traceback (most recent call last):
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view
authenticate(request, user=user)
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate
user.backend = backend_path
AttributeError: 'method' object has no attribute 'backend'
this is the full traceback
I don't have user.backend anywhere in my code
it looks like it's in a init.py file
I highly doubt it's a django error most likely you caused the error on your end witch triggered an exception in django
oh ok
Looking at here i assume this is the file you are working on " File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view
authenticate(request, user=user)"
Yeah views.py is one of the files I'm working on
I included views.py, managers.py, auth.py, and some other files in the gist I linked above
I think the error is at authenticate(request, user=user)
The code in:
def home_view(request: HttpRequest, *args, **kwargs):
code = request.GET.get("code")
user = exchange_code(code)
authenticate(request, user=user)
return render(request, "home.html", {})
Indicates a error in the traceback, i would look for errors there, set a breakpoint see where the error happens and come back if you still strugle with finding it, i normally never use python.
But it's not quite as distinctive as its professional version
Community and proffesional does the exact same thing, they are IDE, if i was you i would uninstall jetbrains product as they are utter shit and just use a text editor instead.
I don't know, it doesn't sound like a good idea
def home_view(request, *args, **kwargs):
print("1")
code = request.GET.get("code")
print("2")
user = exchange_code(code)
print("3")
authenticate(request, user=user)
print("4")
return render(request, "home.html", {})
print("5")
``` @sterile sphinx print 4 and 5 didn't trigger
so I'm pretty sure its the authenticate
and managers.py didn't trigger at all
I don't know what authenticate function is but user=user is reffering to it's self but user is allredy null and user is equal to user means it's null unless user is a global variable?
the authenticate function is to call a custom authentication backend
Hello π
I am trying to do something in Flask and was wondering if someone could help me.
What do I want to do?
I am looking to make a basic messaging application that works without databases. I have made one with databases before but I am now looking to make one that is reliant on nothing other than itself. Don't get me wrong, I am not stupid. I know without storing it somewhere, it cannot be retrieved and shown to the user. But that's not what I want to do. I want to make it so upon the page being reloaded, the message is gone. So basically, User 1 inputs some text into an input field and presses the send button and then the other user (User 2) sees that text on their screen.
Can anyone here who knows selenium help me out with one really tiny thing thats frustrating me for the last few hours?
Using driver.execute_script("return localStorage.getItem('thing')") doesn't work, but when I do it in developer tools of the selenium firefox window, it works
all you'd need to do for something like that is have some kind of in-memory structure that holds send and received messages. If you want realtime posting, then you need to use websockets or have the clients poll periodically for new messages.
Hm. I saw some JS thing and it's called Broadcast Channel. Ever heard of it?
@sullen ridge Nope, I don't follow JS stuff
websockets is one way to do it, but it isn't always ideal. For instance, if you're using a shared hosting environment, it may not be possible to deploy it
another way is just to have each client use JS to periodically poll for new messages
but you don't need a database as such to hold the messages, a dict with lists would do fine
Well you can just use python, make a tcp listner and implement the websocket spec, it isn't hard at all.
hey guys, for wtforms, how can i add the attrs value and link them to bootstrap's form-control
this is flask
@swift wren Is there a package for wtf-bootstrap?
Does anyone want to work on a project together? It's a birthday reminder service.
dose it work with email? or sms
How can I serve react app with Django ?
serializer
make a view which handles any visits to the base URI /
def index(request):
return render_template('index.html')
You are going to have to go into settings.py and make the templates folder & static settings point to your static folder in your build directory once you have npm run build in your react app's root directory.
that way Django knows where to look for your React's index.html page π
@opaque rivet Thank you for help
i wonder if I can do SSR for my next.js app / django π€
I am currently working on building a website using Flask for the server backend
I cannot figure out how to create a hyperlink back to the index.html file
nvm literally just got it lol
in the views.py file , when we write let's say a function home
return render(request,'something')```
> where is request coming from? and what are we exactly returning?
Doubt : Django tech , level:beginner
I cannot link my css file with html...is there anybody who can help me..if someone has some time I can either provide detailed info here or in the dms
I am using django framework btw
I just tried to debug it nothing happening i did everything checked all the selectors and my main.html file again and again
also I tried to find help on websites and It won't help
post code otherwise people cant help
did you set your STATIC_ROOT in your settings.py?
Bro I did and I think this part lacks I think I did not import os property or did something bad there I'll send you ss of settings.py as I have access to my pc
well I'd look into your console and see what response it's giving you when you're trying to fetch your stylesheet. If it's a 404, you know that it's a settings error. Otherwise you have a stale cache.
I have a function which I want to run once when my server starts. I don't think I can use celery for this because it's not a periodic task. To do this, can I just call it in manage.py?
im making an api request with react
but its calling the endpoint twice for some reason
i have a seperate function that fetches the api, and i call the function inside of my component, and its calling it twice
your component is probably being mounted 2x, what's the code?
const ClipContainer = ({ title }) => {
const access_token = getAccessToken()
console.log(access_token)
return (
<>
<h2 className="clip-container-header">{title}</h2>
<div className="clip-container">
<Clip />
</div>
</>
)
}
im just testing it right now, so its console logging the api call twice
its a post request for refreshing access token, so its changing the access token every call
I'm trying to start into 'Django for beginners' and am not sure about starting my virtual environments. If I use PyCharm and create new with pipenv, I start with the pipenv active. Then I install django etc and am instructed to startproject. So, I get two sets of parens. Is this right?
(helloworld-JYK3ZMAd) (helloworld) C:\Users\XLT\PycharmProjects\helloworld>
- use the
useEffecthook with a dependency array (so it will only run 1x, unless your dep. array changes) , I don't see that in your component. - are you rendering the component 2x in some way? maybe passing a
keyprop which changes based off state?
looks like you have 2 virtual environments
yeah, that's what I was afraid of
im rendering it once on my app.js file and i am passing in a title prop, it is only being rendered once, pretty sure.
I am gonna try out using useEffect hook, havent tried that yet. Thanks
@opaque rivet so do I want to stop running the top level pipenv that was created when I started the project and only run the one that starts when i start the project?
I don't really know anything about virtual environments, but opening a new project w/ PyCharm and letting it setup the venv for you always works.
OK. I am ok with starting a project and letting pipenv start the VE. The book has instructions to then start a project which then starts a VE inside the pipenv top level VE... sigh...
maybe the book is focusing on setting up the venv yourself (without letting PyCharm set it up for you). You could do that, just setup a new project without a venv then do it yourself as the book is stating.
I think you're right. Book has us using a text editor and CLI. I'm using PyCharm and it sounds like what you're describing may be true. Thanks for your thoughts
using useEffect worked btw thank you @opaque rivet
e = e || window.event;
what does this line mean ? i see it a lot in javascript
e here refers to javascript event
|| is used as or in some coding languages
looks like its catching both js and window events?(would need a correction, likely wrong)
is django or flask faster?
when i go to try and retrieve my values from the models in unicode, its still staying as article object(1)
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=200)
pages = models.IntegerField()
def __unicode__(self):
return self.name
fixed
|| means or, if e is a falsey value (e.g. false, undefined, null, then e will take the default value window.event
use def __str__(self)
to represent each object as a string
i just spent a few hours coding and got barely anything done π€¦
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)
@app.route('/database_download/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how's the stored_file_name be define like and how to pass the New CSV file into stored_file_name? cause I m getting this error >> NameError: name 'stored_file_name' is not defined
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
Does anyone know how to solve? Please help ~
I have just completed a coding challenge from frontend mentor
any suggestion on how can I improve?
live site : https://roctanweer.github.io/todoApp/
repo : https://github.com/RocTanweer/todoApp/
Thank you!
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values , filename=stored_file_name)
Hi community, response.headers["Content-Disposition"] = "attachment; filename=result.csv" << My new file is being generated from here, so how do I pass my new CSV file into directory, so I can retrieve back from download button?
<a href="{{ url_for('database_download', filename=filename) }}">Download</a> Tag in HTML
This is my reference >>> https://stackoverflow.com/questions/34009980/return-a-download-and-rendered-page-in-one-flask-response
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000,
labels=line_labels, values=line_values)
@app.route('/database_download/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
I m currently deploy a machine learning model in web using flask python, Does anyone know how to pass my response.headers["Content-Disposition"] = "attachment; filename=result.csv" into next @app.route('/database_download/<filename>'), so I could retrieve back from download button?
<a href="{{ url_for('database_download', filename=filename) }}">Download</a> <<< this is my download button in HTML
bro I think the problem is with directory cause the pictures I linked with project are also not working let me send a ss
bro is it enough and what's the problem
Where's the static root?
What's the response code in the console, 404?
And show us the code where you're trying to link the stylesheet
How to make snake & leaders game??
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values)
##response = make_response(new_data.to_csv(index = True, encoding='utf8'))
##response.headers["Content-Disposition"] = "attachment; filename=result.csv"
##return response
@app.route('/database_download/<filename>')
def database_download(filename):
return send_from_directory('database_reports', filename)
<a href="{{ url_for('database_download', filename=filename) }}">Download</a>
Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how to pass my response.headers["Content-Disposition"] = "attachment; filename=result.csv" into next @app.route('/database_download/<filename>'), so I could retrieve and download back the result.csvfrom download button?
Hello, by doing the following can I grab returning data from my-route view?```python
@app.route('/my-route', methods=['POST'])
def login():
return jsonify({'data': data})
```html
<form action="/my-route" method="POST" id="form"></form>
const form = document.getElementById("form");
form.addEventListener('submit', function(event) {
event.preventDefault();
})
.then((response) => response.json())
.then(function(responseJson) {
var data = responseJson.data;
});
File "C:\Users\asus\PycharmProjects\djangoProject\taskmate\todolist_app\urls.py", line 2, in <module>
from taskmate.todolist_app import views
ModuleNotFoundError: No module named 'taskmate.todolist_app'
Anyone knows that where i did wrong importation
try this from views import <view_name>, <another_view_name>
check the spelling
hi all, im developing a website using flask for the backend and i was wondering if anyone knows how i can let users add events created by the web application to their google calendar using a button on the site? the google calendar api docs basically just say copy paste this code to make calendar do stuff so its really not helping π.
let me show the code where I am trying to link the stylesheet
Stupid question: if i setup google AdSense for my website do i earn money from only viewing website or viewers gotta click on ads?
what's the response code when you're trying to fetch the stylesheet
go to browser > developer console > network
let me render the site
you have modules within modules, that's not how you should be structuring your django app
as you can see my pictures and css is not rendering cause I styled my navbar so it looks like blue but nothing is rendering
I am a beginner don't know to much
no, I didn't ask that, what is the response code when you are trying to fetch the stylesheet
go to inspect element
go to network
refresh
Does anyone has any experience with web scraping? I'm trying to get the twitter username of the people who liked a post, but keep getting this as a response if I fetch this url: https://twitter.com/mcnabbd/status/1378352586458206212
The HTML response contains this block:
<p>We've detected that JavaScript is disabled in this browser. Please enable javascript or switch to a supporter browser to continue using twitter.com</p>
So it doesn't return the html of the actual page but a page showing an error message.
@lexfridman βHanging on in quiet desperation is the English wayβ
Pink Floyd
470
what does these errors mean?
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses (100β199)Successful responses (200β299)Redi...
@opaque rivet bro aplogise me I made a very basic mistake I made my static folder within the project instead of my app -_-
sorry for bothering
I really appreciate the help
alright. and yes, 404 means that the path to your static file (that you stated in your template) was incorrect
if you read through the link it will explain further
tysm once again
is there anybody who implement django with vue js before?
Not Me
for sure there is somebody xD
Hi,I always wonder what is the use of class Meta in django??
Hi!! I'm trying to many a One-To-Many relationship using SQLAlchemy but I can't link two objects directly. In pure SQL I'd have to do this:
-- Finding the parent of a child
SELECT p.*
FROM child c
INNER JOIN parent_children pc ON pc.child_id = c.id
INNER JOIN parent p ON pc.parent_id = p.id
WHERE c.id = 2323 -- example
-- Finding parent childrens
SELECT c.*
FROM parent p
INNER JOIN parent_children pc ON pc.parent_id = p.id
INNER JOIN child c ON pc.child_id = c.id
WHERE p.id = 32323 -- example****
Here's the model:
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = # TODO: HOW TO?
class ParentChild(Base):
__tablename__ = 'parent_children'
child_id = Column(Integer, ForeignKey('child.id'))
parent_id = Column(Integer, ForeignKey('parent.id'))
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent = # TODO: HOW TO ?
Can anybody with some experience give a tip on how to code that?
I am not sure but I think it has the same role as a self arguement have in a function...Again I am not sure
Rn My css file is linked with my main.html
but it doesn't render changes
Provides metadata for your class. e.g. if you're using ModelForm, you will need to provide metadata such as the model, the fields you want to include, etc.
hello, idk if its ok to ask this here but, any advice for start web dev with python?
Do a flask tutorial to start.
Or django if you want something more complicated but powerful.
i know in flask you can get parameters from the url like this py @app.route('/something/<para>') def something(para): return para But is there some way, I can redirect the user to a url by passing a parameter to the function and not the url. Something like this```py
@app.route('/something_else')
def something_else(para): # Redirect here and send paramenter in function, not url
return para + ' redirect.'
So you want to redirect?
You could do a return redirect(url_for('something_else')) perhaps?
Oh wait, I've not fully answered
but i also want to send a parameter. the thing is i dont want the user to see the parameter in the url
return redirect(url_for('function_name', value=some_variable))
ah ok that you mate!
you can just call the related method if you want to continue on the same url
this will change url
I've got two functions, a POST, and it redirects to anther function which is a GET, and I wanna pass a file over, but I want to keep the session alive, how does one make it "persist"?
Can you give an example?
I guess you will be getting file from a form post right ? like user will upload file ?
Yeah, I got the logic all drawn up
But this one part is missing
I get an error thrown to say the file does not exist when passing the file over to the function that is solely for a GET
upload = request.FILES['ufile']
path = upload.temporary_file_path
so I guess you should be able to use this url, you can pass while redirecting etc
Thanks, I'll give it a shot
guys
i did this
<img class="logo" src="images/logo.png" alt="sorry image not found" /
width="150">
and this
div.logo {
float: left;
}
but it doesnt work
i defined it
i did this too
logo {
float: left;
}
it dont work
@sacred prism "it dont work" doesn't tell us much. Can you put what you have in a jsfiddle so we can see it?
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
here
its a test site btw
how do i fix this?
this still puts arguments in the url
hey
i need help
how do i class an image?
I AM SO STUPID
NVM NO HELP THX
wdym class an image
Can someone explain to me what python library I would use if I need to full stack development?
Or libraries*
minimally, flask
so like
assume you just want to serve static pages
thatβll be sufficient
often you want to persist some data
that means youβll need a database layer, hence a database driver
you might want some dynamic behaviour on those pages
so youβll need to know JS
that can go all the way to learning a full library/framework like React/Vue/Angular
if youβre doing that your backend is probably just a HTTP API
you can also consider FastAPI/Django
Does anyone have recommendations for JS tutorials/videos, particularly ones that involve interacting with django forms?
I am working on making a template for serverless framework for django, and would love contributions/opinions on several improvements such as asgi support, wsgi workaround for running app on each invoking etc. Anyone here who has worked with serverless framework before or wants to play around with it?
new_data = pd.DataFrame(dicts).set_index("Month")
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv" #Want to return this response to auto download a new CSV file also
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000,
labels=line_labels, values=line_values)
Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone know how to return my response.headers["Content-Disposition"] = "attachment; filename=result.csv" and plot graph together, currently I m able to return the plot graph but no idea how to get or return the download with new CSV? Please share me some tips ~ thanks in advance
do i need a user in a model for django
Anyone know how to solve this, please help !
is it possible to have a different background for every page using Django?
So django can be used instead of the js based libraries?
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
response = make_response(new_data.to_csv(index = True, encoding='utf8'))
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting',
max=17000, labels=line_labels, values=line_values, filename = response)
@app.route('/download/<filename>')
def download(filename):
filename = filename
return send_from_directory(filename=filename, as_attachment = True)
Hi community, I m currently deploy a machine learning model in web using flask python, Does anyone excel in send_from directory, please share me how to return my send_from directory correctly? cause I want to pass my response to serve a download route, currently I only can return my plot graph
Error I got >> TypeError: send_from_directory() missing 1 required positional argument: 'directory'
send_from_directory(filename=filename, as_attachment = True) you passed 2 keyword arguements filename and as_attachment, but no positional arguement directory
oh, so what should I change ?
btw It is possible to pass the to_csv to next app.route and return back one ?
What do you mean?
@opaque rivet
@cedar pasture I dont know what you mean either. Plus I dont know your send_from_directory function. It needs a positional arguement, check the docs or your code if it's your own function.
I think what you're trying to do is make an API
Hi I work with flask restful with a database many to many
many sources have many categories and reverse
class Sources(db.Model,UserMixin):
tablename = "sources"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
source = db.Column(db.String(200), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
#catgeorie_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
categories = db.relationship('Categories', secondary=categories_sources, lazy='subquery',
backref=db.backref('pages', lazy=True))
def serialize(self):
return {'id': self.id,
'source': self.source,
'user_id': self.user_id,
'date_created': self.date_created,
}
class Categories(db.Model,UserMixin):
tablename = "categories"
table_args = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(200), nullable=False)
#source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
keyword = db.relationship('Keywords', backref='categorie', lazy='dynamic')
def serialize(self):
return {'id': self.id,
'categorie': self.category,
'date_created': self.date_created,
}
s = Sources()
c = Categories()
c.categories.append(s)
db.session.add(c)
db.session.commit()
when for a ressource I had to add a categorie for a given source
I used for the post
def post(self, id_source):
category = request.json['category']
categorie = Categories(category=category)
db.session.add(categorie)
but how to make the relation with the id_source that i sent in the url
with the source table
please help or give me a link for a flask community
!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.
Anyone know why flask wont serve background image from css even though I'm sure the css is correct?