#web-development
2 messages Β· Page 131 of 1
Hello, is there anybody who can help me with basic setup flask + rabbitmq + dramatiq + redis?
hi
i need to update the custome file label when image is upload
this is my code
<form method="POST" action="" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.picture.label(class="custom-file-label", for="picture") }}
{{ form.picture(class="file custom-file-input") }}
{% if form.picture.errors %}
{% for error in form.picture.errors %}
<span class="text-danger">{{ error }}</span></br>
{% endfor %}
{% endif %}
</div>
<script type="text/javascript">
$('#picture').on('change',function(){
var fileName = $(this).val();
$(this).next('.custom-file-label').html(fileName);
})
</script>
when i upload image it is not changing the label
but on console it display the image name
Anyone able to help me on this matter? Online docs are very welcome !
someone help
pc = price
Hello, is there anybody who can help me with basic setup flask + rabbitmq + dramatiq + redis?
Look at the django docs about templates / context to see how you can pass things from your view to your template.
def clientProfil(request,pk):
...
client_buy_list = client.buying_list.all() # this is a queryset (list)
context = {"buy_list": client_buy_list}
return render_template('.html', context)
Then in your template:
{% for item in buy_list %}
{{item.pc}}
{% endfor %}
Wow thanks ! it was more simple than I thought ! will check django docs more accurately next time
you could probably change your picture's filename in your backend view.
alternatively, you could submit the picture as a JS File object and specify a name:
https://developer.mozilla.org/en-US/docs/Web/API/File/File
The File() constructor creates a new File
object instance.
@native tide will you please show some code
what specifically
means where to change
i previosuly use only js to cahnge
and it work
but now its not working
Hey can anyone help me out with Django application deployment ? (Any article book suggestion would be nice)
hey guys i have a Q can i replace javascript to python
hey i am thinking of creating a freelancing site like upwork
can anyone suggest me some resources etc
i have 0 experience programming back end. is python a good language for back end?
not for frontend
Yes, it has some very nice frameworks to work with
do you have one to recommend? :)
recommend starting with either Django or Flask,
Flask is a micro framework so its alot more bare bones so no DB orm etc... but has a massive ecosystem to expand it
Django is a full framework so you get your templating, database ORM, middle wear, admin panel etc...
both frameworks are very nice to work with though imo i prefer using Django's rendering engine to flask's Jinja
FastAPI is another good framework if you're planning to make a api backend
performance, asynchronous, auto generates docs, all sorts very nice framework aswell
i guess ill start off with flask. i have a old pc is it possible i can turn that into a server if i installed linux?
@quick cargo ok
Yes
You have which os now?
it has windows on it
How much ram?
i think i have 8gb
can i?
it has 160gb and a 1tb additional drive
See before installing watch YouTube videos
Ohhh
Watch YouTube videos
You have better specs than me
ok thanks. i need to get the computer from my friend. he was putting it together for me.
I have 8gb ram and 1tb storage
my main pc has 500gb
and a 2tb hard drive that i dont really use lol. it cant run games
its my birthday in febuary and then ill have enough money to buy a better monitor >:)
ye ill watch some videos
What work u fo?
You said u will have money
ye ive been saving up
christmas and birthday are gold mines >:)
Good
hello
Hii
i installed batman arkham knight. finna replay that for the second time
on a good monitor
Bro have u played assassins creed
Can I use django and react together?.
Yes I guess
Pls try searching on google
I searched they said that I need to use some framework called django rest which I don't know 
Wait I will check and let u know
Now running out of charge so will let u know later
Will that be ok?
Thanks 
Thats ok π ping me when you reply, thanks again
you dont need django rest framework
it just makes constructing a rest api easier
but you certainly dont need it
is there a big difference between django and django rest framework?.
CAN ANYONE HELP ME?
I created employee model table there are four user and there data but it is not showing in postgresSQL after making migration in under employee table in Django...please help me ππππ
There is a fairly big difference. I would highly recommend using DRF as having serializers handle validation of data sent is seriously a game change. On top of that using it for nested relationships (many-to-many) is extremely easy and quick to get up and running. Plus the ability to extend the generic classes is so valuable.
Ok Thanks, But the same logic applies right.
Eg: Models, views, templates, etc..
Hello Im new to django and webdev in general. I'm building a small app and i have this CharField in a form. and i cant seem to find how to get the text or value of that field unless i post i would there be anyway to do this without posting in django
Does anyone know if there is a Django specific Discord ?
word
Yes. You most likely wouldn't be using templates with DRF. You would create a serializer.py file inside the app as required. The views are in the same place but created differently.
Javascript. Add an event listener and send to a route.
Well django is serverside, so it has no form access until you post/send it
rip
Ok, Thanks a lot 
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
thanks
Assign an ID to the text input and fetch it that way.
document.getElementById("idOfInput")
the thing is i dont know any javascript i have been getting away with doing everything in python i mostly used dash for figures and slider
but its a small this shouldn't be too much
Well, don't be afraid to try doing a little javascript. I sent you basically everything you would require.
awesome
then lastly i dont wanna get ahead of myself but where would i put the js in my django app just in the .html if its gonna be a small function or something?
You can do that or create a JS file and render it in the template. It would be close to the same as an image.
with load static, etc
In Django, I have Many-To-Many relationship, say, Artist to Talent through ArtistTalent with ArtistTalent having an order field. Is there a way to use that field and prefetch_related together ? Meta.ordering seems to be ignored when using prefetch.
That's the best way
But you can always just open a <script></script> in the html file itself and write the functions
Why wouldn't you just use prefetch_related on artist and add talent to it? You don't need to handle functionality with the table for relationships.
Artist.objects.all().prefetch_related('talent')
that is what I do but is not ordred
filter().order_by()
I don't know to be more precise, i don't know how to order it according to ArtistTalent.order field
What type of field are you trying to order on? Primary key? Date?
simple integer field
neither order_by('artisttalent__order'), nor Meta.ordering on ArtistTalent seem to have any effect
Are you filtering on the artist table or the talent?
Or are you doing this on the relationship table (not sure why you would).
Artist.objects.all().order_by('artist_id').prefetch_related('talent')
Artist.objects.all().order_by('id').prefetch_related('talent')
Artist.objects.all().order_by('talent__id').prefetch_related('talent')
Or it might need to be a negative for the order_by
Replace ID with the column name
I'm refering to the through table, so neither artist nor talent
Artist - ArtistTalent - Talent, the through table ArtistTalent has the order field I'd like to use to order the prefetched talents
I haven't ever had to do it that way. I'll toss some ideas out there but it could be completely incorrect.
Yeah, never had to do that before either π
Create a list of the ordered ID from that table. And then grab the Artists.filter(id__in=LIST_NAME)
Which I think should in theory make it ordered and bulk fetch everything.
I see that you can use a Prefetch object defining a QS
@jade lark thanks anyway to give it a try. I try to do it another way.
Of course! Least I can do. If you figure it out please do let me know and how as well!
hey, using flask here, trying to update the page without a reload, from 5 mins of research, browser side js is the bast option for this, anyone have any other suggestions?
Found a way with Prefecth class :
artists = Artist.objects
.prefetch_related(
Prefetch(
'talents', queryset=Talent.objects.filter(artisttalent__artist__slug=slug).order_by('artisttalent__order'),
)
).filter(slug=slug)
Glad to see you got it!
@spring sequoia You can set a timer and make a request to a flask endpoint through javascript
The best way to do this is through web sockets though
thank you : )
how to view the encoding of a return from an api?
I'm not sure if this goes here or in a different channel-
@barren moth it's often returned as an HTTP header
I think its usually called Accept-Encoding @barren moth
From the API response, the encoding will be in Content-Type. You request it with Accept-Encoding
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
When sent from the client:
Accept-Encoding tells the server what compression the client supports
Accept-Charset tells the server what text encoding the clients supports
Content-Encoding tells the server what compression the request body is using
Content-Type tells the server the media type of the request body, which optionally specifies a charset aka a text encoding
HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value.
How can I show my comment view and comment form in the on my app (it's working fine in the backend, the data saving part)?
It's a blog and the post details are being shown from PostDetail class in views.py. My PostDetailView Looks like this:
class PostDetailView(DetailView):
model = Post
Now I want the comments and the comment form to be shown here (in post detail view). The post detail view on the frontend it's just fetching the data from db using object.content
How do I implement my comment function in post detail ??
My comment func:
@login_required
def comment(self, request, pk):
template_name = 'post-detail'
author = self.request.user
post = get_object_or_404(Post, pk=pk)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.author = author
new_comment.save()
messages.success(
request, f'Comment Posted!')
return redirect('post-detail', pk=post.pk)
else:
comment_form = CommentForm()
messages.warning(request, f' Invalid comment!')
return render(request, template_name, {'post': post,
'author': author,
'new_comment': new_comment,
'comment_form': comment_form})
can anyone tell me how i do 127.0.0.1/page/history in Flask, Url routing. I can do one routing but how i do two routing
Hey
So I'm making a sort of chat application, and when I add or delete a message, my message box moves up and down
Any way to fixate this?
position: fixed;
``` This won't work
So I'm making a sort of chat application, and when I add or delete a message, my message box moves up and down
@glossy arrow if you use that you need to specify an anchor
like bottom: 0
you can also use flexbox
Oh ok, thanks :D
Hello, I am using Django to make an inventory system. There are two major jobs that I had to do... Add an item and delete it. The adding page of my project has 2 fields one to select an existing thing and add to its quantity and one to enter the name of an entirely new thing and add it's quantity... Can I have the selection of thing and entering it on the same page such that user only either selects or enters the name?
So essentially using the same form field in forms.py for two different textboxes...
Thanks
im trying to make flex boxes have a minimum/maximum width and height. however when i do, it messes with the justification/alignment
{% extends "complaints/base.html" %}
{% load static %}
{% block content %}
<div class="d-flex flex-column align-items-center rounded">
{% for post in posts %}
<div class="p-2 text-white bg-darkest rounded mr-3 mb-3 py-3 rounded">
<h2 class="text-white">{{ post }}</h2>
</div>
{% endfor %}
</div>
{% endblock content%}
this works fine, but the 'bubbles' made arent the size i want. so i specify my css class:
.complaint-bubble{
min-width: 500px;
max-width: 500px;
min-height:200px;
max-height:200px;
}
and it does this. i want the numbers in the exact center. how can i do this and have the minimum bubble size regardless?
I'm planning to learn some backend in flask /django. Ive heard django is better but is it too difficult to start off with?
where does the text come from
{{post}}?
@vestal hound django
its currently placeholder stuff just for testing. just passing it a list
also i am now using flex and using flex-basis also messes with centering
<div class="d-flex flex-column flex-wrap align-items-center rounded">
{% for post in posts %}
<div class="p-2 text-white bg-darkest rounded mr-3 mb-3 py-3 rounded complaint-bubble">
<h2 class="text-white py-5 py-5 px-5">{{ post }}</h2>
</div>
{% endfor %}
</div>
.complaint-bubble{
flex-basis: 100px;
}
you have way too many classes but
in general
finally got it, i just need them to be wider and to actually fill a line before moving onto the next
justify-content and align-items work on the actual width of the flex item
but you fixed that
so I suppose now you want each flex item to be the width of the flex container
no
i essentially want these to be like playing cards, but each with text taken from a database on them
let me make a mockup
@vestal hound like this
text in the center, but each "card" has a fixed width
so do you want them to be wider or not
width of the container, as in where i specify the flex-column class?
no, you just said you don't want the items to scale with the container
so set the width on the items
oh, i meant that the cards shouldnt scale. basically nothing should scale at all. everything should be fixed
then this
something is wrong about your HTML then
assuming each card is an item
my gut feel is
i posted the html i had lol
whats there is what it is, thats why its so annoying. i have no idea whats wrong either
if theres a better way to approach this i could, i just thought using flexbox would be the best way to do this
it is but
you have lots of classes so I'm not sure what the actual CSS on your elements is
all bootstrap, the only custom class is .complaint-bubble
which is what i posted
.complaint-bubble{
flex-basis: 200px;
width: 500px;
}
<div style="display: flex; flex-direction: column; width: 20rem;">
<div style="display: flex; width: 100%; justify-content: center; align-items: center">
text 1
</div>
<div style="display: flex; width: 100%; justify-content: center; align-items: center">
text 2
</div>
</div>
to clarify, i just want my website to be like this. each 'post' has its own card, the card is a fixed width, and it fills the page. when a row is filled entirely, it will move onto the next row.
i basically want it to take up as much space as it can
let me try that
....
that should be essentially what bootstrap was doing
this is inconsistent
you cannot have "fixed width" and "fills page" simultaneously
for variable viewport width
i just want all of them to be the same size so it doesnt look weird. if theres a way to make them all scale to be the same size to fit the viewport, that would be good
flexbox is the answer π
yes, sorry for the misunderstanding. all the rectangles need to be the same size
i.e. each card is the same size as each other card, but what that size is can vary
vary as in to fit the viewport, thats it. the contents of them should not scale them up or down
ye
you want flex-wrap
for the wrapping behaviour
and I think
you want to flex in the row direction
not the column direction
because as you have it it's gonna go like this:
1 5
2 6
3 7
4 8
yeah, that seemed like it did the trick. just need to fix the god awful centering, idk why its so picky
and id like them to be bigger to fill the page
even if the contents dont matter
it's because
your widths are wrong
in particular
you have a h2 in a div
I don't know what those bootstrap classes do
but
the div is being centred
theyre basically just shortcuts for going into css and editing/making new classes
as in
I don't know what specific CSS rules they apply
anyway
my guess is that the h2 has some sort of right margin
which causes the element, but not the text, to be centred
you can
inspect it in your browser
<div class="d-flex flex-row flex-wrap align-items-center">
d-flex : display-flex
the rest are exactly what they say they are
π₯΄
<div class="p-2 text-white bg-darkest rounded mr-3 mb-3 py-3 rounded complaint-bubble">
<h2 class="text-white py-5 py-5 px-5">{{ post }}</h2>
</div>
I meant these
<div class="p-2 text-white bg-darkest rounded mr-3 mb-3 py-3 rounded complaint-bubble">
p-2 - padding 2
bg-darkest - simply a dark background (custom)
rounded - rounded borders
mr - margin right
py - padding y axis (top and bottom)
complaint-bubble - my custom classes
let me see
see this
inspect it in your browser
you should be able to tell what is being centred
i had those on the h2 to scale up the bubbles lol
i took them off, and the bubbles are smaller- but the centering is still off
or if
the width
of the inner elements
isn't high enough
which I doubt
but anyway
just inspect the actual CSS and bounding boxes
let me make this more than numbers for the test data first
theyre not consistent rip
not sure if this is helpful, but it is actually centered it looks like- but the text isnt actually... centered
@vestal hound can you help me? How do I get a Strong in a Td?
also, the boxes can definitely use more space on the sides to avoid the extra row, but they dont
your h2 takes the width of the container
...that should be fine by default
and there is no need to ping specific people to help you
you need flex-basis and flex-grow (and flex-shrink, or just flex)
...okay do you know how flexbox works?
I feel like
you're just throwing random stuff and seeing what kind of works?
to be blunt
a little, its kind of been a modgepudge of stuff from stackoverflow lol
i have been reading both bootstrap and mozilla documentation too
Oh, sorry. It's because I took the Td but the problem is when I print it. The output shows the strong and span...
get a proper foundational understanding of flexbox
can you elaborate I don't really understand
because it actually makes a lot of sense and it's quite easy to do stuff
but your principles need to be in order
I have this TD, but when I print it the results is:
So I just want the strong or the span one
show your raw template/HTML
this?
The code is:
option = Options()
option.headless = False
driver = webdriver.Chrome(options=option)
driver.get(weblink)
time.sleep(5)
driver.find_element_by_xpath("//div[@class='classificacao__pontos-corridos']//table[@class='tabela__equipes tabela__equipes--com-borda']//tbody//tr[@class='classificacao__tabela--linha']//td[@class='classificacao__equipes classificacao__equipes--time']").click
element = driver.find_element_by_xpath("//div[@class='classificacao__pontos-corridos']//table[@class='tabela__equipes tabela__equipes--com-borda']")
content = element.get_attribute('outerHTML')
soup = BeautifulSoup(content, 'html.parser')
table = soup.find(name='table')
table_rows = table.find_all('tr')
res = []
for tr in table_rows:
td = tr.find_all('td')
row = [tr.text.strip() for tr in td if tr.text.strip()]
if row:
res.append(row)
df = pd.DataFrame(res, columns=["Lugar", "Time", "Sla"])
print(df.Time)
I need my users to be logged in across both subdomains, however I can't get it working.
app = Flask(__name__, subdomain_matching=True)
app.secret_key = 'dsfsdfdfgsfsdsdgfdsf'
app.config['SERVER_NAME'] = "local.test:5000"
app.config['REMEMBER_COOKIE_DOMAIN'] = '.local.test:5000'
app.config['REMEMBER_COOKIE_SECURE'] = None
Does anyone know what i've gotten wrong?
i just started learning flask but the info title when i put it in it says URL not found, anyone know why
looks fine, you are going to 127.0.0.1:5000/information right?
in the console does it say it tried to go to /information
i dont know i just copied and pasted it again and it worked lol
In django orm, if I update a record (.save), will the UPDATE statement affect all the fields or only the fields that have changed?
Update parameters only affected
meaning if I write:
def update_thing(pk, foo):
thing = Thing.objects.get(pk=pk)
thing.foo = foo
thing.save()
does it update the bar column in the database also?
or does it track which fields have changed
Foo will be updated not bar
so it tracks dirty fields?
No it will not
so then the update statement affects every column
No if you want to update the field then Thing.objects.filter(pk=pk).update(foo=foo)
I think you are misunderstanding my question
It doesn't keep track of the updated field
will:
def update_thing(pk, foo):
thing = Thing.objects.get(pk=pk)
thing.foo = foo
thing.save()
generate
UPDATE things
SET foo = foo
or generate:
UPDATE things
SET foo = foo, bar = bar
even though bar was not changed
ok, thanks
because other orms track dirty fields
If want to the change the fields based on the update condition then you have to go for django signal
anyone know how to bar graph a .csv on a website?
Hello Hello Rockstars, Quick Question, what is a good way of serving generated files in a webpage?
i am processing input files and after a while i populate a table with resutls but i want to provide link to 2 files, what would you recommend?
I have read about static files but it doesnt seem to fit the bill, these are dynamically generated files
Hello! How can we get the number of data there is in a table ?
i.e. I'm looking for how many comments are there in comments table when filter by post id? (in django)
nvm got it, it's Comments.object.filter(post='40').count()
Hey what could possible be wrong when a flask endpoint sometimes work & sometimes doesnt
one of the reason is end slash missing or it got redirected
looking for someone to code a bot from scratch for me, because i'm looking for someone to code me a simple bot. willing to pay. DMS ARE OPEN
Hey, line 16 i keep getting a "werkzeug.exceptions.BadRequestKeyErrorwerkzeug.exceptions.BadRequestKeyError" and i have no idea how to fix it, anyone have any idea?
Hey everyone, have a question, in Django I am trying to write a test script in my back end to populate the test database with data using a model.save(). But every time I run it my test db is blank even though I do not get any errors. Has anyone ever encounter this before?
@random kernel try request.form.get('Name')
got a syntax error π¦
got this
i feel this is wrong what i did
like db.String(255)
you have to pass thourgh keyword
like
Participants(name='Neil')
im kinda new to programming lol, its for an assignment
Participants(name=request.form.get('name')
like this?
you have it named as 'Name' not 'name'
ughhhh, i was on this single error from midnight to 3am this morening...
change it to lowercase in your model
inside your Partiipants Model you have it named as "Name"
when you're calling the class, you have it named as "name"
so inside the db.model change Name to name
uhhh, im sorry im kinda confused π¦
got this :/
class Participants(db.Model):
Name # < this is a captital N
GroupPeople = Participants(name=whatever) # < name is lower case N
paste your full 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.
from flask import Flask, render_template, session, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(name)
app.secret_key = "dog"
db = SQLAlchemy(app)
class Participants(db.Model):
Name = db.Column(db.String)
ID = db.Column(db.Integer, primary_key=True)
Events = db.Column(db.String)
Group = db.Column(db.String)
@app.route('/', methods=['POST', 'GET'])
def home():
GroupPeople = Participants(request.form.get('Name'))
db.session.add(GroupPeople)
db.session.commit()
return render_template('home.html')
@app.route('/admin', methods=['POST', 'GET'])
def admin():
return render_template('admin.html')
if name == "main":
app.run(host="192.168.0.61", port="5000",debug=True)
class Participants(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
events = db.Column(db.String(255), nullable=True)
group = db.Column(db.String(255), nullable=True)
@app.route('/', methods=['POST', 'GET'])
def home():
GroupPeople = Participants(name=request.form.get('name'))
db.session.add(GroupPeople)
db.session.commit()
add nullable=True like I have above
Nullable=True means you can insert into the database, without having to insert in to the events and group column
check the table has been created, may have to do db.create_all()
how do i check this?
are you doing it on local host ?
not to sure how to check with sqllite, I use mysql
after db = SQLAlchemy
type
db.create_all()
and restart app and then try
where you setting the database path ?
this what you mean?
no
you need to set a path to the database
like:
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:@localhost/databasename'
wheres this going? under db.create?
ive gone through sooooo many, any suggestions?
from flask import Flask, render_template, session, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(name)
app.secret_key = "dog"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.participants'
db = SQLAlchemy(app)
db.create_all()
class Participants(db.Model):
ID = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.String(255))
Events = db.Column(db.String(255), nullable=True)
Group = db.Column(db.String(255), nullable=True)
@app.route('/<Name>/<Group>')
def home():
GroupPeople = Participants(name=name, group = group)
db.session.add(GroupPeople)
db.session.commit()
return render_template('home.html')
@app.route('/admin', methods=['POST', 'GET'])
def admin():
return render_template('admin.html')
if name == "main":
app.run(host="192.168.0.61", port="5000",debug=True)
i now have all this
but
this too
I have a Django website project where users need to receive daily email updates, for around 2000 users. The emails are scheduled with a python cron job. We ran this project last year using a regular google email account, and then switched to Gsuite to get more email allowance, but Gsuite still thought we were spamming and didn't deliver many of our emails. In the end we had to write code to send them in small batches with time intervals in between. This was a real pain. Is there a better service/bulk email provider or methodology we could be using for this purpose?
@snow olive you can probably look at Mailgun, Sendgrid and friends for this. You should probably make sure users can opt out of your mailers too, so please consider using a template with an opt-out link π
So in django 3.1 async is supported with uwsgi? do I need gunicorn for this?
hi guys, does anyone here knows how to change a user's email in Django?
I am using django's default User model
and function based views
user = User.objects.get(pk=request.user.pk)
user.first_name = first_name
user.last_name = last_name
user.email = email
user.username = email
user.save()
The above snippet is what I tried bu it's not working.
Is it true that OOP is forced opon JavaScript?
anyone can help me in some python queries
like i need some help regarding backend development
Does anybody know if nginx blocks headers by default? My flask server (deployed through nginx and wsgi) is not getting a header in its request.headers that it did get while in dev
Isnt that Java ?
JavaScript worked just like Python for me
How I can remove that numbers in the output when I print a df.astype(str)?
df.reset_index(drop=True, inplace=True) this work?
Hi, I just deployed a flask server through nginx and uwsgi on ubuntu. I am having an issue with headers, basically they are not being passed through nginx to uwsgi.
I have tried setting them through uwsgi_param and basically everything but I just can't get it.
When doing the following uwsgi_param IOS_KEY 'test'; and printing request.environ it works, but when I do uwsgi_param IOS_KEY $ios_key; it does not work.
server {
server_name pyropreme.com www.pyropreme.com;
location / {
include uwsgi_params;
uwsgi_pass unix:/root/server/server.sock;
uwsgi_param URL https://pyropreme.com;
uwsgi_param STRIPE_PUBLIC_KEY ..;
uwsgi_param STRIPE_PRIVATE_KEY ..;
uwsgi_param DISCORD_CLIENT_ID ..;
uwsgi_param DISCORD_CLIENT_SECRET ..;
uwsgi_param BOT_TOKEN ..;
uwsgi_param GUILD_ID ..;
uwsgi_param IOS_KEY test; <= This should be the header
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/pyropreme.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/pyropreme.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.pyropreme.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = pyropreme.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name pyropreme.com www.pyropreme.com;
return 404; # managed by Certbot
Thanks for any help in advance
Where I can put that?
after df.astype(str)?
escrita = df.reset_index(drop=True, inplace=True).astype(str)
maybe this? I haven't tested it
error...
why is 'escrita' an empty dictionary and then you assign a string value to it?
Because I need to put it as a string to my bot awnser whit this info
py df.to_string(index=False)
Oh, that worked. Thanks :)
π
Just one question, is it possible to remove that space?
what column is that?
Time column
are you sure it's Time? It looks like "Club name" or something
ok
Yes it's Club name, but in portuguese Time = Teams
...
Oh that's nice
maybe you can try adding ```py
skipinitialspace=True
in the parameter where you're declaring the df variable
It's more common the person that you helped say "Obrigado" = thanks, and you say "De nada" = you are welcome
De Nada π
Where I can add that?
Because it still have the space
add it in the parameters whee you declared the dataframe as labelled here
But it isn't just for pd.read_csv?
I didn't check if it is a valid parameter for Dataframe initialisation but yeah in the xample they use it for read_csv
I found a python lib called Tabulate, could work
but there is this problem
I'm pretty sure you can do it using pandas though
otherwise this?
I put that after df = pd.DataFrame(res2, columns=['TIme'])?
yeah after
Like this
another possible alternative```py
df['Time'].replace(' ', '_', regex=True)
Nop :/, still have the space
I think the tabulate lib worked
Yep
It worked
But thanks for helped me :)
I'm not sure if this would be the right channel, but how can I communicate between a webserver and a normal python script?
Ping me please
I need to do it without threading a webserver with the script
@somber pasture sockets
Does anyone use SendGrid to send emails from Django? If so do you use the web API or SMTP?
OK
@rustic pebble do the client and server need to be on the same network?
Not necessary but it would be the fastest if they were @somber pasture
So basically socket clients run as a normal python script, but can take requests?
yes
Thank you very much, that's exactly what I needed then
There is a socket client and a socket server
:)
Just make the webserver a socket server, the module you are using should have native support
OK
then just add corresponding socket support on the normal python script
How I can use the 3 TD, but in the second one don't use the SPAN, use only the Strong
Like, the problem is that I have in the second Td the strong and stan
I already removed the stan, so my result is the strong when I print or return
but I want to all the TD
but I can't because If I print, it will show the strong and stan value together
@rustic pebble I want this:
But
where is the names: Internacional.... I don't want the last 3 letters
and when I use the "filter" for the stan I can only use the second Td:
So I want something like:
Pos Time Var
1 Internacional 0
You need to give me more context, how are you generating the tables, what framework are you using?
It's a web scrap, so I'm using pandas
to take the results and generate the table
I can't help you if it breaks this server's TOS
This is the code
But it's just a test bot to take an info and send me
Hello! anyone got an idea for doing Vanilla JS Tables that get formed dynamically after hitting an API?
my app is small and I am pretty sure I dont need React or similar
but I now need custom cells and rendering them by hand its very cumbersome
You can make your API call save the necessary data as an array and then .map() it into table rows, is that what you're looking for?
Just use Ajax to make the call and then in on success re render your table
still cant get this to work. the flex container is supposed to take up 100% of screen width, and each bubble is supposed to be the same size regardless of its contents
<div class="d-flex flex-col flex-lg-wrap align-items-center complaint-container">
{% for post in posts %}
<div class="text-white bg-darkest mr-3 mb-3 py-3 p-2 rounded complaint-bubble align-self-center">
<h2 class="text-white text-center">{{ post }}</h2>
</div>
{% endfor %}
</div>
need code for aesthetically pleasing and fully responsive website navbar
use bootstrap navbar/nav classes
i am not allowed to use bootstrap
well, your starting point is to make it position: fixed;
that im not sure of, thats why i use bootstrap
Hi, is there a way of limiting post requests to once a day using Quart (asynchronous Flask)
"aesthetically pleasing" is subjective
so is "fully responsive", for that matter
what do you want to have specifically
a professionally looking navbar with desktop to mobile responsiveness and some with link hover effects.
...
what is "professional"?
also
"responsive" suggests that it will change in some way with screen size
that is understood
but
colour pallete, background colours and family font
this is mega basic and can be done in a few lines of CSS
what kind of effects?
highlight?
ripple?
popout menu?
there are many options
i will give u an example
I suggest you design it first then think about how to implement it
looks p basic
yethe hover effects
you can just inspect the HTML/CSS and imitate it
i dont know wut hover effects will suit a good navbar
this is a question of design
anyway, just go experiment
and use your own judgment.
will try, thanks tho
Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin, QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript, Scheme, APL, Lua, Python 2.7, Ruby, Roy, Python, Node.js, Deno (beta), Go, C++, C, C#, F#, ...
my website isnt displaying properly
the whole css doesnt seem to work
anyone know the solution around it?
...did you include the stylesheet
huh
in that code?
where
I mean, you need to include the stylesheet in the HTML
k
anyone know why this isnt working?
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
ip = self.get_client_ip(request)
serializer.is_valid(raise_exception=True)
profile = serializer.save(ipaddress=ip)
return Response([ProfileSerializer(profile, context=self.get_serializer()).data])
@staticmethod
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
thanks
thanks
i broke my aws instance lmao
anyone know how to setup django to run in apache?
i dont understand anything thats going on at all
can someone help me with something? (flask related)
I am having problems is calling Django api from react ui, it's working fine in postman. Can someone help please, stuck for two days.
Hey can anyone help me with my CSS code?
not a css guy but I'll have a look
ok thanks
π
This is supposed to create a blue box around Ruby and Scratch but the blue box does not appear
let me try it on my pc
ok thanks
copy paste code please
sure
<!DOCTYPE html>
<html>
<head>
<title>CSS</title>
<style>
.names {
font-size: 16pt;
text-align: centre;
background-colour: blue;
}
</style>
<head>
<body>
<div class="names">
<p>Ruby</p>
<p>Scratch</p>
</div>
</body>
</html>
@unique bluff it's background-color not background-colour
no, colour is the british version of color
in coding color is used
i just tried background-colour and it didn't work
thanks
i am reading a american book so spellings are gonna be different
fixed
heres the code
<!DOCTYPE html>
<html>
<head>
<style>
.names {
background-color: blue;
text-align: center;
font-size:16pt;
}
</style>
</head>
<body>
<div class="names">
<p>Ruby</p>
<p>Scratch</p>
</div>
</body>
</html>
its all good now cheers though
background-colour to background-color is what he changed
ohh haha, i hate small mistakes like that
I usually just re-write the code
Depending on the situation, I generally use background:blue; but yea, colour was updated to color
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
ip = self.get_client_ip(request)
serializer.is_valid(raise_exception=True)
profile = serializer.save(ipaddress=ip)
return Response([ProfileSerializer(profile, context=self.get_serializer()).data])
@staticmethod
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
can i get an hontjie
?error52/(32432)
Hi, I want to implement authentication with username and password, for this I found OAuth2 Grant type Password that solves the problem. But itβs recommended that not to use grant type password for Mobile devices which is a public client as per RFC documentations.
What are the other or best approach to implement OAuth ?
when ever i click on login,
don't know why it adds an extra '/' in url
'' = 127.0.0.1:8000
when i click student login it becomes 127.0.0.1:8000/s_login/
error:
s_login/ not found in url```
Hi I am working on flask + react app deployment but I am facing issue where when i just enter url results are being shown in html file but when i refresh the page it shows api data anyone who can tell me what i am missing
result before reloading
I have solved this issue for other urls before but its not working now
@hasty olive can you show us your react component code
guys, how should I render this message box when I click home in react router?
Hi everyone, I'm trying to build todo app, where each task will have comment section, and wanna do this comment section with web sockets, but I'm kinda having difficulties with understanding how to connect js and backend as i don't know js. I have tried youtube and django channels tutorial, but still feeling like, not enough info. Any good source that you used while learning web sockets? Thanx beforehand
anyone?
save the selected sidebar menu within state, then render components based on that state
@elfin bluff look in settings.py. APPEND_SLASH determines whether the URLs must have appending slashes, and therefore you must change your urls to reflect that.
Simple google search would find your answer π
You can check the issue in summary page of it
works for me
This component is showing issue
Couldn't send you the code because of slow internet so I have to send through mobile pix
Refresh the summary page
yep, works for me
You are not getting the api result?
yes
first time it works fine but when i go to the summary page and refresh the summary page it shows summary api result
not index.html file result
flask
oh, well the issue lies between your url .../summary and .../summary/
with the appending slash there is no issue
so you probably have a route in your flask app for .../summary which returns the api data.
yes
yep, so there's your answer
sure what's the problem
can you explained it little bit
other routes are working fine which are like same like summary why issue is occuring in summary only
your flask app has a route for .../summary which returns your api data, correct?
well when you visit that URL your server is going to be returning your api data.
I suppose you have client-side-routing with your react app and you render your "Summary" component based on a url like: .../summary also. However your component will also show when you visit the url .../summary/ (notice appending slash).
So tldr; visiting .../summary hits your API endpoint, visiting .../summary/ renders your component (even if your client-side url and your server-side url are the same).
Can anyone tell me how can i use django channels with rest framework
I cannot find any resources?
Thanks bro for explanation and helping me with issue .
I am very thankful to you.
np, i like your site
Trying to fetch an api...
@haughty turtle You are wrong, JavaScript is not an OOP language. It's prototype based language.
If I am wrong , please correct meπ
Hi everyone! So like I am new to django and css and scratching my head how to get this carousel to work. I downloaded a css template and the carousel is working fine there but when I try to run the server it isn't working and idk why. Please help.
does anyone know of any COVID vaccine availability APIs or websites one could use for a source of truth? like if i want to receive an email when one is available in my area, is there something I could automate?
nah ive read that, but they dont explain the paths or where to actually put the files. i assume the virtual environment is put inside the the /var/www/html, but theres no real explination behind any of it, just path/to/site, path/to/venv ect.
In the example code on: https://docs.djangoproject.com/en/3.1/topics/auth/customizing/#a-full-example
The password for a user is set in two different ways, is there any particular reason for this?
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
)
user.is_admin = True
user.save(using=self._db)
return user```
what do you mean? you should always use set_password() because it hashes your passwords
in the create_superuser function it uses python user = self.create_user( email, password=password, date_of_birth=date_of_birth, )
from what you have said the documentation just seems wrong
just an example more then anything. example code isnt written to be used in production. just to see how you can do it
ive never used pure django. i use django/rest api. but its the same concept
I am using the djano/rest api as well
trying to figure out the best way of doing authentication
serializer
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(validated_data['username'], validated_data['email'],
validated_data['password'])
return user
api
class RegisterApi(generics.GenericAPIView):
serializer_class = RegisterSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
return Response({
"user": UserSerializer(user, context=self.get_serializer()).data,
"token": AuthToken.objects.create(user)[1]
})
im using django knox tokens as well
the validated_data also hashes the password
http://yonekey.lovestoblog.com/
Look at the designπ€€
is that your page?
why does this end point returns 404 not fount?
rhb = Blueprint("/api/v1/rhb", __name__)
@rhb.route('/initial_sync', methods=["POST"])
def initial_sync():
data = request.get_json()
print("Data: ", data)
username = data['username']
password = data['password']
try:
sync = initial_sync_rhb(username, password)
response = {
"accounts": sync,
"success": True,
"msg": "Account successfully synced"}
return jsonify(response)
except Exception as e:
response = {"success": False, "error": e}
return jsonify(response), 500
from flask import Flask
from flask_cors import CORS
# Import blueprints
from rhb.blueprint import rhb
import os
app = Flask(__name__)
CORS(app)
# Register blueprints
app.register_blueprint(rhb)
@app.route('/')
def index():
return "WALAWONG API IS RUNNING"
if __name__ == "__main__":
# import argparse
app.secret_key = os.urandom(24)
# app.run(host='0.0.0.0', debug=False, port=os.environ.get('PORT', 5000))
app.run(debug=True)
Is their any resource from where I can learn Django
django has a guide on their page for simple django. but ive never found a formal resource. its way to big for just one resource
Great, I wanted to know if there was a good tutorial to understand the basics of it.
Currently, I am following Corey Schafers playlist on YT , not sure if it's the best for a beginner
which playlist?
i restarted my apache webserver but its not showing the updated page content on my website
did you clear your cache?
on chrome?
yea sometimes the server responds with no change and the browser uses the cached copy
@visual wolf im sure thats fine. you should know that django can be used as a front end, but normally isnt. its the biggest problem with web dev. the meshing of frameworks. and no good resources explaining truelly whats going on
hey can someone help me out with flask blueprint
what file are you accessing? is it local network or over the web?
help-boron
Oh, okays
Hello everyone, I am building a Django web app and currently trying to automate populating my database with data pulled from another API. I did some research & built a test.py script to do so by saving directly to my model in the backend. The issue is when I run my test I don't receive any errors and my test database table is empty. I just need help figuring out what I am doing wrong. I feel like it is something obvious I am missing. Any help is appreciated.
from django.db import models
# local database save of the episodes pulled from Podbean and manual inputs
class episode(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
logo = models.ImageField('uploads/', null=True, blank=True)
media_url = models.URLField(max_length=200, null=True, blank=True)
player_url = models.URLField(max_length=200, null=True, blank=True)
duration = models.IntegerField(null=True, blank=True)
episode_num = models.IntegerField()
audio = models.FilePathField(path='D:/DJK Podcast/Website/dev/DJK-Gametime-Website/podcast_episodes/audio', max_length=300, null=True, blank=True)
# string method to print out all of the values of a episode object to a string
def __str__(self):
return f'Title: {self.title} ' \
f'\ndescription: {self.description} ' \
f'\nlogo: {self.logo}' \
f'\nmedia_url: {self.media_url}' \
f'\nplayer_url: {self.player_url}' \
f'\nduration: {self.duration}' \
f'\nepisode_num: {self.episode_num}' \
f'\naudio: {self.audio}'
from django.test import TestCase
from podcast_episodes import utility
from .models import episode
import os
import requests
from .views import list_episodes
from dotenv import load_dotenv
from .serializers import episodeSerializers
# Create your tests here.
class TestPullPodbeanData(TestCase):
def testsetUp(self):
print('pulling data from Podbean')
# utility.podbeanDataPull()
print('pulling podbean data')
token = utility.getPodBeanToken()
url = f'https://api.podbean.com/v1/episodes?access_token={token}'
podbeanEpisode_list = {}
response = requests.get(url)
podbeanEpisode_list = response.json()['episodes']
i = 0
for podbeanEpisode in podbeanEpisode_list:
# print(podbeanEpisode)
episode_data = episode(
title=podbeanEpisode['title'],
description=podbeanEpisode['content'],
logo=podbeanEpisode['logo'],
media_url=podbeanEpisode['media_url'],
player_url=podbeanEpisode['player_url'],
duration=podbeanEpisode['duration'],
episode_num=i,
audio=None
)
episode_data.save(force_insert=True)
print('model save performed')
print(f'====================================================')
# print(newEpisode.id)
# print(newEpisode)
i = i + 1
I am using #help-pie right now if that helps to discuss there
over the web
check your faq for the host your using, every place is different. aws for instance isnt a fan of simple restart of apache. ive had to reboot the server to get it to work
i rebooted the linode then reset the cache but still nothing
i don't see how it's setting the passwords differently. for create_user and create_superuser the password is set in the same way (using set_password())
are you sure that the file being accessed has actually been modified?
ill double check that the files have been modified
what file was updated?
im using a gatsby theme so it would be projects.mdx
Have a look at the code it isn't one uses set_password whilst the other doesn't?
self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
)
self.create_user() references:
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
which uses .set_password().
ohhhhh
https://www.gatsbyjs.com/docs/how-to/local-development/troubleshooting-common-errors/ not sure if that has anything to do with it. just googled your issue and that was one response
hes right, i didnt catch that
hey guys, i cant get my image to appear on html
stored locally in a folder named images
images is in the same directory as my index.html
ive tried using <img src="images/appa.gif"> but its not showing
@wicked elbow following up on my previous question, I was able to figure out why my test data was not showing up in the test db. It was because at the end of each test the test db is rolled back even after running manage.py test --keepdb so that is why I wasn't seeing anything. This article explains how to run a test and to see it in the DB (warning it skips the testdb and goes to your live one)
https://stackoverflow.com/questions/30504031/how-can-i-keep-test-data-after-django-tests-complete
I never said JavaScript was OOP based? I said most likely not, just like Python you have the choice to or not use Classes and the such. I said maybe your being mistaken with Java O.o
Hello, I'm having some problems running django-admin. Can someone help me?
Basically it's trying to run from a path where there's no interpreter, made up of some corrupted version of the username (e.g., if my username is "TristanΓsolda" it's trying to run it from "Tristan`solda/whatever/python.exe"
Nvm, managed to fix it, I hadn't refixed the interpreter path with PyCharm
I'm now immersed on other problems (loading data from a form.ModelForm, loading CSS from outside the app,...), but at least I managed that one π€£π€£π€£
Yes, learning Django by oneself is a hard process. Moreso when I have to check thrice what I could do in html
In Flask, are there any sort of ways to output the result of functions from a Python script on a HTML page? At the moment, as you can see from the pic, Iβm using the F-string (in the main app.py file) to embed multiple paragraphs, break tags (in string literals) to evaluate/execute function calls (which are expressed within the curly braces)
have an nginx/django/uwsgi problem.
im trying to host a django website on a VPS. so far so good, i got it working, got cloudflare and the domain setup. site displays perfectly fine.
i run into an issue: the site is not secure. weird. testing at https://www.whynopadlock.com/ shows that it may be because the website doesnt force SSL.
go into nginx config for my website, force https. here's the issue: after doing this, the site is refusing my connection.
opened port 443 on iptables, nope, didnt work. still blocked.
anything else i can try? i figure i might need to go into nginx.conf to open 443, but i cant figure out how, the only tutorials out there for this use self-signed certs and i am not, im using ones from cloudflare
Why No Padlock? - Why is my SSL web page insecure? Find the culprit!
Looks like its secure for me
no, thats the site im using to test mine, lol
Oh
Hey, I have a problem with requests module would you help please? I just want to get text in https://crowbar.steamstat.us/gravity.json not the html source. How can i do it
tried a lot of things but haven't found a way yet
@mellow shadow not really a web development question, but that is a json file. you need to use the json library to make it a dict you can work with and grab what you want. you dont just "convert to text". you have to tell python how you want it as text
Hi,I am having an issue with SQLAlchemy and Flask, basically I have these 2 models: Key and User these both interact with each other, as they are big models with many methods they are stored in different files, amongst the methods there is a method that needs the import of Key to the User model, I am getting circular import errors though, does anyone have any fix for this?
This is the method I am getting an error at, its a method of User
@classmethod
def group_for_admin(cls):
userobjs = User.query.all()
users = {}
for user in userobjs:
if user.key == '':
user.key = 'NO KEY'
users[str(user.discord_id)] = {'key_type': Key.get(user.key).type, 'email': user.email, 'key': '-'.join(user.key[i:i+5] for i in range(0, len(user.key), 5))}
return users, len(userobjs)
I am import Key in order to use its Key.get method
This is the error I am running into:
Feb 07 01:12:38 app-server uwsgi[194824]: Traceback (most recent call last):
Feb 07 01:12:38 app-server uwsgi[194824]: File "./app.py", line 19, in <module>
Feb 07 01:12:38 app-server uwsgi[194824]: from services import db, mail
Feb 07 01:12:38 app-server uwsgi[194824]: File "./services/__init__.py", line 2, in <module>
Feb 07 01:12:38 app-server uwsgi[194824]: from .database.models.key import Key
Feb 07 01:12:38 app-server uwsgi[194824]: File "./services/database/models/key.py", line 11, in <module>
Feb 07 01:12:38 app-server uwsgi[194824]: from .user import User
Feb 07 01:12:38 app-server uwsgi[194824]: File "./services/database/models/user.py", line 2, in <module>
Feb 07 01:12:38 app-server uwsgi[194824]: from services.database.models.key import Key
Feb 07 01:12:38 app-server uwsgi[194824]: ImportError: cannot import name 'Key' from partially initialized module 'services.database.models.key' (most likely due to a circular import) (./services/database/models/key.py)
Don't completely remember but I recall a solution for circular importing being importing sometimes at the end of the file or something?
Don't completely remember but I recall a solution for circular importing being importing sometimes at the end of the file or something?
@hushed kernel you can import in functions
doesnβt have to be at the top
@rustic pebble
I figured it I think
I just changed the from services import Key to from services import *, I read it somewhere on stackoverflow
I haven't got that error since then
hi guys I have a whitenoise problem
STATIC_DIR = (os.path.join(BASE_DIR, 'staticfiles'))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'```
but it doesnt work on deployment.
INSTALLED APPS has :
'whitenoise.runserver_nostatic',
MIDDLEWARE has:
'whitenoise.middleware.WhiteNoiseMiddleware',
what am I doing wrong?
with this same settings on local test it works.
with debug false
hmmm, you could make sure it is not a permission issue. Depending how/where you are deploying.
I am not familiar with whitenoise, but normally I need to direct my webserver to the static files and give that webserver permissions to access/serve those files
hmm i see
i don't know
when i was using student url like,
127.0.0.1/student and in urls.py student
it was working fine
but now even student got appended slash
127.0.0.1/student/
something is going wrong
does anyone know what does "autoescape" actually do in Django? i've read the official doc, but i still dont get it
Is this in reference to the rendering engine?
Oh then yes
Basically auto escape wipl escape any js, html etc... So it renders as normap text
hi
i have domain name which i map to my ip
but when i open domain.com in my browser instaed of showing domain name it show ip:port of my flask app
@native tide Did you ever solve your ngingx/uwsgi problem?
how can i get those 2 picture and the title at them structure as a navbar, it should be for mobile phones
this is my code so far
i also use a link of bootstrap
should be like this, but just for mobile phones
I know how to do it without any frameworks
you put the 2 pictures and a text inside a div, make it display flex, if its more then one text put it in a div . justify-content: space-around
bootstrap IDK
@haughty turtle this is my css
Yea I happen to have the same problem, but when I turned debug off, it's fixed
I have explained why this is happening...
sure
... just ask... Why make the question longer?
so my website isn't going so well
ask the question
there's no need to "ask to ask"
anyone here who knows how to connect and html with python
use a framework like flask / django
@haughty turtle maybe I am wrong but I played with python and now learning js,for me, js is not same as python
I am feeling like I am using dict of python just in a bit different way and that's allπ
And what I was trying to say is that js is like mimicrying OOP that's what I meant for OOP being forced upon js π
If I said something unusual or incorrect,please respond!
i want to make a lot of codes to my website to make it more better but idk how?
i use wix
hey there, I posted a question on #help-burrito about Django π
Alot more code doesn't mean your website will looks better
Wix is a drag and drop so the only limitations are your imagination
how to pass variable from one page to another
@haughty turtle i switched to gunicorn and it worked lol
i feel like the issue was that the directory was wrong, but gunicorn seems better anyways
Store it in a database and parse it back uwu
or js localstorage
got you
Or cookies
1 more thing
?
this
this is my table image
i need to count those rows
which only disease == breast
in this the output is 2
i count total number of rows
So you want to count the amount of queries of a specific disease?
flask
i use this
to count totatl numebr of rows
<script type="text/javascript">
var totalRowCount = 0;
var rowCount = 0;
var table = document.getElementById("example");
var rows = table.getElementsByTagName("tr")
for (var i = 0; i < rows.length; i++) {
totalRowCount++;
if (rows[i].getElementsByTagName("td").length > 0) {
rowCount++;
}
}
message = rowCount;
sessionStorage.setItem("message",message);
console.log(message);
</script>
which is fine
but i need to count specific disease
Hello i have been using the Django web framework for a little while and want to up my game. So i want to actually do unit test for everything. Can anyone suggest a good resource to learn and put into practice?
ya
sure
<div class="col-lg-12 text-center pt-4 mt-4">
<h1><b><u>MEDICAL REPORTS</u></b></h1>
<table id="example" class="table table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Date</th>
<th>Disease</th>
<th>Has Disease</th>
<th>Report</th>
<th>Update</th>
</tr>
</thead>
<tbody>
{% for result in results %}
<tr>
<td><b>{{result.mrn}}</b></td>
<td>{{ result.name }}</td>
<td>{{ result.date.strftime("%Y-%m-%d") }}</td>
{% if result.disease|string() == "Breast" %}
<td>{{ result.disease }}</td>
<td>{{ result.breast_class }} ( {{ result.breast_confidence }} )</td>
{% else %}
<td>{{ result.disease }}</td>
<td>{{ result.has_disease }}</td>
{% endif %}
<td><b><a href="{{ url_for('invoice', id=result.mrn) }}" title="">Report</a></b></td>
<td><a><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">Update</button></a></td>
</tr>
{% endfor %}
</tbody>
</table>
@toxic flame
You should add a class to the breast disease, then javascript parse all the elements with the same Class Name, count it and add them together.
then set an element to the count
we cannot get directly as i did to get total number of rows?
The method I suggested is to get the number of rows / classNames that contains a specific className
Since in your code if disease isn't "breast" then it won't appear
I'm not completely getting the gist of what you want to do, sorry ;-;
see i have total patients from those patient some have heart disease , some diabtese , some eye
from total patient i need to get only those patient which has diabetese and so on
I want to create a simple website as a drawing platform for my project, where do i start?
yea
Hey @obtuse obsidian!
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:
Hey @obtuse obsidian!
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:
are you allowed to use social media logos for you personal website as links to your social media profiles?
yes
<div id="game">
<div id="javascriptError">
<div id="loader">
<div class="spinnyBig"></div>
<div class="spinnySmall"></div>
<div id="loading" class="title">Loading...</div>
<div id="failedToLoad" class="title">This is taking longer than expected.<br>
<div style="font-size:65%;line-height:120%;">Slow connection? If not, please make sure your javascript is enabled, then refresh.<br>
If problems persist, this might be on our side - wait a few minutes, then hit ctrl+f5!</div></div>
<div id="ifIE9" class="title" style="font-size:100%;line-height:120%;">Your browser may not be recent enough to run Cookie Clicker.<br>You might want to update, or switch to a more modern browser such as Chrome or Firefox.</div>
<!--<div class="title">Oops, looks like we've got a problem.</div>
<div>Please bear with us while we fix it.<br>Your save is safe, don't worry!</div>-->
I am a beginner to python and django and i dont know how to map my address model automatically to the applicant while registrating```python
class Address(models.Model):
city = models.CharField(max_length=100, null=True)
state = models.CharField(max_length=150, null=True)
postal_code = models.CharField(max_length=50, null=True)
street = models.CharField(max_length=200, null=True)
country = models.CharField(max_length=200, null=True)
class Applicant(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
address = models.OneToOneField(Address, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
avatar = models.ImageField(default="profile1.png",null=True, blank=True)```
@unauthenticated
def applicantRegisterPage(request):
form = CreateUserForm()
context = {'form': form}
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
applicant = form.save()
group = Group.objects.get(name='applicant')
applicant.groups.add(group)
Applicant.objects.create(user=applicant)
else:
return render(request, 'kastujo/registration.html', context)
return render(request, 'kastujo/registration.html', context)
how do i get my code in boxes
3x ` at the beginning and end
hello
yes
oo tnx
<div id="javascriptError">
<div id="loader">
<div class="spinnyBig"></div>
<div class="spinnySmall"></div>
<div id="loading" class="title">Loading...</div>
<div id="failedToLoad" class="title">This is taking longer than expected.<br>
<div style="font-size:65%;line-height:120%;">Slow connection? If not, please make sure your javascript is enabled, then refresh.<br>
If problems persist, this might be on our side - wait a few minutes, then hit ctrl+f5!</div></div>
<div id="ifIE9" class="title" style="font-size:100%;line-height:120%;">Your browser may not be recent enough to run Cookie Clicker.<br>You might want to update, or switch to a more modern browser such as Chrome or Firefox.</div>
<!--<div class="title">Oops, looks like we've got a problem.</div>
<div>Please bear with us while we fix it.<br>Your save is safe, don't worry!</div>--> ```
in a game, irl i have a bmw****
Is there anyone here experienced with braintree customer/token/payment flow? I'm rebuilding an ios app in swiftui and I want to switch from stripe to braintree. I need to store payment info for non scheduled reoccurring payments like uber or lyft. The documentation is a little sparse on details for this and when there are details they are scattered around and not very well connected... I think the flow should be ```
- Create Customer ID (server)
- Create token from customer (server).
- Send token to client.
- Client adds token to dropin ui.
- Brain tree sends client a nonce from payment info provided.
6 send nonce to server.
7 update customer with nonce
everything is geared towards single payments or reoccuring payments
Hello. Does anyone have any information on how to make a python web server using the django rest framework for game. I am using Unity3d. Maybe someone has some code, for example on github. Or you can drop some resources to figure out how to do it.
@hallow moon what type of communication will you need for your game? Http requests might not do so well for a highly interactive game and you might need lower level UDP or TCP to keep a free flowing stream of data
but if its something simple like updating trivia questions and relaying answers HTTP would be fine
can anyone help me why my dropdown-menu doesn't work?
Django signals. You can have a post_save signal which is a function that runs after a specified model has been saved (.save()) or created, depending on your use case. This can be used to assign a relationship, etc.
You could also do some assigning manually within your view, but signals are cooler and will help you solve some issues later on
Hey, I am making an api using the django rest framework: https://www.django-rest-framework.org
I was wondering what the best way to authenticate would be. I have two situations so to speak:
- A discord bot is authenticating but is using the permission set of another user
- A browser is authenticating using its own permission set
Using Token Authentication for a discord bot and Session Authentication would seem like the correct way to do this but beyond that I am not 100% sure. My guess for the best way to go about this would be a custom Authentication case that decides whether what the request is coming from. But I am not really sure if that is the best way of going about this?
from .models import User, Post, Project, Comment, Version, Tag
from rest_framework import serializers
import bcrypt
from .models import Stock
class PostSerializer(serializers.ModelSerializer)
class Meta:
model = posts
fields = 'all'
def create(self, validated_data):
I want this serializer to convert the comments under a post to Json
I think it will do. It's just hard to make a web server for an external client, not a Django site.
Thanks!
Ah ok yea django can handle that. I've got a open source website that you can look at for client side login/signup/social auth/password reset here
Basically just use this for end points and what to post with it
Django, API, REST, Serializers
from rest_auth.registration.views import (
RegisterView, VerifyEmailView, LoginView,
)
from rest_auth.views import PasswordResetView, PasswordResetConfirmView
urlpatterns = [
# Rest Auth endpoints
path('api/rest-auth', include('rest_auth.urls')),
path('api/rest-auth/registration/', RegisterView.as_view(), name='registration'), # nopep8
path('api/rest-auth/registration/verify-email/', VerifyEmailView.as_view(), name='verify'), # nopep8
path('api/rest-auth/login/', LoginView.as_view(), name='rest_login'),
path('api/rest-auth/password/reset/', PasswordResetView.as_view(), name='reset'),
path('api/rest-auth/password/reset/confirm/', PasswordResetConfirmView.as_view(), name='confirm'),
path('password-reset/<uidb64>/<token>/', empty_view, name='password_reset_confirm'),
path('api/auth/', include('rest_framework_social_oauth2.urls')),
path('api/social/', include('social.apps.django_app.urls', namespace='social')),
path('api/accounts/', include('allauth.urls')),
]
those are the endpoints you'll need. and just follow all-auth and rest-auth on how to setup your django server
Yeah but how do I do it cuz I cnat get help out of that guide
The guy who asked about twitch
Your Response variable is empty
???
Oh, thank you so much. Because I had a long break in programming, and now they took an internship
Maybe try adding the comments = CommetsSerializer(many=True) field to the PostSerializer, and then doing what you want. And of course, make a serializer for comments
What would be the best way of detecting what type of client is connecting?
@misty goblet its stored in the http request somewhere. I know in django it shows up when requests are made but where is it and how do you get it don't know... ```Feb 07 12:49:07 ubuntu-s-1vcpu-1gb-sfo2-01 gunicorn[4807]: - - [07/Feb/2021:20:49:07 +0000] "GET /v0/fin_user HTTP/1.0" 200 2972 "-" "fin-aquatic-rentals/1.0 (Fin-Aquatic-Rentals; build:1; iOS 14.3.0) Alamofire/5.4.1"
this can also be spoofed though
it relates to my earlier question on my own server vs a normal client #web-development message ? not sure if that means I could do it a better way
Hello, I'm developing a web app with flask and I'm using bs5 to help with front end, my goal is to have a signin form inside a modal, but unfortunately I can't get it to work, it just reloads the website, any tips?
@misty goblet found it, i had to copy the css and js from bootstrap and insert it in my html too
yeah, sorry i meant to reply with some css for you but I had to go deal with something else
is it normal my admin dashboard looks like this on deployment using whitenoise lol
i think i just broke my site lul
ffs
oof fixed it
ooi What was your issue?
Something related to whitenoise
in django is it possible to to only let a field be changed once specifically False -> True and not the other way around?
Guys how would I add a navigation bar but when I click the href link it opens a new route? I am using Flask
hi, i want my images to be saved locally as well as upload on aws s3 in django ImageField, i've done the s3 part but stuck on saveing at both location, anyone know how to do this?
override .save
but why do you want to do that?
i have to perform some analysis on those images on server but want them on s3 aswell
thanks btw
where are you hosting?
it's not ephemeral storage right
it is
aws
im getting this error in django
def create(response):
if response.method == "POST":
form = CreateNewList(response.POST)
if form.is_valid():
n = form.cleaned_data["name"]
t = ToDoList(name=n)
t.save()
return HttpResponseRedirect("/%i" %t.id)
else:
form = CreateNewList()
return render(response, "main/create.html", {"form": form})
this is the function i made
I need people for help me in django
"t" is in if block, and u r accessing it outside of "if"
If I have this page and I want that if someone hover over div d1 then the font awesome icon f becomes visible.
Font awesome icon is in other div.
Javascript
Using "onmousehover"
Here is a quick example
element.addEventListener("mouseover", mouseOver);
function mouseOver(){
element.innerHTML = "hover"
}
And for "unhover" ( idk if that's even a word )
Just change mouseover to mouseout
mornin' what is the recommended way of getting values for a dropdown? options, hardcoded, reading from a module kind of import, reading from a csv, or reading from a database
around 50 values
In Flask is there a way to display visuals (generated from matplotlib.pyplot module) onto HTML webpages using Python?
hey guys, i have this problem in my django webpage
i have made a sidebar, and its covering the content of the webpage
heres the css
<style type="text/css">
.sidenav {
height:100%;
width:160px;
position: fixed;
z-index:1;
top:0;
left:0;
background-color:#111;
overflow-x: hidden;
padding-top:20px;
}
.sidenav a {
padding:6px 8px 6px 16px;
text-decoration: none;
font-size:25px;
color: #818181;
display:block;
}
.sidenav a:hover{
color:#f1f1f1;
}
.main{
margin-left:160px;
padding: 0px 10px;
}
</style>
@toxic flame
I have done this using JS but I want it using css
hey can you help me you seem like you are very smart
:)
I dont think its possible to make an outside div react with an inside div event, not sure idk
hey can you help me:)
The ideal method is to make your body a double grid
Or a flex
can you show me how to do it lol i am a noob
box
(style)
#body{ display: grid ; grid-template-columns: 1fr 9fr;}
<body id=body>
</body>
I guess
U gotta do other stuff to make it responsive though
ok but i am following a youtubers tutorial, and i will get confused if i use your method, so can you just tweak the settings of the css and fix it lol?
this one
aw dang np
If the tutorial doesnt show you then the tutorial isn't the best
in flask i have an email validation and if the email is not valid the message is "Email is already given". How can i put that message in html so it shows up
pass the message in a context and display it in the html
i saw it can be done with flask flashing @toxic flame or you have another way
I'm not familiar with flask but that's how programming works in general i suppose
ahh thanks
I made sign signup using django
But it is directly redirecting to index page
When I goto login or signup urls
Any1 can help me
Sign in**
It should be redirect to index page only after login or signup
Whatβs the best Python web package for doing a lot of dynamic pages with fast speeds
I heard vibora is good
vibora is dead
and also much slower than they make out to be
So what would you recommend
