#web-development
2 messages · Page 53 of 1
Can you send the newest version of the code
it's edited in the comment above
In the login_user() just add user not form.user
login_user(user) you mean?
Yeah
don't think "user" exists at that point
oh hang on, I thought user was just the string
hm the login logic works if i disable PWA caching tho
Man idk why you just wanna make it hard
haha I'm not trying to, sorry
Its ok
just want to learn how to use PWAs
just in case anyone was reading the above: the solution was to just remove the root url from workbox.precaching.precacheAndRoute 😄 don't ask me why or how that works tho
@patent lily I just saw your msg... Do I just have to import it?
what I should put from wtforms.validators import ?
from wtforms.validators import DataRequired, Length, (or whatever you needed)
man this problem is really bad now Im having another one
What?
form=Start()
if request.method=="POST":
print("yo")
try:
session["link"]=form.Link.data
except:
pass
link=session["link"]
res=requests.get(link)
print(link)
res.raise_for_status()
soup=bs(res.text,"html.parser")
Elem=soup.select("a.chapter-name")
ChaptersName=[]
session["ChaptersName"]=ChaptersName
for i in range(len(Elem)):
href=Elem[i].get("href")
regexName=re.compile(r'chapter_\w+\.?\w*/?')
regexFind=regexName.search(href).group()
fullName=regexFind.replace("/C","",1)
fullName=fullName.replace("_"," ",1)
ChaptersName.append(fullName)
ChaptersName.reverse()
chapterEnd=[]
link=session["link"]
chapterStart=session["ChaptersName"]
form.startChapter.choices = [ (chapter,chapter) for chapter in ChaptersName]
if request.method=="POST":
print("hi")
session["startChapter"]=form.startChapter.data
print(session["startChapter"])
if session["startChapter"]==True:
print(session["startChapter"])
Index=ChaptersName.index(session["startChapter"])
for i in ChaptersName[Index+1:Index+61]:
chapterEnd.append(i)
form.endChapter.choices = [ (i,i) for i in chapterEnd ]
session["endChapter"]=form.endChapter.data
print(f'This is Challegning{session["endChapter"]}')
return render_template("manga.html",form=form,link=link,endCh=chapterEnd,startCh=session["startChapter"])
#print("DANG")
return render_template("manga.html",form=form)```
What extension are you using?
The thing that I will say right now was working
not the "if sumbit" another one
What extension are you using?
@nimble epoch you mean python?
So when I try to get the value
of the SelectField it will return None first
So im trying to take the value from it and don't get None first
because now the program give an error if it return None
I have a lottle problem with itsdangrous timedjsonwebsignatureserializer
Anyone can help?
I dont know how to use serializer var in the verify_account_confirmation_token function
Whenever i try it give an error that says the serializer does not match or ....
Evrything is ok but any idea how to use the serializer var in the verify_account_confirmation_token function? I tried everything that came to my mind
Sorry I never heard something about the timedjosnw...
No problem thanks though
np
do you know what to do in the problem above
because really its annoying me now every time I say its working I got another error
Sorry but i dot think that its the time
But probably someone will😉
I have a lot in mind
I hope so... thanks anyway 😄
😁
My Django is Crashing on me and im kinda witless:
I am trying to render a custom form but it crashes with "call() missing 1 required positional argument: 'value'"
Im kinda confused by the error at line 0
nvm found the error
SHIT
If you upload a file, but you don't tell the app to save it to file system, does it stay in memory until reboot?
How should I approach writing functions for function based routes? In flask, or shiuld I switch to the other method?
Would these be the proper records to get both Sitenamehere.com & www.Sitenamehere.com working?

having an odd issue
im running flask on iis with wfastcsgi and i have ajax making calls to flask for data in a sqlite db
im getting a 64ms response time for a request when running the flask server, but im getting a 3.65 second response time when accessing the IIS server
im also getting nowhere near that disparity with any of the other requests
also, its only 9kb of data
havent been doing this very long and this is my first real project, any help or suggestions would be much appreciated
Is it legal to scrape a Facebook post? I don't need to scrape all the posts of a group or all the posts of a page or even user information just need to get the one post the url corresponds to.
Whether they want you to do it and whether it's legal are two separate matters
I am pretty sure they don't want you to do it. I don't know of its legality though
But you can't get help with that here due to our rules
Hey, I'm doing my first project with Flask. I've written a function that returns a dictionary d, and I've got a tab.html file. How do I display the contents of that dictionary (d.get(0) etc.) in the tab.html file. ?
Flask templates maybe
@mystic salmon
You'd return it to the webpage using the return render_template('tab.html', d=d)
then use jinja to display it
guys im getting a circular import error with flask
i've got an error in my flask app jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'endblock'. How do i fix this?
coro=<WebHook.webhook() done, defined at /home/eek/bumprv2/cogs/server.py:18> exception=PermissionError(13, "error while attempting to bind on address ('0.0.0.0', 80): permission denied") hi. Why do i keep getting this when trying to create an aiohttp webserver? how do i fix it? many thanks
@haughty saffron to attach to ports < 1000 you need to have root privileges. If you're using this for testing, pick something like 8000. If you're not, you should probably be using nginx to proxy in front of your server anyway, and it should handle the transition of permissions
so I created google service account to call the google api without auth, I added the client id to G suit and all, but it seems like I've no permission yet
<HttpError 403 when requesting https://classroom.googleapis.com/v1/courses?alt=json returned "The caller does not have permission">
anyone familiar ?
hey guys
how to change my css in bootstrap?
i'm trying to change links on hover and stuff
but its not workin
when i go directly to like>
<div class="nav-link"> </div>
and add a "style="color: white(example);"
it works
but at a custom.css it's not working
<a class="nav-link" href="/signup" style="color: cyan;">Signup</a>
@wild thunder
can you see those new rules from custom.css in the code? if you do, probably you need to increase the "weight" of your new rules to override default rules. if you don't - your custom.css not connected properly.
hmm, how do i do it?
simply try to inspect target element in your browser. you should see a lot of BS's default rules plus your rule
yep, so smth wrong with the way how you connecting your custom styles with the project
and how you build the main.css? are you running a compiler?
sorry, i didn't get it
first day on flask
i mean, my font from main.css is ok
it's showing the custom font
the file is being correctly imported i guess
so you applying your rules to custom.css, but you connecting main.css only. so either you compiling all assets (including custom.css) into final main.css (looks like it's not the case) or you forgot to connect custom.css to your project.
try to put custom.css into the same folder as main.css is located and add another line (<link rel...etc) with your new custom.css
oh sorry, i'm adding it to main.css
all my custom is inside the main.css
the monospace font
is inside the main
and it's being used in the page
cool. what's the rule for color you using in css?
seems correct. try hex to make sure
but when i add it in the html directly it works
i'll add hex
still not working, this is strange
also check the nesting for .nav-link rule in your css
just an example:
body .container .nav-link {}
instead of this try this
.nav-link {}
at least you should see that custom rule in your code, that's your goal for now
a.nav-link
not the best option) you won't be able to re-use it.
and you tried to clear browser's cache right?
just a small "hack": bring all rules back to css, open the file where you connecting this css and instead of main.css put smth like main.css?v=2
idk how to do it, but i'll leave it to fix another time
it's taking much time
haha
the idea is to put my game online
i've made a strategy game
and i want it to be player multiplayer
i'll end up using socketio (i just need to find out how)
Hi does anyone know Bottle?
So I'm trying to make a webpage to converty YT video to audio and download it
How do I do that?
How do I get the path to which the user would like it to download?
is there a very light way way of interacting with the JS on a webpage?
i just spent so long setting up selenium on my rpi and now that its all done
its so ridiculously slow
Would it be best for Selenium to give the page source to BeautifulSoup and then scraping like that?
@cyan bridge you could try ajax commands
say you have a /url_that_returns_data you use ajax and post to that, and do something with the returned data
<script type="text/javascript">
$(document).ready(function () {
$("#btnPost").click(function () {
$.ajax({
url: 'url_that_returns_data',
type: 'POST',
dataType: 'json',
data: { a: "örnek", b: true },
success: function (returned_data) {
// do some js stuff here
},
error: function (error) {
// do error handling
}
});
});
});
</script>
and server side:
@app.route('/url_that_returns_data')
def return_data():
return jsonify({
'myData1' : 1,
'MyData2' : 2
})
this is for posting data to server side, you can post javascript method names to the function, and return modified function name and call that function in ajax
@prime quartz You can use youtube-dl in the backend of your server
you get the url from a form or smt, pass that url to youtube-dl, make it convert to mp3, send the link the link to the converted file
@supple ridge yeah i had made the code for YT video to audio just wanted to know how to convert it to a web based app
Ohkay thank you :D
Oh nice, I'd recommend using Flask, it is really easy to use
you can just import your own python code in it
im having issues with circular importing db and models, whats the best way around? flask
Hey, do you know any good project about appointment setting made with django?
Hi all. i need a little help with django modeling, i'm a total noob.
is there a good fellow django soul to help 🙂
@native tide What do you wanna do with django models?
what information do you want to store?
im new and i am having troubles with relation models
i need a model with form to store 2 level of data, like hierarchie
class Users(models.Model):
username = models.CharField(max_length=30)
def str(self):
return self.username
class Buch(models.Model):
name = models.CharField(max_length=4)
user = models.ManyToManyField(Users)
def str(self):
return self.name
class AdmList(models.Model):
adm = models.CharField(max_length=30)
bukrs = models.ManyToManyField(Buch)
user = models.ManyToManyField(Users)
def str(self):
return self.adm
i know i am doing it wrong, but not what exactly
Seems to be working for me at least
What are you trying to do?
What error it gives you?
i need 3 level model. 1st can have multiple 2nd(2nd = list of 10), and 2nd level can also have one or more 3rd level
and they need to be chained, like django mptt
well, no errors but more like info on how to manipulate it and tag it in html
so you want to display them in html or want user to be able to create them in clientside?
in the end both.. i have the list of users(1st), and need to give them rigth to 2nd level. and within 2nd level there are sublevels which also need to be assigned(3rd)
Ok, now I understand
when model is done, i need a form which user can change through html
Ok
is there a hope for me ? 🙂
Yes
😇
ok reading, tell me please would that model i pasted support my idea?
thanks Terabyte!
i have another question....how can i query my model ? for front end tag
for example, for user=xx show all 2nd level, and if have 2nd show all 3rd in it.. like loop or something
how would you query my model for that kind of question
that have something to do with html tags, right? or in view...
If you want to just display all the model objects into html you make view like this:
def Home(request):
context = {
'hello': hello.objects.all()
}
return render(request, 'home.html', context)```
```html
# home.html
{% for hellos in hello %}
<h1>{{ hellos }}</h1>
{% endfor %}```
First you need to make views.py to get that object model
then you can use it in html
ok i see...i have managed to get all items, but how to sort them by user by level?
I highly suggest you reading and testing out the django documentation, it will be easier for you at the end.
Go there and read all of them in order and you will be pro in the end, and you can do anything with django after it
ok thanks
i see, thanks fir the time
hey how would i go about hosting my own website and writing it in html?
you can in theory host a website from your own computer, if your ISP will cooperate
in practice I suspect most people do what I do: pay $ to a hosting provider. I use AWS; linode is also popular
you have a lot of decisions to make if you do this
hi guys i want find python web development job some but i am new on web some one can tell me list of things i need to know as python web developer plz ?
like, do you want just a plain old Linux box, where you have to install python and the web server &c? Or do you want something preinstalled?
There are lots of cheap vps providers out there where you can host a fair amount of python stuff for ~4eur/m. Ovh is the one I use
@brazen iron find some job postings, and see what they're looking for
@brazen iron https://www.amazon.jobs/en/search?base_query=python+web&loc_query= e.g.
@quasi ridge ty
Can any of you experts check out #help-broccoli
Hey guys! Sorry for the really beginner question but may I ask how do I: Basicly press a button on a website; I am using beautifull soup and I need to press specific buttons to get to where I want to; How can I acomplish this? Sorry again! ❤️
res=requests.get(link)
Does anyone use any file-backend abstraction like this one? https://github.com/amol-/depot I'm looking for something more "modern" although I'm quite happy with it so far.
Guys im trying to do a Selectfield which when a user click It will remove it self and show another SelectField...How I can do this with flask??
Which channel helps with stuff like web scraping ?
I think you can ask here
I see most of people who need help with these problems ask here
@feral minnow Do you mean a completely different select field appears, or just a default option that "disappears" after the select field is changed?
at the bottom of my base.html template
<script src="static/js/jquery.min.js"></script>
<script src="static/js/popper.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
<script src="static/js/vanilla-terminal.js"></script>
<script src="static/js/my-script.js"></script>
<script src="static/js/toggle-term.js"></script>
</body>
</html>
I believe that this jquery not loading is resulting in my popover not working (this is that button that says left)
<button type="button" class="btn btn-secondary" title="" data-container="body" data-toggle="popover" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." data-original-title="Popover Title">Left</button>
You can find it working as it should here
https://bootswatch.com/slate/
You can see loading failed on jquery despite it working for everything else.
Also... if jquery isnt loading, why isnt it saying $ is not definied in error messages where im using jquery in other scripts
for some reason ive never been able to get the popovers or any of the JS based effects from that slate template page to work
If anyone could help me withj that that would be cool
well despite what it said that one time
127.0.0.1 - - [11/Apr/2020 15:28:09] "GET /register HTTP/1.1" 200 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/css/slate.css HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/css/responsive.css HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/css/bullstrap.css HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/css/style.css HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/css/ripped_google_fonts.css HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/js/jquery.min.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/js/bootstrap.min.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/js/popper.min.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/js/vanilla-terminal.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/js/toggle-term.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/js/my-script.js HTTP/1.1" 304 -
127.0.0.1 - - [11/Apr/2020 15:28:10] "GET /static/img/matrixcode.png HTTP/1.1" 304 -
everything is now loading
but popover still doesnt work
Fuck it, I found a CSS solution that works.
@outer apex A complete one
And if I can delete the options as you said and change the label but keep it this will work too
I tried it
But when I want to get the values
Its gives it to the two of them
<li class="list-inline-item">
{% if json.code == 50001 %}
<a target="_blank" style="font-size: 20px;" href="https://discordapp.com/oauth2/authorize?client_id=583016581647433751&permissions=8&scope=bot&guild_id={{g.id}}"><i class="fas fa-plus"></i><br>Add</a>
{% else %}
<a style="font-size: 20px;" href="/guild/{{g.id}}"><img src="https://image.flaticon.com/icons/svg/469/469291.svg" width="20" height="20" class="d-inline-block"><br>Edit</a>
{% endif %}
</li>
https://gyazo.com/8605cfa3803ece62ca3539326e30ea88
any idea why this circle is popping up
Because of the <li>
lmao as soon as you said it was the list i realized the mistake
lol
when your jinja templates are looking like this
{% extends 'base.html' %}
{% block sidebar %}
{% include 'login_form.html' %}
{% endblock %}
{% block leftbaralt %}
{% include 'login_form.html' %}
{% endblock %}
{% block rightbaralt %}
{% include 'main_noauth_side.html' %}
{% endblock %}
{% block content %}
{% include 'main_noauth.html' %}
{% endblock %}
{% block buttons %}
{% include 'main_noauth_side.html' %}
{% endblock %}
haha
I absolutely love JInja templates. They're by far the easiest way of splitting HTML up nicely
(that I know of)
This setup might seem insane from looking at it, but the reason for it is having the ability to remove the block
#leftbar-alt {
display: none;
}
#rightbar-alt {
display: none;
}
@media screen and (max-width: 576px) {
#rightbar {
display: none;
}
}
@media screen and (min-width: 576px) and (max-width: 992px) {
#leftbar {
display: none;
}
#leftbar-alt {
display: block;
}
#rightbar {
display: none;
}
#rightbar-alt {
display: block;
}
}
There is no question here, just showing my setup
but yeah its nice
I also do it that way so i can have duplicates of the same content in multiple blocks and only edit it one place
The reason is that at different viewports the content appears in different places
So I have a question... I learned how to set up a staging and production server on heroku
And I got around to thinking, what happens when you users find your staging server?
Is that to say that every web app I know has a staging server somewhere online
That we could hit if we spidered for it?
Why when I press the submit button a crsf_token shows on the url??
Im using flask
Instead of getting the value of the option that user Selceted
I have the {{ form.csrf_token }}
https://paste.pythondiscord.com/upihuwifaq.py -- generated HTML
https://paste.pythondiscord.com/iyilacaqah.py -- the template that generated the html
Not sure if this will help you but I do it like that.
{{ form.hidden_tag() }}
Put that at the top
Yup i put it
now I tried to put the csrf = CSRFProtect()
it give me a bad request :Bad Request The CSRF token is missing.
Ive never done it like that before
Is this the case with your using that If you have views that don't use FlaskForm or make AJAX requests
Or are you trying to implement that on top of a FlaskForm
Because you only do it this way
<form method="post">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
</form>
if you are not using FlaskForm
If you are, just do it the way its done in my examples above
I do it with flaskforms
<form name="ch" method="post" action="/manga">
<label> Start Chapter</label>
{{form.hidden_tag()}}
{{ form.csrf_token }}
{{ form.startChapter }}
{{form.submit}}
{% endif %}
{% if link and not checker %}
<form>
<label>End Chapter</label>
{{form.hidden_tag()}}
{{ form.csrf_token }}
{{ form.endChapter }}
{{form.submit}}
</form>
{% endif %}```
here's is my code
when I click at the submit button in the second form it shows the token instead of getting what user choosed
same. And your form is probably in python somewhere inheriting FlaskForm, so you dont need that method of putting the csrf token into the form when you are not using flaskform.
That hidden tag automatically places the CSRF token into the generated html where it goes.
I really don't think that you need that form.csrf_token, but correct me if Im wrong.
Also, you are missing a closing form tag on the top one.
In fact, thats why its printing it into your form directly.
the missing form?
Because you're only supposed to use that like this
<form method="post">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
</form>
But if you are having flaskform generate your forms
there is no way to put it there manually
So you use hidden_tag()
{% if link and checker==True %}
<form name="ch" method="post" action="/manga">
<label> Start Chapter</label>
{{form.hidden_tag()}}
{{ form.startChapter }}
{{form.submit}}
</form>
{% endif %}
{% if link and not checker %}
<form>
<label>End Chapter</label>
{{form.hidden_tag()}}
{{ form.endChapter }}
{{form.submit}}
</form>
{% endif %}
Try that
Check the generated html
that the csrf tokenm is where it goes
When I press f12 its not showing the token but it still shows it in the url of the page
if request.method=="POST":
checker=True
if checker==True:
session["startChapter"]=form.startChapter.data
print("t",session["startChapter"])
#checker=False
try:
Index=ChaptersName.index(session["startChapter"])
for i in ChaptersName[Index+1:Index+61]:
chapterEnd.append(i)
checker=False
form.endChapter.choices = [ (chapter,chapter) for chapter in chapterEnd ]
print(form.endChapter.choices)
session["endChapter"]=form.endChapter.data
print(session["endChapter"])
except:
pass
print("hi")
session["endChapter"]=form.endChapter.data
print(session["endChapter"])
return render_template("manga.html",form=form,link=link,checker=checker)```
A part of flask code
Wait hmm I wanna ask you so you said there's no need of putting the csrf token into the form when you are not using flaskform
But Im using flask_wtf?
No, its the opposite. That documentation you showed was for when you are not using it, for example if you make a form that is not a flaskform but you still need your token to safely make the form
read the top of it
do you have something like this somewhere
like what?
class LoginForm(FlaskForm):
email = StringField(email_name,
validators=[DataRequired(),
Length(min=4, max=32),
Email()],
render_kw={"placeholder": email_name})
password = PasswordField(password_name,
validators=[DataRequired(),
Length(min=8)],
render_kw={"placeholder": password_name})
remember = BooleanField("Remember?")
submit = SubmitField('Login')
yup
Okay so you are using FlaskForm
yup
class Meta:
csrf = True
Link = TextField("Enter the manga link here", validators=[DataRequired()])
startChapter= SelectField("Start Chapter", choices=[], validators=[DataRequired()])
endChapter= SelectField("End Chapter", choices=[])
submit= SubmitField("Choose")```
Oh
thx
yup
but its still putting the crsf in the url
I'm trying to think of what could make it do that
Do you have anything like this request.args.get in your route?
nope
I just have a form
not a flask form
which the user put a link there
but its work fine , it can be the reason of the problem?
I have something like this session["link"]=request.form["link"]
Does the problem come from flask code?
maybe the form.endChapter.data is the problem
I dont manage the session like that. But yeah, it might be coming from that. the only thing I can think of is...
I use code like this
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('home'))
And what that goes is if you get redirected to the login form, it tracks what page you came from. And it gets that from the request And it holds it in the url so that it remembers.
That is the only thing I can think of that would add something to the url
So I rally dont know about that
Thanks a lot for the respond and for request.args.get('next') its not working with the selectfield or with "me"
I think its coming from the submit button
because I commented the form.endChapter.data and its still showing up
try taking this out
class Meta:
csrf = True
Buit check and make sure the csrf token is being added to the html
I dont think you need that
I dont use it
I deleted it nothing happened... you mean in the html file?
Basically, when you finally get it working the way you expect, you can verify that the form is csrf protected by looking at the final product html that gets generated. Like, by hitting right click view source.
And if you look at the form, it will have the token in the form as a value if its working
but yeah im gonna let one of the other guys put their two sense in when they see this because i have no idea why it would put the csrf in your url.
maybe thats normal?
When it shows the crsf token in the source?
I found that for some reason when I saw the source the endChapter form have a input with an id="crsf_token" type="hidden", and a value which is the token that shows up at the url
oh thats bad
two of them have it the start and end
chapters
What is the site we use to share code ?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Thanks
I'm having trouble using apache 😦
on centos7
trying to deploy django project
and I'm using Mysql
I'm an nginx/postgres kinda guy... What specifically are you having trouble with? Are you referring to this https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/modwsgi/
@native tide yes
do i need to edit the wsgi.py file inorder to show the project content
or what
cuz i followed all the links that I could find and all gave me the same results
You shouldnt have to do that. You need edit apache2 files somewhere, depending on your os
look for this file httpd.conf either in /etc/apche2 or in /usr/local/apache2
<Directory /home/root/classroom2/myproject/static>
Require all granted
</Directory>
<Directory /home/root/classroom2/myproject/myproject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess myproject python-path=/home/root/classroom2/myproject:/home/root/classroom2/myproject/myprojectenv/lib/python3.6/site-packages
WSGIProcessGroup myproject
WSGIScriptAlias / /home/root/classroom2/myproject/myproject/wsgi.py```
I did edit my /etc/httpd/conf.d/django.conf
@native tide is it weird that apache called httpd in centos ?
I couldnt tell you because ive never used eithe apache or centos haha.
Have you looked over this
https://computingforgeeks.com/deploy-python-3-django-application-on-centos-with-apache-and-mod-wsgi/
It seems more specifically geared yto your exact stack
i did follow this tutorial 😅
damn
https://www.unixmen.com/configure-django-with-apache-centos-7/ it does seem multiple sources verify that is the right place for it.
Someone will come through here and know more about the stack than me
Look over this one and see if it has something you missed
journalctl -xe | grep httpd
That is actually a good sign because now you will find a logging error that has a more specific problem probably
-- Subject: Unit httpd.service has begun start-up
-- Unit httpd.service has begun starting up.
Apr 12 08:49:53 classroom httpd[2058]: httpd: Syntax error on line 353 of /etc/httpd/conf/httpd.conf: Syntax er ror on line 27 of /etc/httpd/conf.d/django.conf: </VirtualHost> without matching <VirtualHost> section
Apr 12 08:49:53 classroom systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Apr 12 08:49:53 classroom systemd[1]: httpd.service: control process exited, code=exited status=1
-- Subject: Unit httpd.service has failed
-- Unit httpd.service has failed.
Apr 12 08:49:53 classroom systemd[1]: Unit httpd.service entered failed state.
Apr 12 08:49:53 classroom systemd[1]: httpd.service failed.
check those lines
ok
IncludeOptional conf.d/*.conf line 353
and I don't see django.conf in/etc/httpd/conf.d/django.conf

solved
[Sun Apr 12 09:05:25.119869 2020] [:error] [pid 2382] [remote 185.203.52.171:80] mod_wsgi (pid=2382): Exception occurred processing WSGI script '/var/www/classroom/classroomCollegeV2/classroomCollegeV2/wsgi.py'.
[Sun Apr 12 09:05:25.119892 2020] [:error] [pid 2382] [remote 185.203.52.171:80] Traceback (most recent call last):
[Sun Apr 12 09:05:25.119911 2020] [:error] [pid 2382] [remote 185.203.52.171:80] File "/var/www/classroom/classroomCollegeV2/classroomCollegeV2/wsgi.py", line 12, in <module>
[Sun Apr 12 09:05:25.120009 2020] [:error] [pid 2382] [remote 185.203.52.171:80] from django.core.wsgi import get_wsgi_application
[Sun Apr 12 09:05:25.120028 2020] [:error] [pid 2382] [remote 185.203.52.171:80] ImportError: No module named django.core.wsgi
[Sun Apr 12 09:05:25.425054 2020] [:error] [pid 2382] [remote 185.203.52.171:76] mod_wsgi (pid=2382): Target WSGI script '/var/www/classroom/classroomCollegeV2/classroomCollegeV2/wsgi.py' cannot be loaded as Python module.
[Sun Apr 12 09:05:25.425118 2020] [:error] [pid 2382] [remote 185.203.52.171:76] mod_wsgi (pid=2382): Exception occurred processing WSGI script '/var/www/classroom/classroomCollegeV2/classroomCollegeV2/wsgi.py'.
[Sun Apr 12 09:05:25.425166 2020] [:error] [pid 2382] [remote 185.203.52.171:76] Traceback (most recent call last):
[Sun Apr 12 09:05:25.425224 2020] [:error] [pid 2382] [remote 185.203.52.171:76] File "/var/www/classroom/classroomCollegeV2/classroomCollegeV2/wsgi.py", line 12, in <module>
[Sun Apr 12 09:05:25.425321 2020] [:error] [pid 2382] [remote 185.203.52.171:76] from django.core.wsgi import get_wsgi_application
[Sun Apr 12 09:05:25.425360 2020] [:error] [pid 2382] [remote 185.203.52.171:76] ImportError: No module named django.core.wsgi
now let me try solve these
haha

I'm not used to seeing py files inside of /var/www/ -- at least nginx that is a vulnerability.
journalctl -xe | grep httpd
@native tide
yeah, learning how to search logs is the answer to all server problems
its never direct about errors
but it is in logs
sure
I've a question
I've some code that gets printed in terminal, is there a way to see that now 🤔 ,
or should I in a way change my code and print it to logs ?
does the code that gets printed to the terminal involve the user in anyway? If not, you can just have it logging to a file so you can check it later. Depends on the purpose of it. With a web app running on a server you typically avoid any type of user interaction through a terminal.
But if you want to keep track of whats going on, you can definitrely have it making log files
✅
@native tide I made a log file, I'm getting an error that permission denied
Have you created it with the root user?
yes
the error that I'm getting is from the server
not from the OS
"apache log errors"
The application is most likely trying to write to a file that it either doesnt own or it lacks permissions to. If you could navigtate to the file or the save directory where it should be, and type ls -l you can view the read write exec permissions of user group other. You might also compare the owner of that file to thee owner and permissions of your app.py file maybe? Its definitely a permissions or ownership error. Make sure you are writing to a location on the fs where thats makes sense
When it comes to hosting a website, how does scaling work? Do you have to worry about GIL, or does the framework, & everything else you use to host, take care of that?
I'm currently running Django/Apache2 & mod-wsgi, if that helps any
Also, the GIL is always released when doing I/O.
GIL should not be on the list of things to worry about
You want to look at mod-wsgi's configuration to set an appropriate amount of processes and threads to fully utilize the resources on your VPS.
and on a larger scale you can look at using load balancers to reroute requests to multiple instances of your service
for load balancing you can use cloud solutions from AWS or something similar, or you can configure one on your Nginx server.
I have a question related to flask_sqlalchemy
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
__tablename = "User"
user_id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50))
password = db.Column(db.String(50), nullable=False)
def __repr__(self):
return self.username
class Book(db.Model):
__tablename__ = "Book"
title = db.Column(db.String(50), unique=True, nullable=False)
author = db.Column(db.String(50), unique=False, nullable=False)
published_on = db.Column(db.Integer, nullable=False)
isbn = db.Column(db.Integer)
book_id = db.Column(db.Integer, primary_key=True)
average_rating = db.Column(db.Float)
total_reviews = db.Column(db.Integer)
def __repr__(self):
return self.isbn
class Review(db.Model):
__tablename__ = "Review"
review_id = db.Column(db.Integer, primary_key=True)
review = db.Column(db.Text)
reviewed_by = db.Column(db.Integer, db.ForeignKey("User.user_id"), nullable=False)
book = db.Column(db.Integer, db.ForeignKey("Book.book_id"), nullable=False)
rating = db.Column(db.Integer, nullable=False)
def __repr__(self):
return self.review_id
That is my models.py
when I run it in main(). I get this error.
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'Review.book' could not find tabl
e 'Book' with which to generate a foreign key to target column 'book_id'```
However I can see in adminer that the tables 'user' and 'Book' have been created.
@cobalt oyster might not be related to the error but in your User model the table name is missing the trailing underscores
I think it names the table by the lowercase of you model name in that case
Oh so that's why it was in lower case. Thnak you. I have tried it with lowercase too still can't find them.
I find this really interesting, because right above you're referencing the user model without any problems basically the exact same way
Yea I'm scratching my head here, would expect the reviewed_by to be the issue 🤔
You have made sure to reset the database?
If it helps I tried again wile correcting the duunder method and I have got this error report.
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching
given keys for referenced table "Book"
[SQL:
CREATE TABLE "Review" (
review_id SERIAL NOT NULL,
review TEXT,
reviewed_by INTEGER NOT NULL,
book INTEGER NOT NULL,
rating INTEGER NOT NULL,
PRIMARY KEY (review_id),
FOREIGN KEY(reviewed_by) REFERENCES "User" (user_id),
FOREIGN KEY(book) REFERENCES "Book" (book_id)
)
]
(Background on this error at: http://sqlalche.me/e/f405)
@native root wow I reset the database and tried again. And it worked this time! Thank you. And can you tell me why it worked?
@surreal tangle Thank you it worked!
It's possible for some things to linger
And I'm not sure how your database behaves with regards to capitalization
Oh so it's not my fault.
so it's possible the table got created and accessed case-insensitively
but sqlalchemy choked
"I created Table Book but Book != book so now what?"
kind of a general term for code getting in a thought-impossible state and erroring
oh I see. Im new to this. Infaact it's my first project so.. But thank you.
👍
hello everyone, I am feelin stuck a bit with multithread (don't know how can I check the number in thread (infinite loop). What do I need to do to make it right?
@app.route("/number", methods=["POST"])
def checkNumber():
number = request.form.get("number")
return (redirect(url_for("index_root")))
def worker():
while True:
val = random.randint(1, 100)
if name == 'main':
t1 = threading.Thread(target=worker, name='t1')
t1.start()
well first of all what you're doing is inherently dangerous 😐
you might get away with it but having different threads messing with the same variable is playing with fire
why not just have the checkNumber function generate the random number on demand?
as opposed to having a thread constantly burning up CPU, generating random numbers, 99.999% of which will never be used
I'm aware it's really memory consumable this way, i maybe did too much overengineering :/
it's really simple task - script generate random number, users enter some number, check if random number = user number than do something..
I don't think it'll use a lot of memory
it will use a lot of CPU, but worse, when you have multiple threads using the same global, there's a risk of corrupting the value of that global
and as you've described your task, there's no reason in the world it needs threads.
Threads -- Just Say No®
ok 🙂 thanks for pointing that out!
How do I check if django form field has nothing added yet
I tried
if len(str(Appointment.fullname)) == 0:
but it turns out error
Guys how to hide the csrf token from the source code for the html in my website??
because it showing up even though Im using flask forms
Or Is just because of the local host?
@feral minnow just going by flask template I'm using: <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
not sure if that's the correct/safe way of doing it, kinda took that for granted 😄
Im using flask form so they said that its hidden if you are using them anyway but it still showing them for some reasons
Thanks btw
for some reason Groups isn't translating here at production server
Is there a weird thing that I need to change in my code bec it's running on linux now ?
IDK
maybe its from your browser?
hmmm it works fine on localhost/ windows
but let me try another browser why not
wait what
!!!
wtf
it's a browser problem ffs 
I don't understand how this's possible, I like I literally have 2 tabs open.
one is running on the production server and the other one is running locally
What Did you set the language for the browser Arabic or English?
because sometimes it auto translate the page
You can disable it from the browser settings
~~the only reference to /img/chesspieces... is in the chessboard-1.0.0.js file as;
if (!config.hasOwnProperty('pieceTheme') ||
(!isString(config.pieceTheme) && !isFunction(config.pieceTheme))) {
config.pieceTheme = '/img/chesspieces/wikipedia/{piece}.png'~~
}
which I've tried adjusting the file path to to no avail!
cleared cache and it worked
Haha. It's always the bloody cache
Actually another question. I have a table I generate in the index.html calling a variable from the flaskapp.py
{% block index_content %}
<div class="container-fluid">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Username</th>
<th>Wins</th>
</tr>
</thead>
<tbody>
{% for i in details %}
<tr>
<td>{{i[0]}}</td>
<td>{{i[1]}}</td>
<td>{{i[2]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
it loads fine initially but when I refresh it disappears?
from flask import Flask, redirect, url_for, render_template, request
from AQChessLadder import win_list
app = Flask(__name__)
names = [--redacted--]
user_list = [--redacted--]
wins = win_list(user_list)
details = zip(names,user_list,wins)
@app.route("/home")
def home():
return render_template("index.html", details = details)
@app.route("/games")
def games():
return render_template("games.html")
if __name__ == "__main__":
app.run(debug = True)
@harsh flare So going to the route /home twice shows different results?
Why cant i receive my variables from the form?
Python
def kontakt():
if request.method == 'POST':
name = request.form.get('input_name')
email = request.form.get('input_email')
nachricht = request.form.get('input_nachricht')
else:
name = None
email = None
nachricht = None
return render_template('kontakt.html', name=name, email=email, nachricht=nachricht)```
HTML
```<form method="POST">
<div class="form-row">
<div class="form-group col-md-6">
<label for="input_name">Name</label>
<input type="text" class="form-control" id="input_name" placeholder="Max Mustermann" required>
</div>
<div class="form-group col-md-6">
<label for="input_email">E-Mail</label>
<input type="email" class="form-control" id="input_email" placeholder="max.mustermann@mail.de" required>
</div>
</div>
<div class="form-grid">
<select class="custom-select custom-select mb-3" required>
<option selected>Grund zur Kontaktaufnahme</option>
<option value="1">Problem</option>
<option value="2">Frage</option>
<option value="3">Sonstiges</option>
</select>
</div>
<div class="form-group mb-3">
<label for="input_nachricht">Nachricht</label>
<textarea class="form-control" id="input_nachricht" rows="3" required></textarea>
</div>
<button type="submit" class="btn btn-primary" disabled="disabled" id="btnSubmit">Nachricht senden</button>
</form>```
When i put in some variables and send the form using the submit button the variables stay None
@queen bough yeah, if I put the same url in again it just has no values in the table
but the table headers are still there
@harsh flare Which Python version are you using?
3.7
@harsh flare Add breakpoint() and you'll drop into a pdb prompt - you can then check what details contains.
def home():
breakpoint()
return render_template("index.html", details = details)
See if it is changing between calls.
@harsh flare You could think of Pdb as a python interpreter at that point (how cool is that?!).
So you can analyse all the variables at that point.
So in this case we want to check the details variable as it's probably what's causing the issue.
So just type details and press enter.
<zip object at 0x00000186C4E97C08>
OK, try list(details)
(Pdb) list(details)
*** Error in argument: '(details)'
fyi my webpage home is just stuck loading
is that due to the Pdb?
ahh cool!
Is it because it's a zip()?
Yeah. Can you convert it to a list?
details = list(zip(names,user_list,wins))
Hmm, I wasn't aware of the limitations of pdb (only started using it recently myself).
ok so if I run that I get my list back
Ah I see.
You have to set it to a variable:
lst = list(details)
(For future reference)
OK, now press c and enter
That allows the program to continue
So on the first visit to the page you should see the data.
OK, now restart the page and it'll "stick" on the breakpoint.
Yup, and analyse it again and see if anything's changed.
How is flask different from django?
@elder nebula In what aspects?
Yeah, there are similarities across all web frameworks (routes, templates, etc.)
Ok
Yes, it does, but different to flasks.
django is for heavy duty?
hmmm seems to be working now :/ lemme take the breakpoint out and see?
WHat are you doing with flask?
@harsh flare Sure, it could have been the zip. Try as is, and if it works and you want to investigate then remove list(zip and analyse details both times.
yeah that seems to have been the problem...weird
Might be interesting to investigate.
If you do, use lst = list(details) to convert details to list during debugging.
It returns a <zip object at 0x00000235F16BEFC8> twice but the second time it doesn't show it
Ah, interesting. Did you convert it to a list?
I think I know why.
zip returns a generator which can only be used once, I expect.
Yup:
>>> x = zip(['a', 'b'], [1, 2])
>>> list(x)
[('a', 1), ('b', 2)]
>>> list(x)
[]
oh wow ok! Thanks that fixed it. Great help! Wouldn't have known that at all¬
No problem, pleased that I could introduce you to Pdb!
yeah thats a great function¬
@wind merlin I'm not sure about this, but try using name="input_name" rather than id="input_name".
https://stackoverflow.com/a/32022575
ok this is a bit of curveball now. If I have a javascript script in the html. Can I call into it a variable from the flaskapp.py?
This is the javascript;
<script>
$(function() {
var cfg = {
pieceTheme: 'https://koblenski.github.io/javascript/chessboardjs-0.3.0/img/chesspieces/wikipedia/{piece}.png',
position: 'start'
};
var board = ChessBoard('myBoard', cfg);
var game = new Chess();
// 1. Load a PGN into the game
var pgn = {'1.e4 e5 2.Nf3 Nf6 3.Nc3 d5 4.exd5 Nxd5 5.Bc4 Nf4 6.O-O e4 7.Re1 Kd7 8.Rxe4 Qg5 9.Nxg5 f6 10.Qg4+ Ne6 11.Qxe6+ Kd8 12.Qe8# 1-0'};
game.load_pgn(pgn);
and in the python app I have a list of pgn that I would like to input there. I know how to do it in html with the {% insert python here %} but it doesn't seem to work ok there?
I'm not comfortable with JS tbh. Should I reference the variable further up outside of the function call?
@harsh flare what exactly doesn't work? you can use the jinja syntax "{{ }}" in the <script> portion as well, as long as it's part of the same html template
I'm having trouble with the fact that my static imports of css only resolve to valid paths if my urls are exampleurl.com/one-slash-in/
lets say I have exampleurl.com/one-slash-in/two-slash-in
That breaks all of my css imports
<link href="static/css/slate.css" type="text/css" rel="stylesheet">
<link href="static/css/bullstrap.css" type="text/css" rel="stylesheet">
<link href="static/css/responsive.css" type="text/css" rel="stylesheet">
<link href="static/css/ripped_google_fonts.css" type="text/css" rel="stylesheet">
<link href="static/css/style.css" type="text/css" rel="stylesheet">
Is there a way to write these in flask so that it just inserts the correct location for a static file?
I know that in Django this is very built in.
But I dont think the static keyword exists in jinja2, just in DTE
{{ url_for('static', filename='css/style.css') }} hopefully this will work
@surreal tangle Its a bad idea to mix templating and JS unless you really have to. The right solution is to set up the static path properly
(misread the problem, but its still a bad idea to mix templating and JS)
Really? Even small amounts of light JS, like you see enhacning bootstrap with popovers and subtle effects?
I would think you would only want it acting on elements in the base template at least.
You can normally achieve the same thing with templating in your classnames/ids, and having JS apply to specific classnames/IDs - but for small stuff I guess its not the end of the world. But when you're doing really any amount of logic in your JS it gets messy very quickly. Kinda like global variables, you start out with something tiny thinking it won't matter - then 2 hours later it causes massive headaches
It very much feels more like a bodge than a fix to any problem
I havent yet experienced that so I dont know it yet but I was wondering how I would pass logic from JS to Python if I ever wanted to. I dont typically use JS for logic at all. I just use it to make little effects in real time without refreshing. Its entirely for presentation.
BUT...
I did have this idea for implementing some JavaScript stuff eventually that would communicate somehow with my backend. But I dont yet know how easy that will be.
I will probably try it just if nothing else to learn the problems that arise from it.
But yeah I was wondering that
Are you talking about using JS frameworks with templating?
or literally no JS
Because it seems like it works if you dont go overboard
practically no JS - I struggle to see a usecase where you'd even really want it
huh...
If you're passing small data, it can be achieved with classnames/ids. If you're passing lots of data, you probably want to just set up an AJAX endpoint at that point
Like, I can see a world where you end up writing a json to a div
then making that div invisible
just to grab the content from it and get it in JS
but that seems hacky and terrible
That is more advanced use of JS than I have ever done. I might get to thinking about that as my JS gets better butr I have never done an AJAX request even.
Imagine this. Imagine that this text is way longer and the user can scroll down. But the login form will be left at the top. I can imagine a simple use of JS here to make sure the user is always feeling prompted to login or register, so that as they read they will become possibly more interested and the login is always right there.
As far as I know, neither CSS or templates can move that login form down as you scroll.
I'm pretty sure that can (and probably should) be done with CSS rather than JS
unless I'm misunderstanding, isn't this roughly what you want https://stackoverflow.com/questions/6786511/how-to-fix-a-div-to-top-of-page-with-css-only ?
https://www.w3schools.com/howto/howto_js_navbar_sticky.asp or something roughly like that. I'm rubbish at CSS unless I have a very specific problem to solve, but it sounds like it should be doable https://www.w3schools.com/howto/howto_js_navbar_sticky.asp
oh - that is JS the second link
I'm dumb (here's a CSS only version: https://www.w3schools.com/howto/howto_css_fixed_menu.asp)
let me have a look, thanks for the resources
I'm gonna have to play with all of these to see which effects they have. I am intersted to know if the CSS will do what I want.
None are exactly what you want, but I'm pretty sure position:fixed lets you do essentially or roughly what you want. CSS is very powerful at this point - a lot of the stuff that used to be the domain of JS, e.g animations, is now best done in CSS
Either way, its not the most important effect yet. But I do plan to add it. I was just trying to think of an example where a small JS effect would easily work with templates.
I think at the point of communicating what is going on in the JS back to the server to render templates or another page, that sounds pretty pain in the ass.
But if what you are doing ends in the browser's current page
why not
yeah css is powerful though
yeah, its powerful and hacky and difficult to pull off all the stuff you're doing at the same time
Adding one property drastically changes the way things work sometimes. CSS is pretty hard really when you start using it to advanced things'
Honestly I would have to create another branch before i started tweaking the frontend with css enough to accomplish this.
ERROR [root] Error: Can't locate revision identified by 'ee0758d7441c'
I'm getting this when I run flask db migrate
It happened after I edited my models, dropped my database, recreated it, deleted the the entire migrations folder
Now Im just trying to start over and it doesnt seem to want to let me
I figured it out. You have to delete the ALEMBIC_VERSIONS table
https://paste.pythondiscord.com/hefeceqije.py
this is my code for extracting news from a website....but when i run this command
scrapy crawl quotes -o news.json
i am getting an empty file
@surreal tangle and @rigid laurel I went to bed apologies. I can't seem to use the {{}} in the script as its within a function within the script it seems/
@harsh flare hm that shouldn't matter, everything in the html file passed through flasks render_template will go through jinja
but like charlie said, it would be preferable not to pass data to js like that. another endpoint in flask that you make a ajax call to is probably a better solution
It doesn't seem to want to read it if I just throw var pgn = {{pgn_list[0]}};
I'll have to read up on ajax calls. I'm not hugely savvy in this area
if you're sending it directly to a js variable try var pgn = {{ pgn_list|tojson }} ref https://jinja.palletsprojects.com/en/2.11.x/templates/#tojson
awesome that helps! realised I haven't properly formatted my variable now though. Gotta pull out the moves from the pgn
ergh
haha
I need a way to check if my database has been updated automatically
when there is a change in the database I want the database to automatically send a the latest information
Anyone know why my .py websockets/asyncio script would work just fine on my local machine; but error out on my aws insance?
I am getting error at self.id isn't a member of Post in Django models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('article-detail', args=[str(self.id)])
@round ferry Try self.id.
Like self.title and self.author.
I don't think it needs to be accessed any differently.
sorry its actual self.id
How are you calling it?
Yup.
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView
from .models import Post
# Create your views here.
class HomeView(ListView):
model = Post
template_name = "home.html"
class ArticleDetailView(DetailView):
model = Post
template_name = "article_detail.html"
class CreateBlog(CreateView):
model = Post
template_name = "create_blog.html"
fields = '__all__'
Also, what version of Django?
What's the command for version check?😅
Run manage.py shell and then:
import django
django.__version__
Or you could just use pip show django...
I get:
(InteractiveConsole)
>>> import django
>>> django.__version__
'3.0.3'
3.0.5
Error @queen bough
So it's giving the id is not member of self in the console?
Yup
OK, can you try this:
def get_absolute_url(self):
breakpoint()
return reverse('article-detail', args=[str(self.id)])
The breakpoint() function causes the program to pause execution there and you can analyse the program at that point in time.
Now you'll get dropped into a (Pdb) shell once you restart the page.
Ok, so where should I use it?
Are you in the pdb shell?
Use the code? You just need to add the breakpoint() line above return reverse...
Then allow the server to refresh and visit the page.
It'll pause and drop into a Pdb shell.
I am not in pdb shell and I don't know how to use it
As I said, first you have to add the breakpoint() line as shown above.
Then, allow the server to autorefresh.
Once it has restarted, refresh the page in the browser to trigger that line of code.
I have a question about parsing json values in help-phosphorus if anyone avail...
@queen bough Nothing showing
Did you refresh the page?
Yup
You should see a Pdb shell.
By "Pdb shell" I mean you should see a prompt like:
(Pdb)
@round ferry
Which version of Python are you using, by the way? This will only work on 3.7+
Hmm, what line did you put the breakpoint on?
Hmm that's interesting.
It seems that it isn't calling that function.
OK do you still have PDB on?
@round ferry
yeah
@round ferry Anything? Also, can you try something other than id? I've a feeling it's doing something else all together.
You're trying to connect it to the admin site, right?
Actually no.
What does your template look like (where you are calling post.get_absolute_url)?
No, I created blog creating template, when I tap submit button, error getting
Can you post the template line which uses get_absolute_url?
{% extends 'base.html' %}
{% block content %}
<h1>Add Post</h1>
<form action="POST">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-secondary">Post</button>
</form>
{% endblock %}
Where's get_absolute_url?
Something like <a href="{{ object.get_absolute_url }}">{{ object.name }}</a> according to the django docs.
In template I should use?
Hmm, I'm trying to work out how your template is working. That's all you have?
so to make a browser game in python what tools are best to utilise?
@queen bough yup
What does the rendered HTML look like?
I don't see a form anywhere - where does it come from?
{{form.as_p}}
What is form?
Link?
Whilst I'm looking at the doc page, could you change self.id with self.title to test if it is that causing the issue or not.
Ok
I assume you have form classes?
same error
id still?
Also, if you could load the first page in the browser and view source and paste the HTML, that would be very helpful.
Can I dm my gitlab link so you can check my files?
Sure.
Heya, I'm using Django and I have this code:
def event_payment_success(request, event_id):
log_report('info', 'EVENT_PAYMENT_SUCCESS | Succeeded for user: {}'.format(request.user))
instance = get_object_or_404(Event, unique_id=event_id)
subscribe_to_event(request.user, instance)```
The log_report works fine and displays the user model, but the subscribe_to_event is giving me: `CustomUser does not have attribute "user"`
This was working fine before and just started being an issue. Any idea what might be causing the hitch?
There's no more code in the function.
Ok... i figure it out... I had @login_required on the functions.
I still don't know why that would matter if log_report works correctly.
I've this function that brings for me the 'ids' which the user is selecting
studentsIDs = []
def list_students_id(sender, instance, **kwargs):
a = instance.students.values('id')
for i in range(a.count()):
studentsIDs.append(a[i]['id'])```
my problem is :
- I've another function that calls an api
- I want list_students_id() to get executed before the api function so I can use it's results in the api function
- problem is list_students_id() is getting executed at the end no matter what
How can I get the json data from a post request recieved by aiohttp?
I've set up a webhook that's triggered every time someone pushes a commit or opens a merge request in a repository, and I need the event name to differentiate between those two events. Here's the first part of my code: if web.json_response(data)['event_name'] == 'push': I was expecting web.json_response(data) to return the json data, which I could then get the value of event-name from, but I got name data is not defined.
Anyone experienced with Django OneToOne relationships? Looks like I need to create the connection for all rows in my two tables manually, that is insane. I must be wrong here
Oh hi @queen bough - Yeah, structured it as One To One. But they seem to create the objects through the shell, for EACH row? That is like, 500 rows in my case
I MUST have the wrong approach to this
There are 500 one-to-one relationship "map" rows?
@marsh ginkgo It would help if you could provide a bit of context as to what two models you are trying to create relations between.
from django.db import models
class Table1(models.Model):
created = models.DateTimeField(default=None)
published = models.CharField(max_length=50, default=None)
code = models.CharField(max_length=25, null=True, unique=True)
class Meta:
db_table = 'Table1'
unique_together = (("created", "published"),)
def __str__(self):
return self.created
class Table2(models.Model):
table1 = models.OneToOneField(Table1, on_delete=models.CASCADE, primary_key=True, default=None)
code = models.CharField(max_length=50, default=None, null=True)
url = models.CharField(max_length=100, default=None, null=True)
more = models.CharField(max_length=100, default=None, null=True)
class Meta:
managed = True
def __str__(self):
return self.code```
Just to clarify - 500 rows of what?
@queen bough Having a hard time describing it but I'll give it a go
My Table1 has a lot of rows, the column "code" contains a unique code for a company. The same column will exist in Table2 as well. But it looks like all the documentation out there creates the connection between Table1 and Table2 manually through the shell?
I thought you could tell Table2 to lookup a column in Table1, in this case "Code" and from there on create the "connection"
So that I could in the end present date such as published and url for code 9999
I hope it makes sense
I think I see what you mean - you are wondering how those connections are actually made automatically (without using the shell)? In that case, yes, it is an automated process - the shell usage is simply for illustration. In an actual project you would have a form which the user submits data to, and the view which handles the data would create both Table1 and Table2 and a similiar process to the examples will be done to create a relationship between them.
Hmm, Okay. But how do I actually create such a connection? All "codes" in Table1 exists in Table2, just don't know how to connect them
So that I could get data from both tables for the same code
Oh that would be as simple as self.table1.code
Sorry, I didn't see that last bit of code at the bottom.
And I've just overcomplicated everything...
Jezz, really? Tried one combination of self but didn't work. Not your format however
Yeah, table1 is an object and can be accessed like you normally would any other object.
I tried creating a few rows of dummy data in Table2, but I receive Field 'table1_id' doesn't have a default value. This is due to OneToOne, is it possible to autoincrement it?
table1 = models.OneToOneField(Table1, on_delete=models.CASCADE, primary_key=True, default=None)
Hmm, a MySQL issue by the looks of it:
https://stackoverflow.com/questions/8073734/saving-a-model-in-django-gives-me-warning-field-id-doesnt-have-a-default-va
Yes, there is an autoincrement field. Try:
id = models.AutoField(primary_key=True)
Not sure if you can set id.
But the OneToOneFiled is the id in this case, If i replace it with an AutoField I will break the OneToOne connection I suppose?
How would I get json data from a request using aiohttp?
@marsh ginkgo I'm not sure, but I expect the one-to-one is established after the id is set so it wouldn't matter. But you'll have to test it to confirm.
@marsh ginkgo If not, try the fix mentioned in the top post on that SO thread.
@mild merlin Would have helped to read the docs - https://docs.aiohttp.org/en/stable/client_quickstart.html#json-response-content
Hi I want to document my flask api. Should I use extensions like flasgger and connexion or directly use the flask-restplus @api.doc() decorator? Thanks!
https://stackoverflow.com/questions/56699115/timedjsonwebsignatureserializer-vs-urlsafetimedserializer-when-should-i-use-wha Just dropping this here for anyone that needs to see this. Topic: Flask token serializers
Hey everybody, I'd like to know if there's a possibility to check SSL certificates of websites by using python scripts
almost certainly
a dumb way would be to use requests to fetch any page at all via an https:// URL, and just see if you get an exception
might be all you need
I think https://badssl.com/ has a web server that deliberately serves up an expired cert, precisely so that you can test against it
do you know any site where I can see tutorials for that?
I am a total noob in this field
or any documentation would be helpful as well
>>> import requests
>>> requests.get('https://expired.badssl.com/')
Traceback (most recent call last):
raise SSLError(e, request=request)
...
requests.exceptions.SSLError: HTTPSConnectionPool(host='expired.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108)')))
>>>
just catch that exception
💐
can anyone tell me how to get today - 10 days in format YYYY-MM-DD
startDate = datetime.today() - timedelta(days=10) doesnt seem to work
What does your import statement look like?
And what error(s) are you getting?
actually looks like it is kinda working now
but how can i convert 2020-04-03 17:24:19.278143 to 2020-04-03?
nvm got it 🙂
👍
Can someone help me with access all json data?
I need to grab all values of results....here is json structure:
{'ticker': 'SPY', 'status': 'OK', 'queryCount': 3779, 'resultsCount': 792, 'adjusted': True, 'results': [{'v': 39356, 'vw': 270.81323, 'o': 270.75, 'c': 271.04, 'h': 271.14, 'l': 270.48, 't': 1586246400000, 'n': 196}, {'v': 23859, 'vw': 270.8784, 'o': 271.2, 'c': 270.93, 'h': 271.39, 'l': 270.66, 't': 1586246700000, 'n': 125}, {'v': 17563, 'vw': 271.16657, 'o': 270.88, 'c': 271.06, 'h': 271.38, 'l': 270.88, 't': 1586247000000, 'n': 98}, {'v': 13949, 'vw': 271.3289, 'o': 271.16, 'c': 271.39, 'h': 271.48, 'l': 271.16, 't': 1586247300000, 'n': 45}]}
i am using this code:
rawData = r.json()
cleanData = [{
'open': rawData['results']['o'],
'high': rawData['results']['h'],
'low': rawData['results']['l'],
'close': rawData['results']['c'],
'volume': rawData['results']['v'],
'timestamp': time.time()
}]
with open(os.path.join(sys.path[0], 'candleData.json'), 'w') as file:
json.dump(cleanData, file)
Problem is it is only saving the first record of results...not all
i am a noob
I am assuming you are tryling to replace each letter with the full name, i.e. o => open
yes
I want to take the original JSON, clean it up and save it in this format
which it is doing.....but only one row
rawData["results"] is a list of objects
like i said i am a noob....
srry
I did some refactoring and now my Flask app things there is no user loader.
Something like this should work:
cleanData = [{
'open': result['o'],
'high': result['h'],
'low': result['l'],
'close': result['c'],
'volume': result['v'],
'timestamp': time.time()
} for result in rawData["results"]
]
@outer apex that sure did! thank you!
Actually. the exact error im getting is
Exception: Missing user_loader or request_loader.
But its occuring on current_user which makes me think its user_loader, which is there. I dont have a request_loader and i dont know why thats for
I don't really understand, all I did was move two functions to a different file
Let me put them back and see if its something else
Yep it works as soon as I put them back
How annoying
haha
Here is the kicker
Then I move them back to the file and it doesnt care anymore.
Works fine.
God I hate when that happens. Now there is some weird error I dont know what caused it
You really do have to think of everything with web apps. For example, I got it all setup to let you get verified status by sending tokenized email but didn't realize you can just change your email after you get verified and then you have verified without being verified. I wonder what else I'm missing...
@native tide I'm back! Did you get your question answered?
https://stackoverflow.com/questions/39869793/when-do-i-need-to-use-sqlalchemy-back-populates -- this is why i love stackoverflow.
First answer is the perfect explanation of difference between back_populates and backref
Yes I know it
But I don't how to design it
Like a normal html form
Is it possible?
Oh so design it is pretty limited
If you would like to get classes and style into the forms...
{{ form.remember(type="checkbox",
class="custom-control-input",
id="rememberMeToggle",
checked="") }}
{{ form.remember.label(class="custom-control-label text-muted",
for="rememberMeToggle") }}
Here's an example
See how I put the class for putting bootstrap classes as a keyword argument?
Almost
Ya and then go to a css file and design it normally?
Yes.
You can also directly put style in with style="property: value;"
But its better to just use CSS files
and classes
Ya i see thanks 😁
what mistake i m doing?
i want to count every word in a article and arranging them with highest one first
Anyone here who knows django?
yes
nopes
Yeah
can u join the voice channel
Put you can then assign that to variable and make the view render it out
is there a way to use the django restframe work post request to store the data in a redis cache instead of a database
def count_and_save_words(url):
errors = []
try:
r = requests.get(url)
except:
errors.append(
"Unable to get URL. Please make sure it's valid and try again."
)
return {"error": errors}
raw = BeautifulSoup(r.text, 'html.parser').get_text()
nltk.data.path.append("./nltk_data/") # set path
tokens = nltk.word_tokenize(raw)
text = nltk.Text(tokens)
# remove punctuation, count raw words
non_punct = re.compile('.*[A-Za-z].*')
raw_words = [w for w in text if non_punct.match(w)]
raw_word_count = Counter(raw_words)
# stop words
stops = set(stopwords.words('english'))
no_stop_words = [w for w in raw_words if w.lower() not in stops]
no_stop_word_count = Counter(no_stop_words)
# save the results
try:
result = Result(
url=url,
result_all=raw_word_count,
result_no_stop_words=no_stop_word_count
)
db.session.add(result)
db.session.commit()
return result.id
except:
errors.append("Unable to add item to database.")
return {"error": errors}
You'll want to look into nltk to be honest, it will make everything you want to do easier. @nova storm
That was from a realpython exercise I did that you can follow if you want
search for realpython flask by example, and it will teach you to do that
hello?
is there a way to make a G Suite Hangouts Chat bot similar to discord.py?
i already have this: https://github.com/fffelix-jan/NTCS-PA/blob/master/ntcs_pa_discord.py
but i want to make it in hangouts
noob question, I want to use flask to use some discord api, I have a website ready, I don't want to change anything, just use flask to return some value using the api, do I have to do @app.route("something") or stuff
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/myfunction", methods = ["get"])
def myfunction():
do some stuff here
return value
if (__name__ == "__main__"):
app.run(debug=True)```
or do I have to do
@app.route("/")
def home():
return render_template("home.html")```
How do I show only one of object in django html if they are the same. For example
{% for q in query %}
{% if q.date == q.date %}
{{ q.date }}
{% endif %}
{% endfor %}
@elder nebula That's the kind of filtering you want to do before you pass the results to the template. Django's templating makes it difficult (sometimes deliberately so) to perform that kind of filtering in the template itself
Hey, can I make it so that I can access my website with a post request when I have a certain parameter passed, like a password, or should I just do random domain name that no-one can guess to store data in?
If not, how can I make the post request thing?
@blazing jetty In that case I'd tunnel the connection over ssh with private key access
then you can use a socks proxy to talk to the web server
The advantage of this is, you can set up the host dns as for any web site, but just not listen on port 80/443, but only on a random port for ssh access or just plain port 22
@cerulean vapor Should I make queryset?
@elder nebula It sounds like you should just make a query to filter the data ahead of time, yeah
Maybe use querysets, I don't really know what should I do. Hmm...
@wind merlin I'm not sure about this, but try using
name="input_name"rather thanid="input_name".
https://stackoverflow.com/a/32022575
@queen bough Thanks!
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
is there a way to get like a website "ping" in flask
What is the best web developer road map?
Guys
Its not ok if the crsf token
shows on the page source
Is there anything i can do
I used [
{{ form.hidden_tag() }}
but still not working
using flask
the purpose of the CSRF token is to be shown on the page https://en.wikipedia.org/wiki/Cross-site_request_forgery
Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF (sometimes pronounced sea-surf) or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts. Th...
it guarantees the client requesting data from the server is able to read the responses from the server, which non-whitelisted CORS domains cannot do, hence preventing CSRF
So its ok if anyone can see it?
yes, the point is to hide it from the AJAX requests of malicious websites
Im pretty new to programming so I don't understand what AJAX is
Asynchronous JavaScript And XML.
it's a request sent from the javascript of the page to the server
yes
here's reddit's login as an example
I redacted my CSRF token, but yeah
the CSRF token is generated with a secure session cookie and then checked against that when it gets a request
I was tinkering with frontend when I started noticing that as many things were starting to look really cool, just as many things were starting to break and look absolutely horrible. It was then that I remembered to ALWAYS create a new branch before you fuck with layout and style.
Now I have to figure out how to merge the cool ideas from one branch into the functional design of the other branch... which things dont work, which thinks were worth tinkering with.
at least in regard to CSS and HTML, the major thing is that its impossible to add things without breaking things (particularly in a responsibe design). I really haven't figured out how to add new design concepts without everything falling apart. I more or less know how to fix things once they start breaking but its tedious and hacky.
TLDR next time I decide to do this Im just starting with a new branch instead of realizing I should have done that half way in
Not sure if it is more appropriate to post it here?Good evening! Had a umm, VSC question? Or potential a django question? So I pulled some data from my models class and it works fine. But my text editor keeps saying that it is wrong, even though the code works just fine in a django shell and live.
How do I fix that?
guys where can i learn about flask app structure?
this has a list of flask template project structures you can learn from https://github.com/cookiecutter/cookiecutter#python
@patent lily There is no defined Flask app structure. You're free to do it however you wish, althogh you end up being confined largely by circular import problems that are hard to understand until you run into them.
In this Python Flask Tutorial, we will be learning how to restructure our application into a package rather than running from a single module. This has major benefits in terms of importing modules across our application. Let's get started...
The code for this series can be fo...
A starter for your Flask app. Kind of like sourdough starter, but less tasty.
Here are two different approaches to the problem.
Also, I will have to check out the cookiecutter thing.
On another topic, I am writing my first AJAX request 😛
I feel so dirty.
hi , im sorry new here and i dont know where to post this but im using selenium, juypitrt
webbrowser.open_new('www.google.com'), i canno even open this , any one got any idea
yes i am using import webbrowser
trying to open chrome>then get to said site
How can I make a route in Flask like
/gift?code=random_code?
Please ping me when reply
I solved it nvm
Is there any reason why when I've pushed my flaskapp to a Linux server and nginx, the app loads fine, the web pages load, but my JavaScript isn't working? Ibe tried pointing the refs to the .js files in static the same way as it was on windows and tried other ways.
Hey Guys,
i am in the process of learning Python, and started to take a look at Django.
Since i am at the beginning of learning, i think its a good time to ask, what i should learn and what is not important.
The tutorials i watched about django dont cover the front-end, wich is fine, but important i guess...
what should i learn to at least understand the frontend part?
is angular a good descision in combination with django? (is it possible?)
i just take notes from the answers and will go back to google, to read about them 😛
(just pm me with your suggestions)
~~nvm i didnt just say that ~~
is there a lib to manage plugins with flask? I create my plugin, I add the folder in the plugin folder and it is taken by the application.
Do anyone know how to create groups of objects in django. Should I use foreignkey?
How can I get the ip of the computer who send a request (just for info it's a post request) ?
i think it should be in the header of the request
if you're using a web framework there should be some kind of request object that has the header info
I'm trying to share data between two python scripts in django, and I'm not sure how proceed
2 separate sites or just 2 different functions?
sparate 2 scripts
again, scripts or sites?
it's a difference
Between 2 scripts on the same site you can just call the function and pass a parameter
yeah I've done that, but then I need to send a response back
I'm getting some data from django channels, I need to send a part of this data to a signal script, because I want to see if a specific row in the db has been update, the db is getting it's data from DRF. If the singnal sees that the pass datas corresponding row has been updated it has to send a response back with telling the channel recieve script, "data has been update", its okay to go to the db
this should happen in a cyclical manner till the client send another row's id to track.
@tired root
send the function the id of the db row to check, do your magic and use return values to determine the further path of the flow
tk_id = None
def get_data_from_channels(data):
global tk_id
tk_id = data
@receiver(post_save, sender=TrackerLocation)
def save_tracker_location(sender, instance, created, **kwargs):
if created == False:
if tk_id == instance.tracker_id:
print(instance)
print(instance.tracker_time)
else:
print("new data")
this is something that I'm trying to work with, the problem is that I'm not sure how/if this is even a good way to do something like this
Is there any reason why when I've pushed my flaskapp to a Linux server and nginx, the app loads fine, the web pages load, but my JavaScript isn't working? I've tried pointing the refs to the .js files in static the same way as it was on windows: src="{{ url_for('static', filename='chessboard-1.0.0.js') }}"
but exact same set up on the linux machine doesn't seem to play ball?
It's the exact same file structure
what does "not working" mean? it's 404-ing when requesting the assets? the mimetime isn't correct? it's serving the wrong file?
Does the server have the rights to read the file?
also Linux is case-sensitive, something many forget
open up the devtools in your browser to ensure that the file is being requested and let us know what the response is
case isn't issue. How would I check rights? It's rading everyything else
Failed to load resource: 403
403 is forbidden, so the rights are not as they are supposed to be
can anyone suggest me some course for django learning
Same
Has a django book for 1 $
okay
ok I'll check rights
thanks
Any book or course for starting Django?
check online if it is good enough for your skill level
i have buyed a course on udemy but he only work on project
that's the best way to learn
by doing projects
I used udacity a while back, looks like they still have lots of free courses https://www.udacity.com/courses/all
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
