#web-development
2 messages ยท Page 173 of 1
and reinstall
wdym delete aws
just delete it
Django in production doesn't serve static files, it's only in development when debug=True, have you accounted for that?
Anychance I can get a hand here, no matter what I do this validation always fails:
class Cipher147Form(FlaskForm):
encrypt = SubmitField('encrypt', validators=[Optional()])
decrypt = SubmitField('decrypt', validators=[Optional()])
nonce_options=["hybrid", "random", "time"]
encoding_options=["base85", "base64", "base32", "base16"]
key = StringField('key', validators=[InputRequired()])
text = TextAreaField('text', validators=[InputRequired()])
nonce = SelectField('nounce', validators=[InputRequired()], choices=nonce_options)
encoding = SelectField('encoding', validators=[InputRequired()], choices=encoding_options)
@app.route("/encryption/147cipher", methods=['GET', 'POST'])
def cipher147():
form = Cipher147Form()
if request.method == "POST":
if form.validate_on_submit():
key = form.key.data
text = form.text.data
nonce = form.nonce.data
encoding = form.encoding.data
if form.encrypt.data:
output = encrypt_147(key, text, encoding, nonce)
elif form.decrypt.data:
output = decrypt_147(key, text, encoding)
data = [key, text, encoding, nonce, output]
return render_template('encryption/147cipher.html', title="147Cipher", form=form, data=data)
else:
return render_template('encryption/147cipher.html', title="147Cipher", form=None)
Here are my imports:
from flask import Flask, render_template, send_from_directory, request
from flask_wtf import FlaskForm
from wtforms import form, StringField, TextAreaField, SelectField ,SubmitField
from wtforms.validators import InputRequired, Optional, length
Here is the HTML bit:
<form method="POST">
{{ form.csrf_token }}
And I do set the key:
# Pull secret key.
app.config['SECRET_KEY'] = os.getenv('CSRF_KEY')
have you checked form.errors to see which fields are failing?
No I don't know how to get that to print somewhere
How can I do that?
print(form.errors)
I did try that and it didn't print...
show code
btw, if request.method == "POST": is irrelevant, form.validate_on_submit(): checks that the request method is POST iirc
Oh nice
Thanks
I tried this and I get no print in the terminal
@app.route("/encryption/147cipher", methods=['GET', 'POST'])
def cipher147():
form = Cipher147Form()
if request.method == "POST":
if form.validate_on_submit():
key = form.key.data
text = form.text.data
nonce = form.nonce.data
encoding = form.encoding.data
if form.encrypt.data:
output = encrypt_147(key, text, encoding, nonce)
elif form.decrypt.data:
output = decrypt_147(key, text, encoding)
data = [key, text, encoding, nonce, output]
return render_template('encryption/147cipher.html', title="147Cipher", form=form, data=data)
print(form.errors)
else:
return render_template('encryption/147cipher.html', title="147Cipher", form=None)
does errors need imported?
its set to deub = false and that wasn't the problem
yeah when debug=False django does not serve staticfiles, another server is meant to serve staticfiles. maybe amazon s3 bucket I've heard, but I don't have any experience doing it
I removed the if POST, though yeah I still don't know how to actually print the errors
apparently i had many other things wrong with my stuff and when i was testing everything locally so i thought i didn't have any errors with my django stuff but i did and that became evident when i tested it on the aws server
if form.validate_on_submit():
# form stuff
else:
print(form.errors)
see if that gets anything in your console
Without the else returning the rendered_template, I can't render the template to test if with inputs in the form.
One sec...
Oh weird
It thinks the token is missing
{'csrf_token': ['The CSRF token is missing.']}
that's retrieving the env variable, did you actually set it?
hmmm... inspect the page source and see if there's a hidden field with the csrf key
right click on the page in the browser, inspect element, check the html code for your form. see if there is a hidden input for your csrf key
Oh
Well there is a gap where the key should be...
<form method="POST">
<div class="card">
<div class="card-body">
<div class="row">
This is what should be there:
{{ form.csrf_token }}
Yes, localhost
There is this weird thing called wtx-context everywhere
Also a weird dashlane thing... which is odd.
hmm, I don't use flask so it's hard to say, but if you don't see any hidden inputs for your CSRF token in the form that's the problem...
are there no errors in your flask server?
might want to check that the SECRET_KEY is actually populated
To be fair I have no idea what I am looking for when it comes to hidden inputs
How would I check it is populated
it'll be something like:
<input type="hidden" name="CSRF_TOKEN" value="csrf_token_here"></input>
by printing it
Printing it says it is none
Fixed it
Needed this right before the </form>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
Also needed this at the start:
csrf = CSRFProtect()
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('CSRF_KEY')
csrf.init_app(app)
What a nightmare lol
Thanks for your help Nicky, I was going crazy. Glad you were here to talk me through where I should focus, was a massive help.
๐
hey everyone
@app.route('/user',methods=["GET","POST"])
def user():
if "student" in session:
current_student=Students.query.get(session['student'])
form=Uploading()
ext={'.jpg', '.png', '.pdf','.txt'}
if form.validate_on_submit() and request.method=="POST":
file=request.files['uploadfile']
if pathlib.Path(file.filename).suffix.lower() in ext :
current_path = os.getcwd()
if not os.path.exists(current_path+"/Flaskiproject/static/fileupload",current_student.fullname):
print(current_path)
os.mkdir(os.path.join(current_path + "/Flaskiproject/static/fileupload",current_student.fullname))
uploaded_file=secure_filename(file.filename)
file.save(os.path.join(current_path + f"/Flaskiproject/static/fileupload/{current_student}",uploaded_file))
else:
uploaded_file=secure_filename(file.filename)
file.save(os.path.join(current_path + f"/Flaskiproject/static/fileupload{current_student}",uploaded_file))
else:
flash(" we don't allow this file extension ")
return redirect(url_for('user'))
else:
return redirect(url_for("login"))
return render_template("User/Homepage.html",student=current_student,form=form)
```py
this getting kinda ugly somehow a lot of code and stuff but anyway
im struggling to make this code cleaner anyone please
what would cause a request body to be formatted like this in my packet sniffer
encryption, a binary file, or a text file with a non default encoding.
can someone help me figure out why this is suddenly happening when I try to run using uvicorn main:app?
...
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 846, in exec_module
File "<frozen importlib._bootstrap_external>", line 983, in get_code
File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
ValueError: source code string cannot contain null bytes
Any Javascript library to filers and cropping the video that is uploaded
:incoming_envelope: :ok_hand: applied mute to @inland copper until 2021-07-18 06:35 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
How to pass multiple headers in webclient ?
Hello
When is it ok for a csrf_token not to expire with a wtf_form
Since it disappears with session end anyway.
I'm building a simple API using the Flask module, does anyone know how to add an image to it?
Hello!
Hi!
You will need to elaborate on what you mean by add an image to it
im gonna send the code
`import time
import tkinter
import flask
from flask import Flask
from flask import request, jsonify
import flask
app = flask.Flask(name)
app.config["DEBUG"] = False
@app.route('/')
def home():
return "<font color='#00ff00'><h1>Hi baba</h1></font><marquee><font color='#00fa9a'><p>I hope you become better!</p></font></marquee><p>If you viewed this click this button</p><button><a href='http://192.168.100.2:5000/hello'>Click this!</a></button>"
@app.route('/hello')
def hello():
return "<font color='#00ff00'<h2>I hope you get well soon!</h></font><button><a href='http://192.168.100.2:5000/p3'</a></src></button>"
@app.route('/p3')
defp3():
return '3rd page lol'
app.run(host='0.0.0.0')` So basically i want the "p3" to return the code for an image to be displayed on http://192.168.100.2:5000/p3
So basically i want the "p3" to return the code for an image to be displayed on http://192.168.100.2:5000/p3
Im pretty new lol
ok thank you!
When showing it on Discord I should add
As far as returning an image, could just add it to the html to my knowledge. Also probably nicer if you use render_template()
ok tysm
Hey guys, I have a form in Django and I want to redirect the user to the newly created object after submission, but I get this error:
The view hrm.views.volunteer_create_view didn't return an HttpResponse object. It returned None instead.
Here is my code:
def volunteer_create_view(request):
form = VolunteerCreateForm(request.POST or None)
if form.is_valid():
new_vol = form.save()
messages.success(request, 'Volunteer created sucessfully')
return HttpResponseRedirect(reverse('hrm:person', args=(new_vol.id)))
I have learned python
Now i wanna start
Web development
So which one will be good
Flask or django
I know difference between flask and django but i just cant get myself to decide
You're not handling the case when form is invalid
Some people would say flask. I personally started with Django and really enjoyed it.
Just choose one and go
You'll probably end up learning both
so I have to enter an else?
I guess i will go with django to
yes
im starting with quart (flask but async)
Oh ok
I installed Django but when i want to start a project it says that the command "django-admin startproject mysite" is unknown
you have to make a virtualevnviroment
try pip freeze
pip freeze will tell you which modules you have installed and am certain django will be one of those models but you can't run the cmd like that. Just use virtualenv https://docs.python.org/3/library/venv.html
Django is better and smoother and more organized
i'd suggest flask for apis tho
Why is this starting week on wednesday? Appointment(date__week_day=date.weekday())
Using django 3.2
should i do this or not?
or should i just pass my object in the view logic as context
Any reasons besides readability
Not to sound ignorant but is there any hits on performance ?
Django is designed in a way on purpose that you have to do most of the stuff on views.py because it makes the app more secure
Templates are served for everyone so it's more vunerable
oh
so how much flexibility do i have with the request object in the template context
you have all the same request things that template has
i cant understand what you're trying to say
He means that its better to put that thing in the context so the template doesn't involve the logic to call it
I guess
Yes, because html templates are unsecure and views.py is made to do the logic for you
Hello. I'm using Wagtail and I want to create a page with custom parametrized route
Like /something/4
currently I do this :
def Success(request, year):
name = {
'resp': year,
}
return render(request,"response/response_page.html",name)
With
urlpatterns = [
path('resp/<int:year>', views.Success),
]
which works, shows the page but doesn't show the wagtail page with content modified from the CMS, just an empty HTML
because the Slug is equal to resp in wagtail
def login(request):
if request.method=='POST':
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user is not None:
return HttpResponseRedirect('/')
else:
return render(request,'users/login.html')
return render (request,'users/login.html')``` idk why but when i'm using the login panel and enter correct password (of any user ) so it do not works but if i enter id password of admin there that works
from django.contrib.auth import authenticate
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
``` ig error can be in 1st import cez idk authenticate
umm
@dusk portal are your users stored in the User model?
@glossy scroll just for readability sake, keep most if not all of the logic in the view.
so its only readability?
Yeah - whether you're accessing data from the request in the view then passing it to your template or accessing request directly from the template, there is no difference. It's just readability, and to debug an issue it helps having it all in one place
It's not "more vunerable" as someone said.
hello guys, working on Django project and sending to template dict that have 1 item - list of dicts, trying to parse it in template and get info but nothing works (
how i send to template:
# db_worker.write_to_db()
data = db_worker.read_db(1)
dic = {'data': data}
return render(request, 'main/blocks.html', dic)```
what contains *data*:
```[{"hash":"384f3e42b8e26443bc1087a0387827146a41f9d3ef663a7d7eda82c927e78bf2","height":"315012","timestamp":"1624372128","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"bcf54ece598e7def8fedfea23c2f4cce7bd2d1ec35351fe9f4d8523ac2fa26de","height":"315011","timestamp":"1624372016","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"aef7e142303e54c08f885965877199f6af6ee4da8687eed8505e6a4fb41ef446","height":"315010","timestamp":"1624371920","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"50ca063a86f434ce08e7e8537808662a0e782935eb5e72bdb506c5e32b5a3391","height":"315009","timestamp":"1624371808","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"f592d181a1bec34566509152d1e0e5ac8531ae23b5a91e6bec27ade3001e69bf","height":"315008","timestamp":"1624371648","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"}]```
part of HTML template:
```<table>
<tr>
<th>height</th>
<th>hash</th>
<th>timestamp</th>
<th>miner</th>
<th>transactionsCount</th>
</tr>
{% for val in dic.data %}
{% for i in val.values %}
<tr>
{{height}}
</tr>
<tr class="even">
{{hash}}
</tr>
<tr>
{{timestamp}}
</tr>
<tr class="even">
{{miner}}
</tr>
<tr>
{{transactioncount}}
</tr>
{% empty %}
<li>Sorry</li>>
{% endfor %}
{% endfor %}
</table>```
but it not work
tried couple of methods
{% for val in dic.data %}
dic is the context. You can't access the objectdic within dic, only the keys within dic.
so this should be:
{% for val in data %}
still not works
well that's not the only thing you have to change, your logic here is incorrect, try to fix it:
{% for i in val.values %}
<tr>
{{height}}
</tr>
<tr class="even">
{{hash}}
</tr>
<tr>
{{timestamp}}
</tr>
<tr class="even">
{{miner}}
</tr>
<tr>
{{transactioncount}}
</tr>
you mean troubles in html?
syntax and logic
im pretty new in thes sphere
Ok you're looping through each value in the dictionary:
{% for i in val.values %}
but then you're trying to access variables that were never defined?
<tr class="even">
{{hash}}
</tr>
<tr>
{{timestamp}}
</tr>
<tr class="even">
{{miner}}
</tr>
<tr>
{{transactioncount}}
</tr>
{{hash}} for example isnt key that im just call ?
If you simply want to loop through the values:
{% for i in val.values %}
<tr>
{{i}}
</tr>
{% endfor %}
no, what you're doing there is trying to get the hash variable from context...
also, how can you even access keys? You're looping through val.values, which are the values not the keys of the dict
try:
info = api_requests.req_info()
return render(request, 'main/index.html', info)
except:
return HttpResponse("Something went wrong")```
``` <ul><h3>
<a href="/admin" ><h1>Admin page</h1></a>
<a href="/blocks" ><h1>Blocks page</h1></a>
<br><br>
<li>height: {{height}}</li>
<li>supply: {{supply}}</li>
<li>circulatingSupply: {{circulatingSupply}}</li>
<li>netStakeWeight: {{netStakeWeight}}</li>
<li>feeRate: {{feeRate}}</li>
<li>dgpInfo: {{dgpInfo}}</li>
</h3></ul>```
Here im not defining anything, just sending dict and then pulling keys
<tr>
{{height}}
</tr>
<tr class="even">
{{hash}}
</tr>
<tr>
{{timestamp}}
</tr>
<tr class="even">
{{miner}}
</tr>
<tr>
{{transactioncount}}
</tr>
{% endfor %}```
changed to this
and as i think val should contain these keys
okay, so does this work?
nope
as u can see here, it doesnt
thats why im really confused, why it not works
no, the code which I am replying to
does that work?
yesm it works
but in that case im sending only the dict as JSON
hey i have a questio
django default db is sqlite and all its authentication tables uses it so if i change my db to mongo can i still able use default authentication tables
i changed to PostgreSQL
and made model
hash = models.CharField(max_length=100)
height = models.CharField(max_length=9)
timestamp = models.CharField(max_length=50)
miner = models.CharField(max_length=100)
transactioncount = models.CharField(max_length=3)```
ok so all things remain same just like in sqlite
Ok, I'll explain why:
With the code that works, you're passing the context info, let's say it's this:
info = {
height: x,
supply: y,
circulatingSupply: z
}```
In your template, when you do `{{height}}` you are accessing the key `height` in your context, so that will work. It will show `x` in the template.
In your non-working code, your context is now this:
```py
{
data: {
height: x,
supply: y
}
}```
so doing `{{height}}` is no longer valid. You have to do `{{data['height']}}`
then pulling and pushing with these code:
from . import api_requests
import json
def write_to_db():
blocks = api_requests.req_block()
conn = None
try:
conn = psycopg2.connect(host="localhost", database="crypto", user="postgres", password="admin")
cur = conn.cursor()
for element in blocks:
cur.execute(f"INSERT INTO main_block (hash, height, timestamp, miner, transactioncount) VALUES"
f" ('{element['hash']}', '{element['height']}', {element['timestamp']},"
f" '{element['miner']}', '{element['transactionCount']}');")
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def read_db(offset):
conn = None
try:
conn = psycopg2.connect(host="localhost", database="crypto", user="postgres", password="admin")
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute(f'SELECT * FROM main_block OFFSET {offset} LIMIT 5;')
fetch = cur.fetchall()
dic = {}
data = []
for i in fetch:
dic['hash'] = i['hash']
dic['height'] = i['height']
dic['timestamp'] = i['timestamp']
dic['miner'] = i['miner']
dic['transactioncount'] = i['transactioncount']
data.append(dic.copy())
return data
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
yes, but to change db server there's some setup
in my case its
{'smth': data}
data:
[{...}, {...}]
that i know i was just worried that if i change it will i able to use django auth.
I know... I'm telling you why this doesn't work, you can change it so it starts to work. I'm not trying to give too many hints here...
{% for val in data %}
<tr>
{{height}}
</tr>
<tr class="even">
{{hash}}
</tr>
<tr>
{{timestamp}}
</tr>
<tr class="even">
{{miner}}
</tr>
<tr>
{{transactioncount}}
</tr>
{% endfor %}
you'll still be able to use it.
thnx for the help bro
@compact glacier in this code, I want you to understand you are trying to access the height key in your context, instead of the height key of an item in your dict. You see that?
yeah
Ok, so you just need to change it so you're accessing the height key of each item. Here's an example:
{% for key, value in data.items() %}
<tr>
{{key}}: {{value}}
</tr>
<tr>
{{data['height']}}```
tried this one, and got error
```django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['height']' from 'data['height']'
oh
with {% for val in data %} <tr> {{val['height']}} </tr>
these one not same
as this
got error
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '["height"]' from 'val["height"]'```
what is your context again?
the thing is that even when im trying just to print val it shows nothing
tried to make code as u said like this:
<tr>
{{val["height"]}}```
and got error above
yeah, so what is the context you are passing to your template?
[{"hash":"384f3e42b8e26443bc1087a0387827146a41f9d3ef663a7d7eda82c927e78bf2","height":"315012","timestamp":"1624372128","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"bcf54ece598e7def8fedfea23c2f4cce7bd2d1ec35351fe9f4d8523ac2fa26de","height":"315011","timestamp":"1624372016","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"aef7e142303e54c08f885965877199f6af6ee4da8687eed8505e6a4fb41ef446","height":"315010","timestamp":"1624371920","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"50ca063a86f434ce08e7e8537808662a0e782935eb5e72bdb506c5e32b5a3391","height":"315009","timestamp":"1624371808","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"f592d181a1bec34566509152d1e0e5ac8531ae23b5a91e6bec27ade3001e69bf","height":"315008","timestamp":"1624371648","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"}] list of dicts
as u can see here
and all this stuff is packed in a dictionary
Maybe theres some easier methods to send this stuff to page instead as one of params of render
but i dont know
well you can try:
{% for item in data %}
{% for value in item.values() %}
<tr> {{ value }} </tr>
{% endfor %}
{% endfor %}
the previous example should work, print the type of your data to ensure it's a list and not str
<class 'list'>
ok, try above example
{% for value in item.values %}
<tr>
{{value}}
</tr>
<tr class="even">
{{value}}
</tr>
<tr>
{{value}}
</tr>
<tr class="even">
{{value}}
</tr>
<tr>
{{value}}
</tr>
{% endfor %}}
{% endfor %}```
made this one, not shows anything
{% for value in item.values() %}
it not works
Keep in mind that for the dot operator, dictionary key lookup takes precedence over method lookup. Therefore if the data dictionary contains a key named 'items', data.items will return data['items'] instead of data.items(). Avoid adding keys that are named like dictionary methods if you want to use those methods in a template (items, values, keys, etc.). Read more about the lookup order of the dot operator in the documentation of template variables.
https://docs.djangoproject.com/en/3.2/ref/templates/builtins/
from official documentation
ah ok
weird... that should work.
maybe just list what's in your data key?
{% for item in data %}
{{ item}}
{% endfor %}
nothing, it shows nothing
implies that your context is empty?
try:
{{ data }}
see what that gives.
well found an mistake
and fixed it
data = db_worker.read_db(1)
sdata = {'first': data}
return render(request, 'main/blocks.html', sdata)```
i was changing name of key in dict, so the screenshot above is the result of this code:
``` {% for item in first %}
{{item}}
{% endfor %}```
I am trying to implement a system where i have a FastApi backend. And It's needs to perform some operation outside the request response process.
Ex :
- I have an endpoint that accepts some data
- I need to add that data into some list (persistent)
- As long as the queue is not empty i need a particular process to run (separate thread?). This process may also contain websockets to update the front_end with what is going on
- if the list gets empty the process should stop, but should start running again if anything gets added to list
How do i implement this in a uvicorn and fasapi compatible way ?
Thank you
ok, we have a promotion,
item.hashshows what i need, but in weird place
now HTML code looks like:
<tr>
{{item.height}}
</tr>
<tr class="even">
{{item.hash}}
</tr>
<tr>
{{value}}
</tr>
<tr class="even">
{{value}}
</tr>
<tr>
{{value}}
</tr>
{% endfor %}```
anyone know if there's a difference between using UUID or just autoincrement for storing table ID's?
how much python do i need to do to start django
OOP for minimum
any video series
i know it
but cant really understand stuff such as decorators
and stuff
and poli
The one by Corey Schafer is a good starting point
It's the one I used to get my start
Or Tech with Tim
@fleet drum Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Is it roughly the same tutorial or does Tim do things a bit differently?
as long as you know inheritance i think django shouldn't be that hard
or CS50 Django Tutorial
can docker be used to send commands between containers? I'm developing a deep learning web app that processes videos and i need to figure out a way to kickstart the deep learning algorithm once the user has uploaded their files on the front end
@cerulean mortar they can send http requests to eachother, so yes in that sense
@cerulean mortar you using CNNs?
bit differetly. hes tutorial simpler, but does not reveal many things like Coreys tutorial
pls help this error when i type django-admin and
maybe try to write any command?
how
like django-admin startproject projectname
also the same error
did u installed django via pip?
yeah
python version?
3.4
@opaque rivet thanks a lot for your help.
I changed a bit code. Now it looks like that:
<tr>
<th>height</th>
<th>hash</th>
<th>timestamp</th>
<th>miner</th>
<th>transactionsCount</th>
</tr>
{% for item in first %}
<tr>
<td>{{item.height}}</td>
<td>{{item.hash}}</td>
<td>{{item.timestamp}}</td>
<td>{{item.miner}}</td>
<td>{{item.transactioncount}}</td>
</tr>
{% endfor %}
</table>```
and it works.
ffs is there any way that i can make forms.RadioSelect widget to appear as checkbox and not that ugly circular buttons?
Leaving them their default look will help people understand how they will work.
yeah didn't think of that, but my problem is that I have a images, that have a category, but i can't make an image have a more than one category and have to work with only 1 category per image, so my idea was to use a widget and appear as checkbox
you want it to work like a radio button, so why not present it as a radio button?
i can make it work with checkboxes if i override the CheckboxSelectMultiple but it will be buggy af probably
well best case is if I can make an image have 1 or more categories and be able to choose this in the form when posting the image
you haven't said why you want it to look like a checkbox
well i like it better, but if we put that aside, i just wanna learn if there is any way I can make it to look
sorry, i don't know if there's a way
it's okay
you can apply custom classes to it, to modify its look. Generally though when using premade modules from django you don't get a lot of customization. It's best to DIY.
hey everyone! Been a while and I'm back with another problem!!
class Poll(models.Model):
question = models.CharField(max_length=250)
creator = models.CharField(max_length=100)
pub_date = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=120)
#options --> point to options database table
#option_votes --> point to options database table
def recent(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
return self.question
def get_absolute_url(self):
return reverse("polls:poll-detail", kwargs={"pk": self.id})
class Choice(models.Model):
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
option = models.CharField(max_length=200)
option_votes = models.IntegerField(default=0)
def __str__(self):
return self.option
Seeing that each question, or, Poll object has a choice_set, I want to order the results for any object by option_votes
I've been trying to do this directly via the template, but it doesn't work.
This could be pretty useful for a lot of people
https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md
looking for some help here
can you share what you did in your template, if you still have it available?
Not sure if this is the right place to ask but does anyone have any recommendations for web hosts?
Just looking for something I can host a personal site as well as python projects reliably and affordably.
netcup is very cheap and reliable for me, i would recommend it. digitalocean is rather pricy, i've also heard good things about Hetzner
@meager anchor thanks for that, i don't have much experience with hosting
are you using wtforms?
is it possible that app.root_path could be giving me the path to a similarly named directory?
i mean that doesn't even make sense but idk whats up with my code
i have a blog that i'm creating by following a tutorial, and a separate blog, and in my separate blog its selecting a profile pic thats in the directory of my first blog
both profile pic directories have the same name but I don't why that should matter
since each blog is in a completely different folder
yes
what type of file is it ?
Hi all, for structuring Django projects, anyone know what should be in the "Service" folder?
Can anyone tell me how can I replace email with phone number in django custom user model??
can someone explain how I can get the amount user that register the website in each month with flask?
ahh okay
Hey @ivory bolt!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Hey @ivory bolt!
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:
how do i debug HTTP ERROR 500
you enable debug mode in your framework
in order to receive more detailer error
Hey how do i deal with python django UserCreationFrom not showing a validation error
guys quick question. Can a website developed with django channels on backend and react on frontend have a maximum number of clients it can handle simultaneously? If so what could be the maximum?
that's the reason it wants a csrf token
What you mean? csrf token prevent csrf
look at his original question
sorry, tagged you wrongly. my fault
wtforms is the reason the app needs a csrf token etc
Hi there. I am not sure if this is directly related to web dev, but it's worth a shot asking.
I'm making a Django website for people to bulk OCR apps, So They can have multiple OCR "Jobs" which is the task of OCRing a folder contaning documents. An user can have multiple OCRs together too. Now, I have a file which does python3 ocr.py <folder-path> and I need to run it as another task whenever any user asks for it.
My questions are,
- How to I spawn a new process to run it everytime whenever user makes a new task from the website?
- How do I control each separate task as needed, such as kill, stop or restart whenever the user clicks on those buttons on the website
- How do I get the logs from the process and display to the user on the site?
- How do I keep a bound on max number of tasks that can be created in total?
Please guide me, I'm really confused about these, but I want to make this to help people do bulk OCR easily through a Intuitive web UI. Here's a image of code for the Job model for django that I made. I need to initiate tasks, control them, get logs as needed and display on website.
Gotcha thanks
@paper vigil you need to do this to your settings file in django
by adding the middleware t o your existing ones
MIDDLEWARE = [
# SecurityMiddleware must be listed before other middleware
'django.middleware.security.SecurityMiddleware',
# ...
]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
anyone's up
so i'm making a e-commerce store and i want to give user option to add thier own products if they r logged in (as a a user) so how know which user added a new product to shop
and if i use OneToOneField with user , so when user will add thier own product it show's profile of all the User's in the site (as i saw in django admin ) so for example my user is xyz but when i click on add product i can access all 5 user's option and the particular i choose will be rendered
umm very complex
guys i am trying to import the css file from static folder in flask but its not working. someone please help me
I have a problem with my DRF ListSerializers:
AssertionError at /api/v1/countydata
`child` is a required argument.
Here's how my serializer looks like
class CountySerializer(geo_serializers.GeoFeatureModelListSerializer):
index = serializers.IntegerField()
class Meta:
model = County
geo_field = "geometry"
fields = "__all__"
And Idgi. On other geo serializers it does it correctly but not this one for some reason
Try html href="static/index.css"
href = "{{url_for('static', filename='index.css')}}"
not sure if it's double or a single curly bracket
Hi
I'm trying to create plugin for Django CMS that having views function but unfortunately I don't know how can point my views function with plugin
I'm trying to call my views function with the help of plugin
But it not working
<@&787816728474288181>
Hello, please do not ping random role to ask for help
@finite ledge well you'll have to ask your question with some technical detail for us to be able to help
Is there any localstorage i can use in Django
I'm not using render(request,...)
User navigates to raw URL
But I need to retrieve data from previous view
so i'm making a e-commerce store and i want to give user option to add thier own products if they r logged in (as a a user) so how know which user added a new product to shop
and if i use OneToOneField with user , so when user will add thier own product it show's profile of all the User's in the site (as i saw in django admin ) so for example my user is xyz but when i click on add product i can access all 5 user's option and the particular i choose will be rendered
noone replied
@opaque rivet
@hardy laurel http requests are meant to be stateless, so they should contain all of the information required within the request without relying on any previous requests.
Data can be transferred as cookies, e.g.:
You can save the user's token in a cookie, then use that to retrieve account information.
You can also save formdata within the body of the request.
You can also include data within the query string of the URL.
"Local storage" is clientside only
Maybe query the number of users that exist after a certain date? This is a bit more complicated since you have to tell the database what you want - unless you use some outside service.
@dusk portal a OneToMany relationship is probably better... so one user can make multiple products
umm this time i have made whole project on my own
without any reference
i have to apply some stuff in this like
search bar with searches in whole models ( all models all types )
so like a date filter with a for loop, and use kind of like slice[i:i+30]
This in Django?
flask
Not sure what the query looks like in Flask, but basically just get all users, filtering for anything beyond the specific date.
ok ok
Hey @knotty musk!
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:
everytime i do "python manage.py runserver this comes up, and main.urls does have patterns btw, so what could be the issue?
this is django btw
help
pls
pls
help
ok
Hey @knotty musk!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
just the urls part
from django.urls import path
from . import views
urlpatters = [
path("", views.index, name="index"),
]
here
im new so keeping stuff simple lol
Are you following a tutorial?
yeah
welcome
guys do you have any idea why media queries using css doesn't apply ? is there any problem django rendering them
weird thing is i made it work just as i want and then just added an mt-4 class from bootstrap and now it doesn't render im talking specifically about the column-count: 1; css property, not being read correctly
any insight will be helpful
let me ask, are you applying column-count: 1; directly into a css file?
yes in static file with .css extension
can i ask what you expect this to do or change?
I have 3 columns with pictures in some fancy grid display for desktop and when it's for little screens like 480 i want to make it display only 1 column
i mean i have other css as well but i think this is what doesn't display
im not sure if its a cache problem, even though i have disabled it
you're using bootstrap to apply the grids i'm guessing?
yeah i have a template that is using the bootstrap but i think mainly it uses the custom css
idk how can i show you the css code in here ? if i put it in `` will it show it as a code
im new to this discord thingy ๐
bootsrap uses css grid and flexbox for their layouts. basically they have their own set of properties you can use to change how content is structured. column-count doesn't really affect that
what's the difference between WebRTC and Websockets? and why did discord choose webRTC? and when it is better to use webRTC for a chat app?
ooh yeah i didn't think of that haha
from django.conf import settings
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.urls import include, path
from django.urls.conf import re_path
admin.autodiscover()
urlpatterns = [
path("sitemap.xml", sitemap, {"sitemaps": {"cmspages": CMSSitemap}}),
re_path("meri/", include("merger.urls"))
]
urlpatterns += i18n_patterns(path("admin/", admin.site.urls), path("", include("cms.urls")))
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)```
This root URLs.py code
This is template render with the help of plugin
Does anyone know why i can only chat numbers and not letters anymore?```php
<?php
include "/connect/db.php";
session_start();
$text = $_POST['text'];
if(isset($_SESSION['username'])){
if (strlen($_POST['text'] == 0)){
//$_SESSION['error'] = "title is emtpy!";
echo 'Please enter text!';
die();
}
else{
$text_message = "<div class='msgln'><span class='chat-time'>".date("g:i A")."</span> <b class='user-name'>".$_SESSION['username']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
}
?>```
I am trying to learn CSS and HTML can anybody be of any help?
guys do you have any good resources for django signals, im trying to understand the flow mainly pre_save and post_save how do they work and so on
I can help out a bit, what do you want to know?
brohoof
anyway i am looking to learn the basics and later advance HTML and CSS for website building
currently i have figma templates and i have to export them
and i have 0 knowledge of HTML or CSS
and i have a 10 day deadline
a bit nuts
https://www.oreilly.com/library/view/head-first-html/9781449324469/
this could be of help
literally from zero... you would have to walk really fast though
what about it? ๐ I saw figma only from afar
I think you can export pictures out of it
and font styles
ok
and is there a diffrence in coding or learning material
or does the book cover it all
not clear question
elaborate
rephrase your question in a more meaningful one
Understood
@app.route("/db")
def webdb():
ip_address = request.remote_addr
would this give me their requesting IP address or do I have to write
def webdb(request):
second
thanks
If i were to understand and grasp the knowledge to which that materialized confinment of knowledge (a book) witholds will i face any difficulty exporting a figma (or should i say ligma
) webite template.
@inland oak
exporting from figma is a basic skill to navigate any program, it is not related to the book.
@broken mulch a cookie file is saved to your PC, Mac, phone or tablet. It stores the website's name, and also a unique ID that represents you as a user. That way, if you go back to that website again, the website knows you've already been there before.
@inland oak
oh
how am i to grasp said skill
Pretty sure figma gives you the css for what you've created, you just need to sort out the html then copy/paste
https://htmlcheatsheet.com/css/
This can help a bit
really? cool
It makes things much easier if it is so
Thanks @opaque rivet @split steeple @inland oak for your input, and assitance it is very much appreciated :))))))
just use computer from day to day life, it already increases this skill
Anyway, google "exporting from figma" or something like that to find some tutorial how to do that
ok thanks
it doesn't work
TypeError: home() missing 1 required positional argument: 'request'
not enough code provided to know.
you have somewhere second url with function def home perhaps
this is the start:
@app.route("/")
def home(request):
Iirc with flask request is accessible in the function due to the decorator, it's not required as a arg
but the IP address doesn't match
What's the issue again?
oh yeah
im trying to fetch request.remote_addr
request is not needed in function args
but it's the same every time
from flask import request
is used instead
@broken mulch google is your best friend
when an ip address reached their limit
ok
does anyone know if I can connect to my website DNS using flask
or do I have to use django
This is probably another moment where google is your best friend...
can someone help me get set up with flask? i installed it and made the starter code but "flask run" says could not locate a flask application
nvm could you just send your code
me?
Yes @untold hull
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, world!</p>"
then on the console "set FLASK_APP=hello.py" and "flask run"
but it won't run
says "could not locate Flask application" anyone know the fix?
how do I change from django.utils import timezone to my timezone? I've added my local timezone in the settings.py, but still it shows time in UTC. in Django
oww....
hey guys hows it going I was wondering if anyone has experience with flask-appbuilder and if I can pick their brain about it
for context I need to extend their security model to make a custom authentication function and I can't seem to find the right way to do it in the docs
Django: What's the proper way to hash imported passwords with Django-import-export? I'm trying to use make_password, but it says Invalid password format or unknown hashing algorithm.
I'm getting this error in Django.
Internal Server Error: /app/oauth2/login/redirect
Traceback (most recent call last):
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Internet\Desktop\Programming\Discord\exo_website\website\exo_dashboard\dashboard\home\views.py", line 188, in discord_login_redirect
return redirect("/app")
File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 126, in login
request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
AttributeError: 'QuerySet' object has no attribute '_meta'
[19/Jul/2021 14:20:18] "GET /app/oauth2/login/redirect?code=code HTTP/1.1" 500 79016
This is the code
def discord_login_redirect(request, *args, **kwargs):
code = request.GET.get("code")
exchange_user = exchange_code(code)
discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user)
login(request, discord_user_auth)
return redirect("/app")
I believe the error is originating from login(request, discord_user_auth). Does anyone know what this error means?
discord_user_auth is the user
ah sorry idk the Backends yet
I have a custom authentication backend so instead of request.user I have to use discord_user_auth
"could not locate Flask application" anyone know the fix? i tried FLASK_APP=hello and flask run
if you run it inside the folder that has the app.py file it should work
that's the only file in the folder
if its set up right you might be able to get away with python ./hello.py I guess
what's weird is i got it working a moment ago
restarted the ide and back to square one
does nothing
can you show what is in the file
anyone's up
Hi, hope I'm not disturbing but I'm trying to put some logo credits under some details and summaries tags to be used on github readme profile but for some reason the summary doesn't end up being the summary and then it gets linked to an a tag up top
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "<p>This is the homepage.</p>"
@bitter thunder
any django dev i mean
checking 1 sec
nope. Do you mind helping me though?
umm sure
thanks
This is my question
Right now the preview for my github readme looks like this
umm
but I want "icons sources" to be in the place of "details" as expected but it became a bullet point
<!--- A tag with the link --->
<a href="https://www.youtube.com/channel/UC" target="_blank"><img align="center" alt="Youtube" width="48px" src="https://img.icons8.com/color/48/000000/youtube-play.png" />
</p>
<details>
<summary>Icons sources</summary>
<ul>
<li><a href="https://icons8.com/icon/13441/python">Python icon by Icons8</a></li>
<li><a href="https://icons8.com/icon/20909/html-5">Html 5 icon by Icons8</a></li>
<li><a href="https://icons8.com/icon/21278/css3">CSS3 icon by Icons8</a></li>
<li><a href="https://icons8.com/icon/108784/javascript">JavaScript icon by Icons8</a></li>
<li><a href="https://icons8.com/icon/20906/git">Git icon by Icons8</a></li>
<li><a href="https://icons8.com/icon/9OGIyU8hrxW5/- visual-studio-code-2019">Visual Studio Code 2019 icon by Icons8</a></li>
<li><a href="https://upload.wikimedia.org/wikipedia/commons/4/4f/Icon-Vim.svg">Wikipedia</a></li>
<li><a href="https://icons8.com/icon/19318/youtube-play-button">YouTube Play Button icon by Icons8</a></li>
<li><a href="https://icons8.com/icon/63807/website">Website icon by Icons8</a></li>
</ul>
</details>
name?
But yeah right here, what happens is that Icon sources will take the link from the a tag for some dang reason
No idea why
just replace details with icon sources
drom all the places
simple
oh
Yeah I tried that
But then
it's no longer a toggle thing
it just becomes bullet points
So I need the detail I think
If I remove all the a tags though that links to my youtube channel, or other websites, then it works fine
But then I'll only be left with the sources ofc :/
<li><a href="https://icons8.com/icon/13441/python">Python icon by Icons8</a></li>
This creates a bullet point, and the anchor tag will redirect the user to the href link... isn't that expected behavior?
Yes you're right but as you can see in this image
toggle thing?
and what happens is that it will grab the most bottom a tag that contains a link
oh bro i need a help kind of tricky
?
This is the full preview rn
So rn, icon sources which is the summary
hmmm... I'm not really sure, is it possible to build your .md file solely with html?
will be linked to my youtube channel and if I remove the youtube icon + the youtube a tag then it'll be the website
the default for flask is app.py
I think so yeah
I thought it was only markdown
yeah i knew that, but the problem was vscode was using powershell rather than cmd, i figured it out when i tried it on cmd and it worked, i switched vscode's terminal to cmd and now it works, thanks
But it seems to support html
fair enough yeah
maybe get rid of the <details>/<summary> tags?
Oh but I kinda want to hide sources
like I added it so that if someone wants to use those icon
They can just toggle the button beside "details" and see the icons
rather than have it in plain sight
def register(request):
if request.method=='POST':
first_name=request.POST.get('first_name')
last_name=request.POST.get('last_name')
email=request.POST.get('email')
username=request.POST.get('username')
password1=request.POST.get('password1')
password2=request.POST.get('password2')
if password1==password2:
if User.objects.filter(username=username).exists() and User.objects.filter(email=email).exists():
print('Already taken')
new_user=User(first_name=first_name,last_name=last_name,email=email,username=username,password=password1)
new_user.save()
return HttpResponseRedirect('/')
return render(request,'users/register.html')``` this is my register which saves to the user model (register) so when i'm filling form from html so when i saw user which i created by html so it was saved but when i focussed on the difference if i add any user directly by django admin so it's login is working fine but the other which i render by html in that i noticed ```Invalid password format or unknown hashing algorithm.
Raw passwords are not stored, so there is no way to see this userโs password, but you can change the password using this form.
Personal info```
@opaque rivet haha whole para
it's saving to user db but while im doing login so it's not working but when i create user by django admin and then do login
it's workin
issh
my mind
explodes !
well, print what the password is and inspect its format
ohh
xyz456
<class 'str'>
print(password1)
print(type(password1))
hello, i'm having a issue in my django app:
``python
from django.contrib.auth import get_user_model
user = get_user_model()
user.objects.get(user="toto")
``
it throws this error : TypeError: all() missing 1 required positional argument: 'self'
when im doing from admin it's working
it shows
problem is in
def register(request):
if request.method=='POST':
first_name=request.POST.get('first_name')
last_name=request.POST.get('last_name')
email=request.POST.get('email')
username=request.POST.get('username')
password1=request.POST.get('password1')
print(password1)
print(type(password1))
password2=request.POST.get('password2')
if password1==password2:
if User.objects.filter(username=username).exists() and User.objects.filter(email=email).exists():
print('Already taken')
new_user=User(first_name=first_name,last_name=last_name,email=email,username=username,password=password1)
new_user.save()
return HttpResponseRedirect('/')
return render(request,'users/register.html')``` here
or html
have you googled your error
for backend web, should i go for nodejs instead of python?
You can use whichever you prefer
Both are great options
i heard python isn't great for employment regarding webdev
Not really
A bunch of really big companies use Netflix for their backends, such as Instagram and Netflix
do they use flask or django?
And I've heard that Python web dev jobs are rising, but it depends on your location
Instagram uses Django with a fork of CPython called Cinder (https://github.com/facebookincubator/cinder), dunno about Netflix
it probably is but it's still noticeably lower than its peers
hmm
But I doubt Netflix uses Flask
Hi, I'm trying to do something with django and ran into a problem ... I can't fire up my local server ...
https://pastebin.com/8VSXztZS
I do everything according to https://docs.djangoproject.com/en/3.2/intro/tutorial01/ and the nth time I check everything and I don't see an error anywhere ...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
In the end for programming jobs, companies look for people able to learn things. Yes specific positions will ask for specific stack, but I've often seen companies hiring people for their talent and willing to pay you to learn technologies (like a senior I know who was hired for a Kubernetes architect, but never did kubernetes but they know he could learn it and pay very well)
hey guys, working on django project,
in db(postgresql) i need to sync with api(), and im calling to 5000 objects in api, then adding to db.
So, what i need, compare last item in db (row in special column) with parsed items in json, OR
maybe other ways to do it by built-in methods.
i tried this:
query = requests.get(f'https://bcschain.info/api/recent-blocks?count=3')
checkedQuery = compareItems(query.json())
for i in range(len(checkedQuery)):
objects = Block.objects.create(height=checkedQuery[i]['height'],
hash=checkedQuery[i]['hash'],
timestamp=checkedQuery[i]['timestamp'],
miner=checkedQuery[i]['miner'],
transactioncount=checkedQuery[i]['transactionCount'],
interval=checkedQuery[i]['interval'],
size=checkedQuery[i]['size'],
reward=checkedQuery[i]['reward'])
def compareItems(obj):
try:
last = str(Block.objects.latest('height'))
for i in obj:
if i['height'] == last:
return obj[i:]
return obj
except:
return obj```
but `last` is `Block object (333413)` and when comparing with `i['height']` `str(333413)` it shows FALSE.
what contains `query`
```[{'hash': 'a0642ba14658fc50a093450b2f149a1d589cd3df76414b5661fd8cb08f6727d9', 'height': 333420, 'timestamp': 1626727600, 'interval': 80, 'size': 2283, 'transactionCoun
t': 2, 'miner': 'BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az', 'reward': '50000000000'}]```
can you paste the urlpatterns mentioned in the error?
๐ error was here: I had to change from urlPatterns to urlpatterns ๐
๐
anyone a big brain flask-appbuilder user?
any1 have any tips on making a skill tree in html/css/js?
Im thinking of just making an image of arrows and using divs for the tree leaves
Does anybody know a website, or source where i can learn more about HTML and CSS, website building, figma exportation.
i have little to no experience in HTML or CSS, and i am willing to learn
currently i have a figma template to which i am to format it into an actual website
can anybody help me?
codecademy for html / css, you learn by doing
yeah i just broke another roadblock i depend on bootstrap for basically 90% of everything though
i recommend just using react or some npm way to install the stuff
so im working with quart and discord ipc to make a dashboard for my bot
im getting this weird error where it says the key is missing but the key is clearly there
Im on the part where im getting the guilds
This is my bot code:
@ipc.server.route()
async def get_guild(data):
guild = bot.get_guild(data.guild_id)
if guild is None: return None
guild_data = {
"name": guild.name,
"id": guild.id,
"prefix" : "?"
}
return guild_data
This is my webserver code:
@app.route("/dashboard/<int:guild_id>")
async def dashboard_server(guild_id):
if not await discord.authorized:
return redirect(url_for("login"))
guild_data = await ipc_client.request("get_guild", guild_id=guild_id)
if guild_data is None:
return redirect(f'https://discord.com/oauth2/authorize?&client_id={app.config["DISCORD_CLIENT_ID"]}&scope=bot&permissions=8&guild_id={guild_id}&response_type=code&redirect_uri={app.config["DISCORD_REDIRECT_URI"]}')
return guild_data["name"]```
This is my error:
``` File "C:\Users\jacob\AppData\Local\Programs\Python\Python39\lib\site-packages\quart\app.py", line 1933, in dispatch_request
return await handler(**request_.view_args)
File "c:\Users\jacob\OneDrive\Documents\GitHub\scpinfosite\app.py", line 50, in dashboard_server
return guild_data["name"]
KeyError: 'name'```
I think the dict is returning as null
If I delete a certain user or an object by using flask admin, how would I be able to add that action into the daily log(This action will be written into a .txt file)?
Like if I deleted someone with flask admin, and hoping to see this action like "user" got deleted by the admin message
I have this file but the JS wont work
<!DOCTYPE html>
<html lang="en">
<head>
<title>Haha, STOOPID!</title>
</head>
<body onmouseover="openWin()">
<h1> Enable POP UPS </h1>
<p> ^</p>
<p> ^</p>
<p> ^</p>
</body>
<style>
body {
background-color: black;
color: red;
}
</style>
<script>
function openWin() {
myTab=tab.open("","","width=800,height=300");
myWindow.document.write("<p>You are an idiot!'</p>");
}
</script>
</html>
```Did I do something wrong?
OK\
guys im new to flask and im trying to run my flask website but its not showing anything
@errant oyster
thats all that happens
lol
idk huhu

u need check step by step again @@
i know a little web
because i lean data analyst
hi.. any idea build calendar time slot.. i plan to build booking appointment.
any1 wanna work on a project that can make us money?
(context django) i have 2 fields price and discount_price, how can i filter discount_price and if it is null then use price value for filtering?
for example, to filter with discount_price__lte but if discount_price is null then filter with price__lte?
hi i am new to flask and python
i have written this code form my flask server
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "i am on"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
and i want to link a html file to this server
but also keeping the discordbot connected to it
but i cant find a way to do so
if anyone can help it will be so nice
<?php
while($row = mysql_fetch_array($query)){
echo '
<tr class="entry">
<tr>
<td style="width: 60px;" class="text-center">'.$row['id'].'</td>
<td style="width: 270px;"><a style="color: red; font-weight: bold;" href="/user" target="_blank">'.$row['username'].'</a></td>
<td style="width: 90px;" class="text-center">0</td>
<td class="text-center">0</td>
<td class="text-center" title="Not Done">Today</td>
</tr>
';
}
?>
``` does anyone know why this isnt showing anything
@native tide you can try to do it like this:
<?php
while($row = mysql_fetch_array($query)) { ?>
<tr class="entry">
<tr>
<td style="width: 60px;" class="text-center">'.$row['id'].'</td>
<td style="width: 270px;"><a style="color: red; font-weight: bold;" href="/user" target="_blank">'.$row['username'].'</a></td>
<td style="width: 90px;" class="text-center">0</td>
<td class="text-center">0</td>
<td class="text-center" title="Not Done">Today</td>
</tr>
<?php } ?>
this does the same thing
check the page source if uyou have any weird stuff maybe?
errors won't show in the console, that's only for javascript errors
Can you check the page source on the place where you'd expect the php stuff?
<table class="table table-striped table-hover">
<thead>
<h6>All Users</h6>
<th class="text-center">ID</th>
<th>Username</th>
<th class="text-center">Pastes</th>
<th class="text-center">Comments</th>
<th class="text-center">Joined</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div align="center">
<p>Showing 100 (of 14 total) users</p>
<br>
<a href="#">Back to top</a>
<br><br>```
tbody is where the php is
what will happen if you will remove "
A guide for how to ask good questions in our community.
Hi, I am learning Django. And I create my own model for users(based on models.Model), I have password field, I encrypt it. And I tried to use check_password(). Idk why, but it always returns False. How to fix it? If you understand Russian language, here is StackOverFlow : https://ru.stackoverflow.com/questions/1306410/ะะต-ัะฐะฑะพัะฐะตั-django-contrib-auth-hashers-check-password-ะฒัะตะณะดะฐ-ะฒะพะทะฒัะฐัะฐะตั-false.
views.py :
error = ''
objec = users.objects.all()
for i in objec:
if request.COOKIES.get('profile_session_id') == i.session_id:
return redirect('profile')
if request.method == "POST":
form = LogInForm(request.POST)
post = request.POST
error = 'ะคะพัะผะฐ ะทะฐะฟะพะปะฝะตะฝะฐ ะฝะต ะฒะตัะฝะพ'
if form.is_valid():
error = 'ะะตะฒะตัะฝัะน ะปะพะณะธะฝ ะธะปะธ ะฟะฐัะพะปั'
is_session = True
while is_session:
session = random.randint(1000000000000000, 10000000000000000)
is_session = False
for i in objec:
if session == i.session_id:
is_session = True
response = redirect('profile')
user = None
if '@' in post['login']:
for i in objec:
if i.email == post['login']:
user = i
else:
for i in objec:
if i.username == post['login']:
user = i
print(check_password(post['password'], user.password), post['password'])
print(user.password)
if user != None and check_password(post['password'], user.password):
user.session_id = session
user.save()
response.set_cookie('profile_session_id', session, secure=True, max_age=31536000)
return response
else:
return render(request, 'main/login.html', {'form' : form, "error" : error})
form = LogInForm()
return render(request, 'main/login.html', {'form' : form, "error" : error})```
Form:
class LogInForm(Form):
login = CharField(widget=TextInput(attrs={
'placeholder' : "Email ะธะปะธ ะปะพะณะธะฝ",
"class" : "form_elem textinput",
'required' : True
}))
password = CharField(widget=PasswordInput(attrs={
'placeholder' : "ะะฐัะพะปั",
"class" : "form_elem textinput",
'required' : True
}))
Model:
class users(models.Model):
username = models.CharField('ะะผั', max_length=250)
email = models.EmailField('Email')
discord = models.CharField('ะะธัะบะพัะด', max_length=250)
session_id = models.CharField('ะกะตัะธั', max_length=250)
password = models.CharField('ะะฐัะพะปั', max_length=250)
def __str__(self):
return self.username
class Meta:
verbose_name = 'ะะพะปัะทะพะฒะฐัะตะปั'
verbose_name_plural = 'ะะพะปัะทะพะฒะฐัะตะปะธ'
Registration :https://pastebin.com/VtwBrU2V
PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', )
Thanks!
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
ะฏ ัะฐะฑะพัะฐั ั ะฑะฐะทะพะน ะดะฐะฝะฝัั
SQLite. ะ ัะพั
ัะฐะฝัั ะฒ ะฝะตั ะฟะฐัะพะปั ัะตัะตะท make_password(). ะ ะบะพะณะดะฐ ั ะฟะธัะฐะป ะฒั
ะพะด ะฒ ะฐะบะบะฐัะฝั, ะผะฝะต ะฟะพะฝะฐะดะพะฑะธะปะพัั ะฟัะพะฒะตัะธัั ะฟะฐัะพะปั ะดะปั ััะพ ั ะธัะฟะพะปัะทะพะฒะฐะป ััะฝะบัะธั check_password.
ะฏ
i think you should use the form.cleaned_data['password'] instead of post['password']
#help-burrito please
hi lads!!
for the post request i couldnt find the form-data in the chrome developer tools . you guys got any idea??
im stuck in this for a long time
#help-cake pls
Looks like you have the wrong credentials setup for database access.
if i work it on xampp its not get an error, but after i upload it to a hosting its gonna like that
Don't have any experience working with php, so I won't be any help
but thank you somuch you want to answer me
Hey guys
how do you take input from a html form and save the data in mysql database using django?
Please do the Django tutorial, this is a part of. The basics
can u please let me know real quick i just started django two days ago
No, it's too long to let you know "real quick"
anyone can help this
like a calendar in booking form?
yup, i try to setup seem like this
I'm having a hard time to come up with a catch-all function for my containerized Flask server. I've got React in another container. When I have React and server running on the same system I can go with:
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path)
return send_from_directory(app.static_folder, "index.html")
but ^ this is useless if my front-end is running in separate container. The app is docker-compose-managed.
Any suggestions ?
I used a calendar in booking form once I'll dm you the code hold up
Hi
how could i center text in html?
<p align="center" >Paragraph_1 Explained</p >
like this?
or with <center><p>Paragraph_1 Explained</p ><center>
this way
Okay ty
i think "<center>" tag was removed from html in an update
Ah okay
why would you need a catch all if you're not serving the react frontend from flask?
Because of Cypress automated testing. Cypress asserts "/" fine but throws 404 on all other routes. Cypress core developer told me that the catch-all function needs to be added.
were you using ajax or html/django forms?
def search(request):
if request.method=='POST':
searched=request.POST.get('searched')
x1=Product.objects.filter(title__contains=searched)
return render(request,'index/search.html',{'x1':x1,'searched':searched})``` this works fine it works when it contains anything but i want to add more filters
like
startswith
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="skills.html">Skills</a></li>
</ul>
</nav>
Could someone please help?
When i go normally to the main link, i dont have /filename.html
any1`?
bruh
Anyone had success deploying a React and Django app to production?
I'm just looking for some advice in what things to look out for when doing so, how to structure the project, etc.
Html django forms mate
Seems that some people use django as the root where others prefer React as the root.
In your form did you include the {% csrf_token %} tag?
help!
@dusk portal You can chain filters.
objects.filter(user=user).filter(email=email).order_by('created_date') etc.
@dense slate I use django as root with the react app in a dir called frontend. Django apps are microservices
In form put {% csrf_token %}.
And for the frontend I use next.js to be able to do SSR
@opaque rivet Why did you decide to have Django as the root instead of React? Since React has a build process, it feels like that should take precendence.
I have an app with django as a subfolder of Next.js.
Does it really matter in the end?
@dense slate Don't think it matters. In my mind, the django app takes precendence because it has to render a page, so having that page in a frontend folder just makes sense...
Probably the least of your worries though
How do I make toggle between weeks and years in django urls. When no more weeks in a year, switch to another year ect.
my url patterns looks like this: path('<int:year>/<int:week_num>/', Index, name="index"),.
I can't design frontend I'm so unimaginative
Has anyone here succeeded in getting a pymc3 installation to work recently? Tearing my hair out here
I tried adding 1 but I need to add some logic to it.
Hmm, interesting. Since the browser hits the front end first, and the front end just need information from teh backend, that was my reasoning.
Are you a fullstack?
Yea, I'm configuring the entire app.
Cool!
I do serverside and backend, also html and css, but never really learned react or any frontend framework
me?
I use adobe xd and figma
gimp or figma if I am on linux
I like adobe xd over figma idk why
If you are not web designer, it`s ok.
Yea, I love the whole process.
Plus if you want to make your own software, you need to do it all.
I do prefer the front-end though.
@opaque rivet Design in what sense?
How to unite different queries results from pandas?
Totally agree. I also enjoy doing my own designs and also the backend.
I have not ever needed to use react, but what's the benefits of using react as frontend?
I think mainly it is for separation of development, making it easier to have a front-end team and backend team.
But I use Next.js and some other libraries for even more benefit, like SEO, caching, etc.
Really focusing on site speed.
Can you do some extra css / element tricks with react that can't be done without?
I don't know about tricks, but it's very easy to make a component and then reuse it everywhere.
That really helps.
hi does some know about trio python ?
@dense slate design in the sense of UX and the visuals of the site
I prefer the technical side
dude
it's displaying them alphabetically,it doesn't even affect anything
idk
isn't this something you are defining yourself?
you don't need to specify it if it's a primary key, it will auto increment when you insert the data
why is my datepicker results not saving into the sql db?
i set it to DateTime column in models
@opaque rivet I'm just creating components and styling them manually to reduce any bloat in the material side of things.
It really doesn't take that much time and I feel like I have a lot more control from the beginning this way.
Hmm, mainly color schemes I struggle with. I'll send some designs later maybe
There are some good sites that basically come up with schemes for you.
Like combinations of colors that go well together.
e.g. https://coolors.co/
Im new at web dev so does anybody recommend a good course that I can use to get started?
Learn Flask first even whether you wanna use Flask or Django later cos it'll help you understand how web development works
Flask mega-tutorial (book) by Miguel Grinberg is a good starting resource. Make sure you're familiar with the basics of python and some html before starting it
What are you learning in Flask that you don't get starting with Django?
@jovial cloud
what is the best db system for a graphQL api (graphene) based on your experience?
Nothing. However, for a beginner the learning curve for flask is easier. And it helps to not get overwhelmed with information when one is just starting out
yea
i was doing django before but ill do flask instead
@violet briar I think that's more a question about what kind of DB you want/need for your project. I don't think it matters much which one you choose from a graphene perspective.
ah, okay, was just wondering which one handles expensive queries better
One vote for VS Code here.
Hello everyone, today i have switched from webstorm [ a jetbrains application ] to visual studio code, i am a web developer and am need of your assitsance. What extensions should i get, any suggestions?
for html and css
@app.route("/login-admin")
def login_admin():
auth = request.authorization
admin1 = db.session.query(Admin.password)
if auth and auth.password == admin1:
token = jwt.encode({'user' : 'admin'}, app.config['SECRET_KEY'])
toknen = jsonify({'token' : token.decode('UTF-8')})
return redirect(url_for('add_doctor', token=token))
return make_response('Invalid!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})```
I'm trying to use the admin password to login to jwt auth, since, I wanted the admin can change their password when ever they want in frontend, however, after running the code, when I submit the input, it redirect me back to the same page, like it just refreshed it. So is there any where i did wrong? ๐
What's the form look like on the frontend?
its like a littly pop-up window that vallow me to enter username and password
i don't know how install it

but im still not sure why it isnt working
no java script involved
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.args.get('token')
if not token:
return jsonify({'message' : 'Token is missing!'}), 403
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
except:
return jsonify({'message' : 'Token is invalid!'}), 403
return f(*args, **kwargs)
return decorated
this is all the code for the jwt auth
I dont have a frontend code for this
I inputed the link address and this is what came up to me
so the only front end is for the admin model which transfer its data from a flask form than to route.py and too database
"live server" i think it was called, also activate auto save, "prettier" (for formatting the code but its just visual stuff and personal preference); also learn the shortcuts like div.somename will make div tag with class='somename' or ul > li * 3 will make ul tag with 3 li inside it
oh
does anyone know how to do somehting like this
with
<select>
<option> aaa bb c </option>
</select>
aka have "subsections" of each option element
use column-count in css
would the column-count property go in select or option? and how would i use it?
right, i saw that you wrote
<option> aaa bb c </option>
so if it's all on one line column-count will devide the element and spread the content into even columns, but that might not be what you want so you can instead use flexbox or grid
i'm not familiar with grid but i'll show you an idea of how you can achieve it with flexbox
actually, option wont work for this
that's not how it works
that will only produce a drop down list
define another option and you'll see what i mean
let me check something
Hello so I did a post request using js and the post works just fine
function deleteApplication(application) {
fetch("/deleteapp", {
method: "POST",
body: JSON.stringify(application)
}).then(res => {
console.log("Request complete! response:", res, application);
});
}```
but I am struggling to get it on the python side I am trying to get rid of the b'' surrounding it when printing
```py
@app.route("/deleteapp", methods = ['POST'])
async def deleteapp():
text = await request.get_data()
print(text)
return text```
Console: `b'"TEST"'`
I am using quart for the web development.
No errors I just need to get rid of the b''
what do I need to do?
so i guess it is possible, let me show you with flexbo
so you'll have a structure like this:
<option>
<div class="options">
<span>a</span>
<span>b</span>
<span>c</span>
</div>
</option>
then in your css
.options {
display: flex;
flex-direction: row:
justify-content: space-between;
}
iirc you can't put extra tags in <opion> tags
i tested it and the extra tags worked
hmm let me test
<style>
.options {
display: flex;
flex-direction: row:
justify-content: space-between;
}
</style>
<select multiple="" size="20" style="width: 300px">
<option>
<div class="options">
<span>a</span>
<span>b</span>
<span>c</span>
</div>
</option>
</select>```
when i copy/paste this into the browser i get
<html><head><style>
.options {
display: flex;
flex-direction: row:
justify-content: space-between;
}
</style>
</head><body><select multiple="" size="20" style="width: 300px">
<option>
a
b
c
</option>
</select>
</body></html>```
completely removing the inner tags :I
yh rip
to do it that way
well thanks for helping
anyone hiring
For what?
Hello
<script>
function myFunction(id) {
if (document.contains(document.getElementById("newForm"))) {
document.getElementById("newForm").remove();
}
var d1 = document.getElementById(id);
d1.insertAdjacentHTML('afterend',
'<form id="newForm" action="/blog/add_reply/'+ id +'/{{d_blog.id}}/" method="POST">\
{% csrf_token %}\
<div class="d-flex flex-row add-comment-section mt-4 mb-4">\
{% if request.user.profile.profile_photo %}\
<img class="img-fluid img-responsive rounded-circle mr-2" src="/media/{{request.user.profile.profile_photo}}" width="38">\
{% endif %}\
{{form.media}}\
{{form}}\
<button class="btn btn-primary" type="submit">Comment</button>\
</div>\
</form>\
');
//document.querySelector('#id_parentt [value="' + id + '"]').selected = true;
}
</script>
form variable here doesn't get loaded, what can i do?
fullstack engineer. django/react/docker
Ah I see, well for my freelance work, I already have enough support for backend but could do with some Frontend/JS persons.
sure, I'll DM you
But we don't use django.
Hey guys, I already know basic python, and now I want to get into Backend programming. Can I use python with postgreSQL?
yes
ok so new question
let's say i have a <div style="overflow:auto;width:50px;height:50px"></div>
how would i make it so
when adding a new element to this div (with javascript)
the scroll will 'sticky' to the bottom
unless it's scrolled
ok nvm i figured out how with javascript
i just checked the scroll top and div height with the total scrollheight with js
!e
print("Hello")
@stiff briar :white_check_mark: Your eval job has completed with return code 0.
Hello
@lavish prism hello
Can some help me? At the end of this script, {{form}} variable not loading
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
anyone's up
Hi
how can i set a gradient background?
<style>
.my_bg {
height: 100%;
background-color: blue; /* For browsers that do not support gradients */
background-image: linear-gradient(45deg, #FFFFFF, rgb(0, 157, 255));
}
</style>
I tried this
im not sure what to do to show it as the background
<div class="my_bg"></div>
hey guys, was reading a blog and came across this:
A queryset in Django represents a number of rows in the database, optionally filtered by a query. For example, the following code represents all people in the database whose first name is โDaveโ:
person_set = Person.objects.filter(first_name="Dave")
The above code doesnโt run any database queries. You can can take the person_set and apply additional filters, or pass it to a function, and nothing will be sent to the database.
How does that code not run any database queries? Doesn't this run something like this in SQL under the hood?
SELECT * FROM Person
WHERE first_name = 'Dave';
yes, you can essentially even see the SQL code under the hood
person_set = Person.objects.filter(first_name="Dave")
print(str(person_set.query))
oh cool - that will come in handy. But then doesn't that contradict the statement "The above code doesnโt run any database queries"?
I'm unsure what's meant by that.
well... I think they mean that...
when you just write
Person.objects.filter(first_name="Dave") it is not running query immediately
because it allows you to chain your ORM code in this way
Person.objects.filter(first_name="Dave").filter(second_name="Lalala").filter(third_param="lalala")
only when the phrase is finished
then it runs
combining all functions you requested in chain into one SQL query
oh... I misread, well then it does run a database query once its called
well yeah
is someone here good at django? i need help
. it does run a database query once its evaluated
A guide for how to ask good questions in our community.
thanks. got it now
@opaque rivet hey
def search(request):
if request.method=='POST':
searched=request.POST.get('searched')
x1=Product.objects.filter(title__icontains=searched)
if not x1:
x2=User.objects.get(username__icontains=searched)
return render(request,'index/search.html',{'searched':searched,'x1':x1,'x2':x2})```
{% if searched %}
<center>
<p>You searched {{searched}}..</p>
</center>
{% else %}
<p> U didn't searched anything..</p>
{% endif %}```
{% if x1 %}
#all the stuff
{% else %}
<p> No result found for {{searched}}</p>
{% endif %}```
{% if x2 %}
<strong>Users</strong>
<ul>
<li>{{x2.username}}</li>
</ul>
{% endif %}```
so here i want that it should search by title and if not any post come by that title and if any User is with that related username (like a restuarent have named as pizza hut so when i write pizza , so item pizza also comes + the restuarent (username)
so i want to filter that
so my user function is working fine
by 1 my product is SPACE
works fine!!!
so i have item called space and i wanted to render it it comes
when i enter xyz (with is not in both user and title)
So what's your question.
Btw I would probably instead pass each variable individually to the function and just use them as you need them. Something like:
def search(request, **kwargs):
if request.method=='POST':
if kwargs['title']:
result=Product.objects.filter(title__icontains=title)
else if kwargs['username']:
result=Product.objects.filter(username__icontains=username)
return render(request,'index/search.html',{'result': result})
there's probably an even more efficient way
or else you'll have a separate context returned for each condition which can get messy quickly. @dusk portal
help
Hello guys. I badly need help, I need to do a webscraping. To give you details, They gave me a zip folder to extract a file, inside that extracted file was 3 folders with python codes, they told me to use beautifulsoup and pip. so after extracting it, I dont know the next thing to do. here is the screenshot. the notepad was the extracted file with codes then the other side is a jupyter notebook which I prefer to use. Unfortunately, it is not working
From the error, you need run_Geofence in your environment.
I don't know if it's a library or just another file.
What's get_services look like?
Just share it here. I'm not sure what your question was.
anyone good with html / javascript
Some of us are, if you ask your question, we can help
i hope i can ask questions here about html/css because on servers dedicated to the topic, people werent very helpful,
soo i want to create a vertical navigation bar using a google font (i dont yet know if google font is relevant or not) and the list items do not have the padding ive set and i also couldnt adjust the font size.
here is my css and html:
.verticalnav{
background-color: darkblue;
font-family: 'Ubuntu', sans-serif;
font-size: 15;
text-align: right;
}
div.verticalnav{
position: fixed;
top: 0;
left: 0;
width: 30vw;
height: 100%;
padding: 5%;
margin: 0;
}
.verticalnav ul{
list-style-type: none;
margin: 0;
padding: 0;
}
.verticalnav li{
display: block;
float: right;
padding: 10 0;
margin: 0;
width: 25vw;
}
.verticalnav li a{
color: white;
text-decoration: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Try xWater</title>
<link rel="stylesheet" href="waterlanding.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@500&display=swap" rel="stylesheet">
<meta charset="UTF-8">
<meta name="description" content="A demo landing page to promote a glass of water">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class=verticalnav>
<ul>
<li><a href="#AbW">About xWater</a></li>
<li><a href="#WhyW">Why xWater?</a></li>
<li><a href="#JTM">Join The Millions</a></li>
</ul>
</div>
</body>
</html>
pls someone help me find a solution
ohh
anyone's up
@login_required
def order(request):
if request.method=='POST':
name=request.POST.get('name')
email=request.POST.get('email')
author=request.user
phone_no=request.POST.get('phone_no')
address=request.POST.get('address')
zipcode=request.POST.get('zipcode')
entry=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
entry.save()
return render(request,'index/order.html')```
class Order(models.Model):
name=models.CharField(max_length=50)
email=models.EmailField()
author=models.OneToOneField(User,on_delete=models.CASCADE)
phone_no=models.IntegerField(default=0)
address=models.CharField(max_length=100)
zipcode=models.IntegerField(default=0)
def __str__(self):
return self.name``` am i going correct?
how can i render that user on html umm
Hi, can you tell me if it is ok the way I did it?https://github.com/SoundB1/ToDo-Django
<div class=verticalnav> the classname has to be in quotation marks
looks good to me...
if you want to have a property or something from the view order you need to put that in a context = {'name':variable_you_want} and pass it as a third argument to the render function; thus way you can access that variable_you_want with the DTL syntax like {{name}} in the html template
im not sure if thats what you are looking for but, at first look that is what is missing in your order view
also:
name=request.POST.get('name')
email=request.POST.get('email')
author=request.user
phone_no=request.POST.get('phone_no')
address=request.POST.get('address')
zipcode=request.POST.get('zipcode')
entry=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
all of this can be simplified into
entry=Order(**request.POST)
@dusk portal
Similar! JS's spread operator works for almost all iterable objects. Python however has two unpacking keywords: * and **. The latter is for dict whereas the former is for non-dict iterable of objects (e.g. lists, sets).
https://realpython.com/python-kwargs-and-args/
Nice thanks!
so.....i am working on porting my desktop GUI apps over to web apps. right now i am just building my design but am starting to look at frameworks. I am looking at Django and flask. any others i should look at?
background: I have done some flask work but it always seems unintuitive to have it served in a production level. I have mainly written scripts and desktop gui apps in python, but, due to some circumstances (thanks COVID), so many remote working people has caused my pyinstaller'd apps to take WAY too long to open (30+ minutes). I am also working on consolidating m apps so you only have to go to one site to get to all of my apps.
Queston: What framework would you recommend?
I would recommend Django 
It may be hard at first but it will become easier as you use it
What do you mean?
It returns the logged in user who is making the request
git config --global user.name "Emma Paris" $ git config --global user.email "eparis@atlassian.com"
how can I generate html forms from the admin panel? I want to be able to add custom fields and things like that.
look at Pyramid https://trypyramid.com
Pyramid is a lightweight Python web framework aimed at taking small web apps into big web apps. This site provides an easy entry point into Pyramid.
hey everyone i'm new to django and i'm trying to wrap my head around the apps business
i get that each app is sort of meant to be a delegate for one business domain or context
but i'm not sure i understand how it's meant to be used in practice
because, as far as i googled, you can't start django and have multiple apps running simultaneously
so i'm very confused how you're supposed to manage this
You can, you need to use gunicorn and preferably for me nginx for the reverse proxy to Django, then you can specify multiple domains that point to different apps in nginx
i was given a small spec of a project with two apps and they want me to run each app as its own microservice, each on a particular port. initially i just worked on each app individually and made sure they work, now i'm struggling to find how i can run them both since one app's model contains a foreign key for the other app's model
ok this helps, now i have a starting point to work with
thanks
Hey, im having problem with the Static folder. i always get errros like "Not found" or "HTTP 404 "
do you load static in your html
and have you put the STATICFILES_DIRS = ['BASE_DIR / 'static'] in your settings
also you need to load it with the {% load static %} in your html template and in the <link> tag the href should look like this {% static %}
and the url to the file you want to load from the static folder
i wrote this by memory so there could be mistakes in the variable names, so check it in the django doc to be sure
How do I build a button that on click sends data to my Postgres database? This is after the page has received a POST Form with a url that is used to scrape a certain website
I would rather not use a second (hidden) form or ajax/jquery for this, as these seem a bit hacky approaches
I wrote this question more extensively in #help-coconut but the channel was closed before someone could answer my question
You can catch the click event on the button, and then execute the post request inside it
but this would make for a second post request on the same page
and I already have an if request == POST section in this particular view for the scraping part
How exactly do you plan to save data to postgres?
Do exactly that inside the function
but would this be a js function?
Ok
Since you want non browser behavior
So then I have to connect to my database from both Python and JavaScript in this project
That sounds like a bad idea
That's what I thought
If your backend already connects to the database, send the request there
And the backend can do the rest
Create a new function to handle this
I meant
Just create a view
An api view
And send a request using window.fetch in the Javascript part
Hm
Ok that sounds like a new approach, I'll take a look into that
Thank you very much!
heard of that one too. you have any experience with it? does it come packaged with a production ready way to serve the site?
@login_required
def order(request):
if request.method=='POST':
name=request.POST.get('name')
email=request.POST.get('email')
author=request.user
phone_no=request.POST.get('phone_no')
address=request.POST.get('address')
zipcode=request.POST.get('zipcode')
entry=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
if Order.objects.filter(email=email).exists():
error_message='Email already exists'
return render(request,'index/order.html',{'error_message':error_message})
else:
entry.save()
return render(request,'users/order_history.html')
return render(request,'index/order.html')```
its not showing any error
but it's not saving info to db
@opaque rivet umm