#web-development
2 messages ยท Page 121 of 1
how to check if a value exist ?
def put(self, request, format=None):
print("DATA ",request.data)
instance = Car.objects.get(id=request.data["id"])
new_color = []
if (request.data.pop('new_color')):
new_color = request.data["new_color"]
Error:
File "D:\Dev\Django\template\default\views.py", line 36, in put
if (request.data.pop('new_color')):
KeyError: 'new_color'
hi i am new to django and was just wondering how i could rename this object
should I move to django, or stay at flask?
You need to add a __str__() method to your model. It should return whatever you want it to say instead.
I would recommend learning both.
Django works perfect for most of my web dev projects since it comes pre-built with a lot of things I need. But sometimes that is overkill.
is it possible to use Array data types with Flask-SQLAlchemy?
are you supposed to test view functions if it's static content that is being served
Hi ALl
Can you please take look at this question,
With Django am unable to lazy loaded module
Django
Im trying to play audio in my template but it doesn't load the file properly.
I've added a FileField, defined medai_root and url and successfully uploaded a mp3 file that got saved in the specified directory.
Now im trying to reference it like this in the template but it doesn't find the file even though it does look in the correct directory.
page.html
<audio src="{{ story.upload.url }}"></audio>
JS Console:
localhost/:22 GET http://localhost:8000/media/audio/Testmusic.mp3 404 (Not Found)
Feel free to @me :)
jinja2 or brython ,which one do you recommend?
I use flask and I would like to link it to brython to make my site interactive (adding one or more pop-up windows) is it possible thanks
@trail vapor jinja is a template engine and brython is just an api to convert python code to javascript, those are 2 different things
if you want the site to be interactive, i think javascript is enough
what HTTP response code should i use for a API endpoint that requires a auth token, but no token has been generated yet?
would the normal 403 work fine, or is there something that would be more specific?
jijinja2 serves me at the back but I would like with brython create pop_up windows for all which alert message such successful authentication or other
I misspoke
Does anyone like using Django with React? What stack do you use? Also... do you use Next.JS?
Is creating a new app in django for authentication the right way to do it ?
I mean the signup and login views and the profile view etc
avoid using the default auth user models and views @near bison
Why? @nova nacelle
I might not use the default user views. but why not the default User Model ? @nova nacelle
first thing it is not practical to make changes to them, and like if u want the user to log in with the email address, or u wanna change the max length of username and all...
i faced such things and decided to create a custom user model for my project
also i can have it anyway i want
create ur own views, it helps u learn a lot.
first thing it is not practical to make changes to them, and like if u want the user to log in with the email address, or u wanna change the max length of username and all...
i faced such things and decided to create a custom user model for my project
@nova nacelle if i make the model myself , will i have to write code to manage sessions , authorisations, permissions etc?
Isn't there a way to customise the default user model?
!accept
it disturbs the whole system
Hello , I am coming from a java-springboot rest api background, im trying to set up APIs using flask, how does the whole models and dtos work in python
how should i structure my application ?
@near bison I like to not touch the User model directly but if there is extra information I want for the user I will sometimes tack on another model with a onetoone field
tag me if u can help me with css
not a specific questino but more generic: What are some standard ways / checkboxes to tick for API logging? I'm not entirely sure that I'm properly capturing all the possible errors that could happen when someone hits my API and I would like to log them in the server.
An example: If I have a basic GET API which returns an Object, I do basic checking for whether the object exists or doesn't, then I send back an appropriate response. But I want to be able to
- Record that call and the response given somewhere, perhaps a database or logging module (database is probably better for obvious reasons)
- Catch other exceptions out of the scobe of object retrieval, for example bad headers or server errors or something like that
I feel a bit out of my depth in understanding all the things I need to track to make sure I'm properly handling all of the possible ways an API can get messed up
How do i add a field to User Model ? Or should i inherit from it and make a new model ?
how to save form data when user leave page?
like if i close browser by mistake while filling form
so i want old data that i fill in the form
yeah, what is it?
I keep getting SMTP errors, and I'm clueless what should I do to debug
How do i make a new one ? @nova nacelle
why did my app sent the raw html instead of the styled page on email?
which error are you getting
I tried to hide the password and username for version control, when I directly put them on settings.py it worked
but it didn't in .env
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
``` this is my `settings.py`
export EMAIL_HOST_USER = xxxxx@xxxx.xxx
export EMAIL_HOST_PASSWORD = xxxxxxxx``` this is .env
am I not doing right? @full sedge
wdym?
@full sedge btw, that sent the confirmation email but it sent the raw html message lol
why did that happen?
I am trying to learn how to use the django_rest_framwork and react. But currently, I am stuck at the CSRFTOKEN.
Currently, I have a button which get which trigger a fetch POST, but everytime i triggered it I get 403 forbidden. Does anyone know how to fix this?
handleDocument = () => {
axios(
{
method: 'post',
url: url,
data: {
"test": "test"
},
}
).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log(error)
});
<button className="buttons" onClick={this.handleDocument}>something</div>
In My Python Flask App I want To Make Some Custom Stuff In HTML Template
{% if session['loggedin'] %}<a href="{{ url_for('dashboard') }}" class="cta"><button>My Account</button></a>{% endif %}
{% if not session['loggedin'] %}<a href="{{ url_for('login') }}" class="cta"><button>Login</button></a>{% endif %}
this is my code inside of the flask app
what im trying to do is if session['loggedin'] is true it will display my account
otherwise it will show login
i fixed it thanks anyways
@zinc hill have you download django-cors-headers
And allowed requests from your react frontend
django-cors-headers for rest api
In django, Is it possible to validate a normal html form submission. which isn't made from a forms.ModelForm against a forms.ModelForm ?
How do i validate a normal html form which isn't made as a forms.ModelForm instance ?
How do i add a phoneNumber field to django
<a href="http://{{domain}}{% url 'activate' uidb64=user_id token=token %}"
target="_blank"
>http://{{domain}}{% url 'activate' uidb64=user_id
token=token %}</a>
``` when I do this, the link is generated but the text displays the href same (without the exact syntax). how do I solve?
@near bison you can write a forms.Form and tell it what fields you want and write your own validation methods on it. A phone field often will use some regex to validate that it is the format you are expecting.
@indigo kettle and then can i use it validate any form ?
i mean a form which is not created with that using it in the template
i have a doubt with data bases
i'm creating a todo list
and i wanna make it a personal todo list
i've been researching and watching videos about this
but they only show how to create they never show how to create for each every user
if i create one todo list in one acc
i see the same todo list created in the second acc is see the todo list created in first acc
pls DM me
You're saying you're rendering a template that isn't going to use the forms.Form class but you still want to validate it using the Form? I suppose you can but it's a little strange
@somber fable I've answered this for you already, your program has to differentiate between users. You need authentication.
And what is that error
i dont know
i didnt undertsand wat happened
so i just removed the the todo list and started fresh
Well the error should've told you what happened...
Then we could've troubleshooted and continued
it says line 2000+ and stuff whereas i didnt write any code above 100 lines
yep, because you're using Django, which includes its own files which has thousands of lines of code.
So if you are using a feature incorrectly of one of them files, there will be an error
Or flask, since you're importing modules
ohh i'm unaware
i'm just a rookie, started 2 months ago
You should read through a tutorial which explains it
but currently trying web dev
I think it's called werkzeug-security for auth
i did
umm
i think this would be shameless if i ask
can u do this and explain me
i really dont get it
do what?
i mean creating database which carry a todo list for each and every individual
Well, it's not really a database problem. You will have one table in your database which contains all the todos for users. It's an authentication/account issue
i really dont understand wat u r tryna say me
but i'm very rookie to this web dev
just started like 6-7 days ago
@native tide
u there?
umm..
i might have been troubling u
sorry then
i just need this to be done
i completed remaking the app again
just need to do this
What I'm trying to say is, you need to store your notes within a table in your database, and then you need some form of authentication to link a logged-in user's notes to their account
fyi, there is also https://paste.pythondiscord.com/.
Hey guys!
Ideally We use Table to show the data we fetched from a sql database right?
we do that by using jinja templates and mysql cursor.
we execute a select * query and store the info in some variable and pass that variable to html page.
but what to do in case of this
if the html page is already made and it contains fields to display specific data values.
ex: if I have a student table with columns:- ID, NAME, SUBJECT
the table will look like this
| Id | Name | Subject |
| 01 | John | Biology |
| 02 |Fred | Economics|
and I write this query:
sid=02;
Sdetail=cur.execute(" Select * from student where id=%d",(sid))
return render_template('data.html', studentDetails=Sdetail)
and data.html will be like this:
ID:__________________
Name:_______________
SUBJECT:______________
how will I display those specific cell data to the specific fields?
hey all ...
any chances to show time live format?? without ajax or js..
i have this in template {% now "d/m/y" %} {% now "H:i:s" %} but it is frozen of course..
"live" is ajax
hi I am working with flask and i have this function ```python
@app.route("/", methods=["POST"])
def filterUpdate():
if request.method == 'POST':
filter = request.form['filter']
return redirect(url_for('index'))
"filter" isn't returned
What are you trying to return back to the code?
You need to pass the filter variable back to whatever code called the function.
so i have filter defined outside the function as a global
doesn't that overwrite create a new filter object the global definiton? (I don't use FLASK, just python)
I don't think so, because filter is local to the function.
Django follows the MVT structure: Model, View, Template. Your Template is your html file, View is written in python and in the view you tell it how to interact with the web app or the database. Model is the foundation of the database.
"To access a global variable inside a function there is no need to use global keyword. If we need to assign a new value to a global variable then we can do that by declaring the variable as global. This output is an error because we are trying to assign a value to a variable in an outer scope.May 31, 2020"
@tired venture I'm also not sure why you wouldn't just return "filter" back to the original function?
Doesn't seem like much else is going on there.
you can reference but not assign to a global in a function, unless you define the global inside the function, makes sense
When I first tried it it was messing with my redirect for the webpage so I was trying to see if I could bypass that but that could have been another issue
The other thing is this event is triggered by a button on the web page
if request.method == 'POST':
Why aren't you using this in the function that handles the form?
Oh I see, you press a button and that activate this function.
@app.route("/", methods=["POST"])
def filterUpdate():
global filter
if request.method == 'POST':
filter = request.form['filter']
return redirect(url_for('index'))
``` adding ```global filter``` like this fixed my issue
Hi everyone, I'm trying to upload images from TinyMCE's textarea to Django's server side and call them back as a list. Anyone tried to struggle with it before?
@fluid dawn I'm trying to hold with a postAcceptor.php script as docs says. Did you use it to make it work?
how would i go about sending a request to run a python function in a running python script? im essentially wanting my web page to take in a few user inputs then run them in my running selenium script.
what would i research for this is mostly what im asking
im trying to use django and js. not sure what else i need
@formal gull Have some API endpoints using django-rest-framework
You can make request to those endpoints containing data from your frontend, to run a specific function
okay. im still quite confused on what that completely means right now but im on the right path to learning i think
thanks
Okay, if you have any questions feel free to ask ๐ It's very similar to how you have your routes in urls.py and a view that runs whenever you visit a route - it's just that the API endpoints handle requests from your frontend which are not designed to be user-facing
thanks! im currently just watching the tech with tim videos that he has out now and will kind of break away when the stuff is different then what i am looking for
kindly suggest anyone to me, how to send bulk email in background or schedule through djanog. thanks
What's up ya'll. I have open source code for a Hero Slider I am trying to incorporate into my site. I have all the code for js, html, css, but cannot get it to work. Can anyone take a quick look and helpme out?
Thanks
@naive shard take a look at Celery of python, it work well with django for scheduling tasks
anyone who is familiar with aws ?
how much do you usually pay for a django app ? average. i know it depends on how much it's being used. is aws the cheapest option out there ?
@near bison also depends on your traffic and application complexity. It could be from less than $5/m to thousands/m. You might want to be more specific
generally is not only serving just Django but also implies database, cache, background task services, etc
I am having trouble extending the default django user model
i need the user to have
phone_number(pk)
registration_id(optional)
first_name
last_name
password
Address -- (has more fields) (i am thinking about making address a different table and having a one to one relationship)
Street
District
State
Country
Pincode
But i don't want the superusers to have all the properies. superuser needs only first_name, last_name, password.
@near bison you could use AbstractBaseUser to make your own User model with all of its properties. On saving an object to the model, you can check if is_superuser is True. And, if so, you can restrict the data to the columns you want.
@limber edge could you have your dest_address and from_address fields as a part of your Address model?
Then you can setup a relationship between Orders and Adress, and then access both of those fields from one relationship instead of multiple.
how can i overcome this error?
django web app deployment in heroku
wait a minute i'll send that too
@limber edge Yes, that would work if you want to specify if an address is dest or from.
I've not that familiar with SQLAlchemy, but like any ORM you can just access the tables fields through the foreign key.
If you find any better ways about it let me know, I'd be interested :)
@proven wedge what's the issue?
its saying : Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
Have you downloaded Python onto your PC?
yes
at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=todoapp-django1.herokuapp.com
im getting this error in log
@proven wedge and upon installation, did you tick the box about PATH variables?
check the directory , it may be an error
just go to the manage.py directory and give the command
i dont remember that right now
yes
๐ซ
Iirc I had a similar issue with python not found. I reinstalled python and made sure to tick the PATH variable box and it worked after
For windows 10
ok i'm gonna do that
Hey so I have a react express server with frontend and backend. In my backend Im storing data about Books in the actual localhost site when i open localhost:3000/Books all of the data shows up there, but Im checking if I can see the data in my Postman and when i try to enter localhost:3000/Books or localhost:5000 it just says Cannot Get /
What could the problem be
Hey guys! how would I take date type input in flask?
date=datetime.strptime(request.form['startdate'],%Y-%m-%d)
should it be like this?
yeah thanks that worked!
thanks!
@mental lodge It's a general rule that you should spend at least 20 minutes trying to solve something before you ask for help I believe
@limber edge been trying since yesterday
Can't find a lead
hello
i have this .html file here
but when i opened it in the webbrowsewr
it returns a blank page
it flashes the content of the file for a second but suddenly it became like this
Could you provide is with the html file please? @slim ether
should i start learning javascript because I'm decent with python(flask),html,css
sure, it can be helpful in the frontend as you already know flask.
the fetch API or ajax is quite helpful for interacting with backends (flask)
making the UI smooth, example: not refreshing when you hit the like button (only possible with JS)
cool
should i learn python gui and js together
flask can render web pages, you can sprinkle in some javascript to make the website more fluid and better
well it depends
like in different time period
its totally upto you
๐
Hey guys, I built the backend of an app now i'm really hating building the GUI
would you guys have any nocode solutions for this?
just to turn it into an app/ webapp
I see some nocode solutions online, wondering if anyone has any experience with them?
Could you give me an example?
@near bison Cause django will throw an error at you if a field is blank
@near bison Perhaps if you override the null or blank in forms.py, but I'm not 100%.
If you don't, then no.
You could have a default, which could just be {} or whatever as a placeholder.
@steep fiber Checked out bubble.io?
I'm not 100% if you can use the front end to connect to your own private API but I'm pretty sure you can.
ooo thanks so much looks promising
@split steeple @near bison blank=True on a field only affects forms iirc. That means that the field will be required if you render that form within your template. You can also have null=False in this scenario too. If it's a Charfield and nothing is passed and null=Falsedefaults to an empty string being saved in the model, so you can submit that form and not run into an errors (I think). Or you can have a field like this which will be based on the value of another field within the form.
Ah ok
i need help whit flask t-t
How do I clean a table in Django? I need to perform it just once, so I don't want to write python files for it
Meaning remove all the entries?
You can create a function that simple loops through and deletes all the entries. I am trying to remembers.. I think they're called manager functions?
Or you can do it manually of course with db commands on the server.
hello how to install requests in my jupyter notebook please ?
How? I removed a column from my table and there are some errors connected to it
Model.objects.all().delete()
@quick schooner "!pip install"
ohhhh
Where do I write it?
working thanks !
in your terminal use python3 manage.py dbshell
from models import yourmodel
Model.objects.all().delete()
this will delete all entries for this model
i think dbshell works
I mean, it seems to be not accepting python
you want to delete all entries from a model right ?
Yeah
so this should work yes
Aha, thanks
yourmodel.objects.all() loads all the entries
add .delete() and it deletes all entries
Makes sense
make sure u import your model first with from models import yourmodel and you are good to go
Yeah I did it all, now they all are deleted, cool. But it didn't help my initial problem ๐ฆ
So the problem I'm talking about is that after I removed a column from a table, in the admin's panel I can't access the table
Neither I can add, nor remove elements
I get an error "OperationalError at /admin/..."
And "no such column: my_column_mycolumn.price_range_from"
Don't you know the issue?
The thing is, it works just fine on my local machine, just doesn't work in the production for some reason
hi
im trying to show an PDF in my browser with flask..my problem...my route only starts the download... is this possible? without something like pdfjs?
#discord.js
Hey guys!
suppose In a flask project I have an event.html form where the user enters his details i.e. Username and Phone no.
now if I need those username and phone no. in another page what should I do?
in my case the Student enters STUDENTID and SportsID and gets redirected to the Sdata page.
Sdata page will display all the details about student with the help of above parameters. How would I pass those StudentID and SportsID which I have taken as an input in event.html form to Sdata page?
You actually don't have much control over this, as it will vary browser to browser and machine to machine for your clients. They may have PDF readers set up or they may not. They may have Acrobat Reader as a full app or plugin or Chrome may say "I'll open everything in a window and never start a download until requested".
Now, of course, it also matters how you're sending it. Are you just redirecting to a static PDF file that is on your server, a dynamic one that you're generating on the fly and you're just streaming to the user, or what? If this is the case, you may just have the wrong headers being sent.
not sure where to ask this
but i have some string data stored in mysql
I would like to preserve its formatting
like indentations
someone is copy pasting a word document into a text box in my webpage, and that data is then stored in a mysql
db
but id like to preserve formatting
You would need something to indicate the markup.
Like, strings throughout the text that specifically render spaces or other indentation (spaces not so much but other more specific stuff)
And then probably render that with javascript on the front-end.
Not off the top of my head. Maybe look at how escaping works in javascript, or look up libraries for markdown.
we used a "light box" to display ours
Could anybody who has gotten a career in web-dev shed some light on when you should start applying to jobs? Atm I've only done one project (Django + React note-taking app) and I'm working on another project which would integrate with an eBay/Amazon seller's account and calculate their tax returns from their business stats and spreadsheets.
These projects take a long amount of time and I'm torn up with imposter syndrome whether it's viable to apply to jobs or not with only 2 projects.
Hi guys! Is there any solution to run a task with timer? Not exactly a cron job, for example when I create a payment instance, I want to set a timer say 24hrs, and after 24hrs will run a task to expire that payment, like a set timeout callback, not sure how to do it. Im using Django BTW.
Hey, does anyone know of a resource to use CPython with beautiful soup? My boss is about to have me working on a webscraping project and I want to try to optimize with cpython
Is the data returned a string?
hi , how do i deploy backend to heroku if my github repository has a structure like so
root
---backend(flask)
---frontend(react)
From what i m reading, heroku needs the app in the root directory
error i'm getting ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/anagramcheck.git'
repo: https://github.com/Leeoku/anagram
Hi, does anyone know how to add these 3 python dictionaries to a list? I have tried but I can only get the last one in a list. I see they are not separated by a comma. Any help would be great!
@native tide you can use python append()
your_list = []
your_list.append(your_dictionary)
Thanks, I tried that but only the last dict was going in.
can you tell me how did you get those dicts?
I have one dict and I wanted to change the year from and to value in it so I made a list of new year from and to value, looped though it to create more dicts
can you share the code for that?
!codes
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
def year_loop():
payload_per_year = []
for f, t in zip(year_from, year_to):
parsed_json['timePeriod'] = (f, t)
print(parsed_json)
this doesn't work right?
for f, t in zip(year_from, year_to):
your_list.append(parsed_json)
that only inserted the last dict into the list. the dicts are not separated by commas if that has anything to do with it?
i'm trying to figure out the code that where you print to the console
the for loop loops 3 times right?
@gaunt marlin can you answer me?
@thin dome you want to run psql raw query? take a look at https://docs.djangoproject.com/en/3.1/topics/db/sql/
thanks
yes 3 times but then when I go to append the 3 dicts, only the last one goes into the list
When you are appending dictionary, you are actually appending its reference since dictionaries are mutable - that's why all of the entries are actually pointing to a single copy of the dictionary
Use this instead:
your_list.append(parsed_json.copy())
ok great thank you I will try that, I have to go now but I really appreciate your help ๐
Hey guys quick question!
I'm using the django library django-maintenance-mode. This library is used to put the page in maintenance mode (thank you Angel).
The thing is that it has a config param called:
MAINTENANCE_MODE_IGNORE_URLS = (HERE IS WHERE I NEED HELP)
The docs says this
list of urls that will not be affected by the maintenance-mode
urls will be used to compile regular expressions objects
MAINTENANCE_MODE_IGNORE_URLS = ()
The only page that I don't want to be in maintetance mode in the login page because the admins will need to log in and the maintenance won't affect them.
That param is in the settings.py file. My problem is that I don't know what I have to write in the parenthesis to avoid the login page to be in maintenance mode.
This is my folder strucutre
core
โฃ settings.py
authentication
โฃ urls.py
And this is my urls.py file:
urlpatterns = [
path('login/', login_view, name="login"),
path('register/', register_user, name="register"),
path("logout/", LogoutView.as_view(), name="logout")
]
thank you guys ๐
Anyone here have some experience with Traefik?
can you make a professional website using django?
instagram is a lot of django, so yeah
Hi
Someone working in some open source project using django?
I have a little exp of DJango
And want to level up by contributing to open source projects
you could look into contributing to our website, I think we have some good first issues, though I am not 100% sure.
hello
My Question Is :
in below script
def create_app(test_config=None):
what is test_test config Explain why it's used here
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(name, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
ask away
I have done a website by HTML,CSS, and JS and I have uploaded it at my domain at one.com
unfortunately the line will be %%%.com\index.html
are they anyway to make it at a home page that doesn't says
%%%.com\index.html but only be %%%.com
Is there a way to get the client's mac address using django backend...?
I hope one day someone will answer me
@compact flicker MAC addresses are used in ethernet, so only in local network range, all you can get is MAC address of your gateway (ip router)
Ok...
then is there a way to get IPv6
I don't use django but probably you will have it in request object: https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest
try request.META['REMOTE_ADDR']
connection to a remote mysql database times out when doing a post request. How can I capture the exception and get flask to redirect else where when this happens?
@main_bp.route('/record/update', methods=['POST'])
def update_record():
try:
## some code here to check if the record has already updated
## some code here to update record if it hasn't
except Exception:
## some code here to check if the record has already updated
## some code here to update record if it hasn't
Not catching the exception
2020-12-10T16:54:01.517184+00:00 app[web.1]: [2020-12-10 16:54:01,500] ERROR in app: Exception on /db/update/record [POST]
2020-12-10T16:54:01.517195+00:00 app[web.1]: Traceback (most recent call last):
Anyone used WTForms with Flask
I am trying to get the validation error
if not AdminRegister().validate_on_submit():
print(AdminRegister().email.errors)
returns empty dict
if not AdminRegister().validate_on_submit():
print(AdminRegister().errors)
returns empty dict
if not AdminRegister().validate_on_submit():
print(AdminRegister().errors.items())
returns empty dict
why config.update
and not app.run
yeah I use that too for my projects, but never had to use config.update
Normally setup app name in init, and then have a run file if I'm using it locally with debug set to true
Honestly I'm not sure
hello
is there a better way to do this please ?
e_home = e.filter(Q(home_team__abbreviation=team))
e_away = e.filter(Q(visitor_team__abbreviation=team))
odd_array = []
for event in e_away:
try:
odd = event.bet.all().first().home_opener_odd
if odd != None:
odd_array.append(odd)
except :
pass
print(odd_array)
print(np.mean(odd_array)) ```
trying to get the average of a field of a model which is linked to another model with a foreignkey
Hey all, if I wanted to use Rank() I can annotate it into a queryset and display it
def leaderboard_queryset() -> QuerySet:
rank_window = Window(expression=Rank(),
order_by=F('elo').desc())
board = (
Leaderboard
.objects
.select_related('profile')
.order_by('-elo')
.annotate(name=F("profile__name"))
.annotate(rank=rank_window)
.annotate(win_rate=Case(
When(games=0, then=0),
default=(Decimal('1.0') * F("wins") / F("games")) * 100,
output_field=DecimalField(),
)
)
# How can I preserve Rank if I was to do something like this?
.filter(profile__name__icontains="Drac")
)
return board
However now I have quite a few entries where I'm adding in server side pagination and a search. Is there a way to preserve the rank from the entire dataset rather than the filtered data set?
hello, can you be more specify? are you talking about django form validation or custom error message?
actually that is html feature, when you set blank=Flase the html input will rendered with required in the form, for example it will render like so <input type="text" required>. If you rendered with django form then the validator will still kick in, you can see the validation error with {{ form.your_field_name.errors }} in the template, but it will show after you submitted the form.
here it is in the docs https://docs.djangoproject.com/en/3.1/ref/forms/api/#django.forms.Form.errors
also the validation only kick in for forms.ModelForm, not forms.Form
I have an custom authentication for user. But also I want authentication for developers who are using my API. So how to implement two authentication in DRF.
Jwt
@stable kite you can create your custom authentication class by subclassing BaseAuthentication class of DRF, and use it in drf default authentication class in settings or per view. Take a look at https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication
Django, API, REST, Authentication
and yes you can have multi authentication with adding those custom class in settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
i have created a custom authentication
you have to write a custom one for DRF, which is not related to the django one
i know
i have created as per drf documentation
@gaunt marlin My problem is if the first is for User & the second one for developer than drf runs user only & not developer one
it run by order from top to bottom, you have to figure out a way to satisfied both conditions then
that's what my question is how to do that?
i took a look at the docs and at this part
The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.
In some circumstances instead of returning None, you may want to raise an AuthenticationFailed exception from the .authenticate() method.
Typically the approach you should take is:
If authentication is not attempted, return None. Any other authentication schemes also in use will still be checked.
If authentication is attempted but fails, raise a AuthenticationFailed exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
you need to return None on your User authentication class so it can run the other
no it don't run it
as user is not None after running user authentication
i don't think you understand what i mean, if you want to run both authentication your first authentication class have to return None (if fail authentication) so it can run to the second custom authentication class(developer)
i don't have my pc with me so i can't test but it's what the docs described
@gaunt marlin My first authentication (User) returns (User,None) & second authentication(developer) returns (None,Developer).But drf only runs the next class when both are None. Which is not possible in my case
@stable kite i think you supposed to return None, not the tuple of (User, None) (if the authentication failed on it)
@stable kite this is what i mean
first_authentication_class():
if ok:
return (User, None) # this will stop the flow
else:
return None #so it run to the second authentication class
second_authentication_class():
if ok:
return (Developer/User, None) # this will stop the flow
else:
return AuthenticationFailed() # now we done with checking
The method should return a two-tuple of (user, auth) if authentication succeeds, or None otherwise.
i know i have
first_authentication_class():
if ok:
return (User, None) # this will stop the flow
else:
return None #so it run to the second authentication class
second_authentication_class():
if ok:
return (None,Developer) # this will stop the flow
else:
return AuthenticationFailed()```
if you did it like so then it's strange as the docs state this should work, i will test this when i get home
sure
hi is there any free design tool for front end develop. I am not that intrested in design stuff but is there any tool that can be used?
@dense slate
1.I want to change the text-decoration of a link inside a div in my article.
2.there is this called 'user style sheet' which has default text-decoration : underline.
3.I wish to make text-decoration:none. But my change is not executed.
4.help me ๐
@glacial orchid refresh your browsers cache to manually update any CSS changes if it doesn't do it for you. If it's not as desired then theres an issue within your CSS
I'm having trouble using Flask and Jinja2 forms
I'm creating a site for school which has a SelectField of the grade and then I have a selectfield of the class number I want the select fields options to be for example
B'5
where B is the grade and 5 is the class number but I don't know how to do some
class whosTableForm(FlaskForm):
classesPerGrade = {'ื': genNumbers(16), 'ื': genNumbers(17), 'ืื': genNumbers(18), 'ืื': genNumbers(17)}
Grade = SelectField("ืฉืืื", choices=['ื', 'ื', 'ืื', 'ืื'])
Class = SelectField("ืืืชื", choices=classesPerGrade['ื'])
Capsule = SelectField("ืงืคืกืืื", choices=["ืืืฉ ื'", "ืืืฉ ื'", "ืืืชืชื"])
Submit = SubmitField("ChooseClass")
This is my Form class but I don't know how to change the choices for Class according to the value selected by Grade
Nothing in my css brother
I did same outside my div article.
That worked
It's just that in my div
Outside, everything is usual
@native tide
How are you implementing the changes? Show a snippet of your code, and for you to change text decoration its in your CSS, press CTRL + F5 after any changes to clear your cache @glacial orchid
class Room(models.Model):
partOneDes = models.CharField(max_length=30, blank=True)
partOne = models.CharField(max_length=30, blank=True)``````py
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
fields = ('id', 'partOneDes', 'partOne')``````py
class RoomView(generics.ListAPIView):
queryset = Room.objects.all()
serializer_class = RoomSerializer```could someone explain why this ends up saving all of my entries in the api? i am looking to not have them saved since i do not need to store all of this data. i just need to use it once and then it can be gone essentially. (worried about future storage) https://gyazo.com/2dcb149782f3affed190d18a750ec025
would deleting it after it is done being used just be the way to go here?
How do i store phone number with django model with a validation
do i have to use Charfield and write a regex myself
Why am i able to create two entries in a table with same primary key during testing
and some of the field specific validations also seems to be not working during testing
show code
@near bison Charfield w/ RegexValidator or import a module for a phone field
There's a package called Django phone number field. It works pretty well.
Having trouble finding something simple. I'm trying to demonstrate how variables work within templates.
I have this example:
<p>
For instance, "Hello {{request.user}}!"
</p>
<p>The above username was rendered out by inserting <code>{{request.user}}</code>.
I want the display to show {{resquest.user}} as the raw code {{request.user}}.
I'm just having trouble finding info on how to do that.
I thought it would be something as simple as a filter
maybe by sending this string {{request.user}} as a value argument to the template
Sorry, I just realized I forgot to say I'm using Django
in the render function
@slim night yeah, that works but I want to do it on the fly
<p>"{% templatetag openvariable %} some text {% templatetag closevariable %}"</p>
Does anyone use Django and Strapi.js?
@indigo kettle perfect! exactly what I was looking for.
follow up question. I can get away with
{% verbatim %}
{{request.user}}
{% endverbatim %}
as opposed to
{% verbatim someblock %}
{{request.user}}
{% endverbatim someblock %}
Is that bad practice?
no
it's fine
you just have the ability to name the block in case you want to write the verbatim tag inside of the block
see here is the error professor
@native tide Wrong server?
It doesn't work perfect for me
If i use PhoneNumberField as the primary key and i try to delete multiple users from the admin panel. i get the error that '<' is not supported between two PhoneNumber instances (in django)
And why does python test let me create non valid phone numbers in phone number fields
do you have add a validator to your phone field?
you should call clean method to validate.
when hosting a aiohttp thing on heroku what should i put in as the address
rn im just throwing in "localhost" as the address and port 5000 and I just get the application error message from heroku
perhaps it is misconfigured
?
i am not that intrested in designing web site. is there any software i can use that could help me with this?
hey anyone know why I'm getting this error:
Application object must be callable.
2020-12-12T05:20:22.909496+00:00 app[web.1]: [2020-12-12 05:20:22 +0000] [9] [INFO] Worker exiting (pid: 9)
2020-12-12T05:20:26.000000+00:00 app[api]: Build succeeded
2020-12-12T05:20:52.999760+00:00 app[web.1]: [2020-12-12 05:20:52 +0000] [4] [INFO] Shutting down: Master
2020-12-12T05:20:52.999851+00:00 app[web.1]: [2020-12-12 05:20:52 +0000] [4] [INFO] Reason: App failed to load.
2020-12-12T05:20:53.069213+00:00 heroku[web.1]: Process exited with status 4
2020-12-12T05:20:53.111871+00:00 heroku[web.1]: State changed from up to crashed
2020-12-12T05:22:26.435188+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hurbapi.herokuapp.com request_id=3783bd56-c1f7-4c93-91b3-0c29754418d1 fwd="69.181.8.147" dyno= connect= service= status=503 bytes= protocol=https
2020-12-12T05:22:26.567586+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hurbapi.herokuapp.com request_id=1323c415-8459-437e-830f-ed787077e82c fwd="69.181.8.147" dyno= connect= service= status=503 bytes= protocol=https
2020-12-12T05:22:30.253251+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/settings" host=hurbapi.herokuapp.com request_id=91995d00-c400-4bb9-8732-513336cd07a9 fwd="69.181.8.147" dyno= connect= service= status=503 bytes= protocol=https```
from this simple code:
```py
import json
from flask import Flask, make_response, jsonify
app = Flask(__name__)
@app.route('/settings', methods=['GET'])
def settings():
with open("servers copy.json") as f:
storage = json.load(f)
return jsonify(storage), 200
if __name__ == "__main__":
app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)```
task = logs.query.filter_by(typeVA='V').first()
flasksqlalchemy i wanna add secondary filter
id == request.form['id_client']
perhaps you forgot to set env variable for flask
Are there any plug and play mongodb backends for django?
I could find djongo(www.djongomapper.com) but several features like transaction, text search, etc are paid.
django-mongoengine is opensource, but looks outdated
hello
i want to make an online pdf to docx converter with Django is there any project or online resources from which i can start learning?
do you know django?
Eyo boys, can someone give me a hand here. I have form that creates recipes and i have a creator field which should display the user that created it
i have a user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) in the model
but on the creation page it gives me the choice to pick every user i have registered ๐
i want to be limited to just anonymous or the current logged in user
i had this problem before which i corrected using Javascript , and it's not optimal att all , kinda Cheesy , but i believe oneToMany is the way to go
you can try changing your view , if you're trying the class based view change it to function based view , and then try to create the model(post for example) manually Post.objects.create(user=request.user) while maintaining the foreignKey relationship to Make cascading on delete
then some if statements in the view and some in the template html and you can have some customised logic runnig
my play apparently is to overwrite the validation
so it sets the user before it validate
Cannot assign "<SimpleLazyObject: <User: stefan>>": "Recipe.author" must be a "UserProfile" instance.
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
i am lost ๐
django help pls
So this is my custom manager class and model
however,when I try to make migrations I get the following error
File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\backend\models\__init__.py", line 2, in <module>
from .data_sheets import DataSheetsCluster, DataSheetsCategory, DataSheet, DataSheetField, ForeignKeyField, FieldData
File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\backend\models\data_sheets.py", line 233, in <module>
class FieldData(models.Model):
File "C:\Python39\lib\site-packages\django\db\models\base.py", line 161, in __new__
new_class.add_to_class(obj_name, obj)
File "C:\Python39\lib\site-packages\django\db\models\base.py", line 326, in add_to_class
value.contribute_to_class(cls, name)
File "C:\Python39\lib\site-packages\django\db\models\manager.py", line 113, in contribute_to_class
self.name = self.name or name
AttributeError: 'RecordDataManager' object has no attribute 'name'
Why?
Can someone pls help me?
Pls ping me when help!
thanks!
you forget to super().__init__() in __init__() of your manager
it should be like
class RecordDataManager(models.Manager):
"""
A manager class to deal with Cluster Size Limits,
Field DataType Validation and JSON.dumping raw data.
"""
def __init__(self):
self.data_type_validators = {
'BOOLEAN': BooleanValidator,
'INTEGER': IntegerValidator,
'FLOAT': FloatValidator,
'CHAR': CharValidator,
'DATE_TIME': DateTimeValidator
}
self.max_record_kilobyte_size = 2500
return super().__init__()
def validate_data_type(self, data, field_id: int):
"""
Checks if the provided data suits the dataType
of the given field. Raises a ValueError if the requested field doesn't exist.
"""
ref_field = DataSheetField.objects.get(id=field_id)
return self.data_type_validators.get(ref_field).validate(data)```
@scenic dove https://docs.djangoproject.com/en/3.1/intro/tutorial01/
@halcyon lion
Thanks man
โ๏ธGreat books for learning Django
@native tide
Thanks
no idea ๐
im currently trying to inspect this webpage with selenium https://www.google.com/search?client=opera-gx&q=poggers&sourceid=opera&ie=UTF-8&oe=UTF-8
but whenever i do the 'agree to chrome tos' or something thing comes up.
I tried to get around this by clicking on the 'agree button' but it always says 'element not found.'
what do i do? (im using chrome web driver)
Hey I finished learning basic web scraping wid Python.
I wanna try out django or flask now
Which one should I learn and from what are the best rss?
How to connect python django communication between .net core web project??
def register():
"""Register user"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("Enter a Username Or Username already exists", 403)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("Password does not match", 403)
password = request.form.get("password")
confirm_password = request.form.get("confirm_password")
elif password != confirm_password:
return apology("Passwords does not match!", 403)
after running flask
i get this error
how is it invaid pls help me
Cuz you have code unindented then try to continue the block.
ok
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@nova sparrow Also if you're using WTForms you should have validation done within your form model, instead of the view. Such as ensuring that the fields are not empty.
Hello, I currently have an application where you can monitor your calorie intake and it also suggests plans, I am wondering maybe someone could recommend features I could implement, that would make me learn more about web dev in general and django.
@native tide @dense slate
look at the 'user agent stylesheet'
look at the body of html
and look at the css
I did the same thing for two ancher tag but one is working and other is not
please help
default value of Blog link is changed but not of title link although I did same thing for both of them.
above user agent stylesheet is for author
this one is for blog link
and here is the template in action
I hope its enough explanation for anyone to understand
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'item'
elif request.method == 'POST' and request.form['type'] == 'remove':
db.session.delete(stock(name=request.form['item']))
db.session.commit()
{% for task in task %}
<tr>
<td> {{ task.name }} </td>
<td> {{ task.quantity }} </td>
<td>
<form action="/makhzon/" method="post">
<input type="hidden" name="type" value="remove">
<button>
ุญุฐู
<input type="submit" name="item" value='{{ task.name }}' style="background: none; color: white; cursor: pointer; outline: none; border: none" />
</button>
</form>
</td>
</tr>
{% endfor %}
help pls
what is a good practice to get a new access_token? should i just do call getNewToken every 5 mns? or ....?
@glacial orchid why is the selector so long?
.profile a, .title a{
text-decoration: none;
}```
its one way to do it
I also have used the direct one
still didnt work
Something is overriding your style
Try adding inline style with !important @glacial orchid
hey hey, I'm interested in a question what you guys think.
is django a good career option?
because somebody said me it's not 2010 anymore, so..
Yeah
I mentioned
And that's why I'm here
Yep,I posted some pics
Inline styles
In the HTML file
In the a tag
<a style="text-decoration:none !important" href="#">Home</a>
@glacial orchid
I'll try and let it be known
@native tide include segoe UI's font link in your html or css file
yo can someone check out my project? https://github.com/hanyuone/kanban i'm trying to do put requests (in frontend/index.js) with django but it doesn't seem to update the database
are you running react & django on same address?
uh react's on localhost:3000 and django's on :8000
what error are you getting?
Did that!
it worked
thank You
You know why it worked?
@stable kite didn't get an error, the put request returns 200 but it doesn't actually update the values in the db
@native tide you want to store a JSON file on your server and grab it later on directly ?
not sure about server thing but I want to grab the data from it. I'm just learning
what's the best practice?
but where are your obtaining this data from? are you obtaining it from the client and sending it through fetch? is this something that you can save under a model there is a JSONField model.
nah I have the json file
what's jsonfield model?
What's the proper way to let Users create shareable content in Django? For example "User A" create a "Project" and lets "User B" and "User C" as admins (read and write rights) and "User D" as member (read rights) and all others users can only see the name of the project.
Why is get_user_model() function used in django ?
why can't i just import the User model myself
Yea
There was an extra curly bracket in .css file๐๐๐
do you guys have any suggestions on where i can learn web developmnet using python ONLY
you cant, you're gonna have to use HTML, CSS and most likely JS no matter what youre doing
well in django dont you ONLY use python or?!
Hi, is flow the go to py module for web development?
never heard of flow ever and google it on anything other than pypi doesnt reveal much so i doubt
Quart/Flask is a great starter framework
for security, use DJango
for advanced, use aiohttp
meh security in Django is no better than any other
if your a show off...create your own framework
it has more available to it
sync frameworks:
- Django
- Flask
- Bottle
- some others
async frameworks:
- FastAPI
- Quart
- Sanic
- AioHTTP
- Starlette
- Japronto (no longer maintained)
- flacon
- some others
not really?
@app.route("/images/<variable>")
def main_page(variable):
return (f'<img src="C:/Users/scorz/Desktop/images/{variable}">')
why doesnt this work?
i get this
yes the path is right
It's generally not good practice to use full path for an image
Try using a relative path
Try using alt attribute as well for testing
either wont work @noble smelt
starting with web developing with the goal of becoming a fullstack dev, I guess I should use Django. Question is: I heard that Django is not the best choice for frontend. Do you recommend using another frontend framework and which one, or should I first learn frontend in django and later swap to another framework like react?
Do react and django combine well or how is it done?
Well backends that pair well with react would be the ones that are also in JS, so node.js (specifically express).
I'm using a Django backend with a React frontend and actually it's not too hard to combine them together
I have django render one page when the user visits the site and the rest is handled with React (technically as an SPA) and with react-router
can anyone tell me on how to configure/setup selenium grid 5 for threading/multiproccesseding
To dynamically import User model
Having some trouble getting this JS script to work, any suggestions? ```const img = document.getElementsByClassName('clickpet');
const textBox = document.getElementById('textBox');
img.onclick = popup(){
console.log('clicked on');
};```
At line 4 (the { key), I get an error, ';' expected.
hey guys I am Shaish Guni And I have a question how should I start web development on python using django and flask
flask is easier to learn
DJango is a bit more complex but also a good learning curve
Yeah i agree with you, and also Django had great Documentation. Meybe at first you feel some difficult until you learn CBV it become less difficult.
how can i get a personal url?
What's a personal URL?
i want a url for the website designed by me.......with html
You mean you want to know how to host your website on the internet?
Hosting usually costs money, but there are some free hosting options.
Do you have a web server already?
what is a web server
Check out "pythonanywhere". If I remember correctly, they're targeted mainly towards hosting websites in Python. A different option is "GitHub Pages", which can host static web pages.
A web server is a computer connected to the internet that will host your website and allow people to connect to it.
ohhh i see
so is it is basically a computer right from where i'm writing my xml?
huh? @proper hinge
No. Where you write the code and where it's hosted aren't necessarily the same.
Hey guys, I have an old website just using basic html/css/js on a lamp stack, but I want to make the webpage more dynamic with a django backend. I'm trying to figure out if I can re-used the old frontend (css/html basic layout) while still using django, but I can't really find any resources.
I'm comfortable with python/html/css/js by the way, just not with the specific implementation/django. Does anyone know a straightforward way/resource to achieve this?
@light gale i think u can look up literally any youtube vids on django project it would show you how to do that
Most existing projects create or use a 'template', I would like to re-use as much of my frontend as possible.
or am I thinking weirdly? Maybe it is easier than it seems to me
ohhh I think u need to look into Django rest_framework
i am assuming you want ur Django only as backend right?
so this way ur front-end can just http request stuff to django back-end right?
Yes exactly
I have a 'website' set up using html/css/js, and I just want to connect some nice things using Django
yeah rest_framework django would be the way to go
for instance, grab my twitter feed autoamtically and update divs accordingly etc.
let me take a look, thanks
@light gale if you want your webpage to be dynamic, Ajax work nicely with Django Rest Framework API
When I am trying to send mail in django it shows "No connection could be made because the target machine actively refused it"
@rough tulip you probably didn't set up email backend config in your settings.py
I did
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER =''
EMAIL_HOST_PASSWORD = ''
Does anyone know if it's possible to override the from address in an office 365 email? In one of applications I can get it working with a different provider, but with o365 i get a load of errors.
so in Django, I created a post class which contains information about what I want to display on my index.html. loading 'posts' on index is working, but I now manually define my posts here (views.py):
# Create your views here.
def index(request):
#return HttpResponse('createpost/index.html')
post1 = Newpost()
post1.desc = 'test'
post1.url = 'https://www.google.com'
post1.date = '20 JAN'
post1.target = '_blank'
posts = [post1]
return render(request, 'createpost/index.html', {'posts': posts})
I'm using the default sqlite3 database, I'm guessing I want to store the posts in there and pull it? I'm not sure where to find info on how to do this though, can someone send me in the right direction?
I probably need to do that in models.py then, for reference, this is the code there:
from django.db import models
# Create your models here.
class Newpost:
url : str
date : str
desc : str
target : str
Yup, you'll need a model to save/retrieve your information.
https://docs.djangoproject.com/en/3.1/topics/db/models/
Hello I'm Will
Hello
Can I do web Dev in python without using any framework?
Since the help channels are off I'll try my luck here...
I need help with Flask and WTForms
I'm trying to create a table which each <td> contains a select
and on POST I want it return the data of the entries, I'm trying to do so using WTForms FieldList
<tbody>
{% for hour in range(1, 12) %}
<tr>
<td>{{ hour }}</td>
{% for day in range(6) %}
<td>
{{ template_form['schedule'].TwoDTable[6 * (hour - 1) + day].form.Lesson() }}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
This isn't working but I don't know how to make it work...
This is my Form.py:
class lessonForm(FlaskForm):
Lesson = SelectField('lesson', choices=args.Lessons, render_kw={"Class" : "lesson"})
class scheduleTableForm(FlaskForm):
TwoDTable = FieldList(FormField(lessonForm), min_entries=1)
submit = SubmitField('Submit', render_kw={'value': 'ืขืืื'})
and how do I pull the data in app.py
what are the best resources to learn gevent ?
How can I add pagination to tables in Django?
Hello guys, am kinda free and need to work on someone's Django project. If you feel needing help, kindly DM me. Its free!
Are you familiar with Flask?
Anyone here familiar with Flask and WTForms?
I really need help :/
just alittle bit,
Mind helping with a few things?
for some reason when I place my Field it also places a label is there a way to disable it?
show the code please
<table>
<thead>
<tr>
{% for day in range(8) %}
<th>
{{ days[day] }}
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for hour in range(1, 12) %}
<tr>
<td>{{ hour }}</td>
{% for day in range(6) %}
<td>
{{ template_form['schedule'].TwoDTable[6 * (hour - 1) + day] }}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
This is the table part, for my understanding I only place the object that is contained in the FieldList TwoDTable
class lessonForm(Form):
Lesson = SelectField('lesson', choices=args.Lessons, render_kw={"Class" : "lesson"})
class scheduleTableForm(FlaskForm):
TwoDTable = FieldList(FormField(lessonForm), min_entries=66, max_entries=66)
submit = SubmitField('Submit', render_kw={'value': 'ืขืืื'})
I do not understand why it adds a label
Also Is there a way to pass it a parameter?
I want it to have an ID of which Select field it is
class NoLabelClass(object):
def __init__(self, *args, **kwargs):
super(NoLabelClass, self).__init__(*args, **kwargs)
for field_name in self._fields:
field_property = getattr(self, field_name)
field_property.label = None
class lessonForm(Form):
Lesson = SelectField('lesson', choices=args.Lessons,
render_kw={"Class" : "lesson"})
class scheduleTableForm(FlaskForm):
TwoDTable = FieldList(FormField(lessonForm), min_entries=66, max_entries=66)
submit = SubmitField('Submit', render_kw={'value': 'ืขืืื'})
class NoLabelForm(NoLabelClass, scheduleTableForm):
pass
my_no_label_form = NoLabelForm()
try this..
Hey guys, I am still "new" to Django and I was trying to make a website that was integrated with discord. I already have everything built up so that if someone is given a role in our discord server, that roles gets associated with the "Member" model
I also figured out how to implement my own user models so I could use exclusively discord login
The last part I cant seem to find a solution or docs on how I would so that is the "Groups"
I want so that the "Roles" are the "Groups"
But I am not really sure how to reimplement that feature like I did with the Users model
If anyone had to do this in the past or knows something that could help me x)
@keen acorn you can link the Roles and the Groups models together with a OnetoOne field
hello, in flask or builtin have something like "readfile" from php? I want download files directly from url, with headers in php it is possible. In python i can use urllib for that reason. But then i need first download file to server.
im so confused by all these flask wrappers
like why do flask_user and flask_login both contain a login_required function
all im trying to do is manage user access based on roles
i have no clue what best practices are with all this overlap
hey guys, does anyone here have experience with flask? Because I have a module, and I dont want to pass it every time as an argument in every render_template() func, wanted to ask here how I can set it as an environment variable or something so it will be automatically passed in every template in flask
Something like the current_user object. I dont have to pass that every time as an argument in my render_template function, but can access it in my templates
Hey guys, I'm doing the following stupid thing:
I want to use the price variable which I give with my view
it works here, when I hardcode it:
which is: ```html
<div class="grid-container-2">
<div class="Date-2"><p>Dec '20</p></div>
<div class="Text-2"><p>Today, the 14th of december 2020, I decided not to invest $5000 in BTC, and instead spend it on more worthwhile things. At the current rate, this means I have lost out on ${{price}} in profit.</p></div>
</div>
but when I try to implement it within my 'news' posts:
{% for new in news %}
<div class="grid-container-2">
<div class="Date-2"><p>{{new.date}}</p></div>
<div class="Text-2"><p><a href={{new.url}} target={{new.target}}>{{new.desc}}</a></p></div>
</div>
{% endfor %}
``` - > the new.desc contains the {{price}} as a string. is there a straightforward way to let it grab the price variable?
I basically grab it from here.
This is django by the way
@light gale new.desc is a string, and you have {{price}} within that string. You will need to pass that price from your view.
I don't think Django will parse the output of a variable and render anything inside that
So, what you could do is:
In your view, retrieve the price, then pass it into your template as a variable (such as price) to then be shown.
def index(request):
#return HttpResponse('createpost/index.html')
# post1 = Newpost()
# post1.desc = 'test'
# post1.url = 'https://www.google.com'
# post1.date = '20 JAN'
# post1.target = '_blank'
# post1.save()
posts = list(Newpost.objects.all())[::-1]
news = list(Newnews.objects.all())[::-1]
btc = btcresult
context = {'posts': posts, 'price':btc, 'news' : news}
return render(request, 'createpost/index.html', context)
def btcresult():
url = "https://api.coindesk.com/v1/bpi/currentprice.json"
response = requests.get(url).json()
price = response['bpi']['USD']['rate']
result = round((float(str(price).replace(',',"")) - 19065.72) * 5000/19065.72, 2)
return result
``` this is my view
So you have to manually render it
I pass price using the view, but then the text gets loaded as a string
Create a template object from the description and render it manually
then pass the rendered output to your "real" template
class Newnews(models.Model):
url = models.CharField(max_length=100,default=None, blank=True, null=True)
date = models.CharField(max_length=100,default=None, blank=True, null=True)
desc = models.CharField(max_length=300,default=None, blank=True, null=True)
target = models.CharField(max_length=100,default='_blank', blank=True, null=True)
``` this is my news template, right?
from models
That's a model not a template
I just started with Django today, so it's quite fuzzy still.
Let me write up an example for you
Nice, that would work!
<div class="grid-container-2">
<div class="Date-2"><p>Dec '20</p></div>
<div class="Text-2"><p>Today, the 14th of december 2020, I decided not to invest $5000 in BTC, and instead spend it on more worthwhile things. At the current rate, this means I have lost out on ${{price}} in profit.</p></div>
</div>
Here you are passing price into your template (from your context). Good.
Here:
{% for new in news %}
<div class="grid-container-2">
<div class="Date-2"><p>{{new.date}}</p></div>
<div class="Text-2"><p><a href={{new.url}} target={{new.target}}>{{new.desc}}</a></p></div>
</div>
{% endfor %}
You are not passing the price. You are passing {{new.desc}} which is a string, and it will be rendered as one.
Thanks Nut, I thought as much, but it is unclear to me how to fix.
Mark is suggesting a template
so the only template I am using now is the index.html, which is basically the webpage.
(and some static entities such as css/js/media)
template = Template(desc)
ctx = Context(dict(price="123456"))
rendered_desc = template.render(ctx)
...
context = {'desc ': rendered_desc }
return render(..., context)
If you don't render the description manually, Django just interprets the price in your variable as a literal string, not as template syntax that should be rendered. Hence you were seeing literally {{ price }} in your web browser.
wait, I am stupid. I can just do it muchu easier I think.
๐คท okay
But yes, that would go in your view
I didn't use the exact variable names you have but hopefully you get the idea
posts = list(Newpost.objects.all())[::-1]
news = list(Newnews.objects.all())[::-1]
btc = btcresult
news.replace('{{price}}', btc)
that would work.
What do you guys think about this landing page? I feel like I'm missing something.
I'm going to add an animated scroll prompt for the user. But if you guys have any additions kindly let me know!
Yes it would work but it's not really proper
This is monkeypatched together, but it works.
Golden rule of programming, that means it is not stupid.
It is clean but too much whitespace
or I guess bluespace
like look at it 'from afar' -> it is mostly nothing. Maybe go a bit bigger on the text?
Thanks ๐ I'll go with that, some bigger text and I'll have small interactive trinkets to fill in the whitespace
Appreciated
No problem. I'm by no means good at design, so take it with a grain of salt
looking sleek so far, gj.
new django question:
class Meta:
db_table="Newpost_db"
db_table="Newnews_db"
class Newpost(models.Model):
url = models.CharField(max_length=100,default=None, blank=True, null=True)
date = models.CharField(max_length=100,default=None, blank=True, null=True)
desc = models.CharField(max_length=300,default=None, blank=True, null=True)
target = models.CharField(max_length=100,default='_blank', blank=True, null=True)
class Newnews(models.Model):
url = models.CharField(max_length=100,default=None, blank=True, null=True)
date = models.CharField(max_length=100,default=None, blank=True, null=True)
desc = models.CharField(max_length=300,default=None, blank=True, null=True)
target = models.CharField(max_length=100,default='_blank', blank=True, null=True)
So I just created a new db table newnews, migrated, but it does not seem to work?
for some reason, all my newnews items seem to be added to the newpost database.
anyone know what the easiest approach to creating and displaying the following would be:
df = pd.read_csv(
"https://raw.githubusercontent.com/allisonhorst/palmerpenguins/master/inst/extdata/penguins.csv"
)
mask = (
(df["species"].isin(["Adelie", "Chinstrap"])) & (df["body_mass_g"].le(3600))
) | df["sex"].eq("female") & df["year"].eq(2007)
df[mask]
so - here I want to be able to display a dataframe on a webpage (or the first 15 rows / something like that), and enable the user to create the mask, i'm not sure how I'd take input of something like that though - I think something like django would be overkill, but as I never touch web stuff I don't know what words to search for in order to find what other tooling enables this sort of thing.
my rest api seems to work, but then it just gets added to the newpost table instead. I probably just missed something, anyone have an idea?
Do you want it to be dynamic, or just load once then display statically on a page?
dynamic - the mask here is created by the user and they kinda need to see how it looks
If it were static I'd just hardcode it if you want a quick fix, seeing that it is dynamic, perhaps django is the way to go. You can probably find a mask alternative in JavaScript, but I'm guessing you want to keep using pandas?
i want to use pandas yeah, if it's django i won't bother tbh, too heavy
I'm not sure, if I were you I'd go the django route, but others might have an easier suggestion.
yeah bc you know django XD
Exactly, I'm biased ๐
but i don't want to learn a framework, i want to make a few buttons or some shit (presumably) and filter on them... hrm, i will leave it
@light gale what is your view for that API endpoint? are you using a modelSerializer?
@fossil thicket Using JS wouldn't be a bad idea. But also, if you use Django, if you are just rendering to a page it really won't take long to learn. You could do it in a day
I cry when cpanel default python version is 2.7 and I spent 2 hours trouble shooting why my code wont work haha
Hey @karmic egret!
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:
thanks for the tip!
is anyone good with flask and jinga. will literally pay u to help lol
bro
help
my authenticate function is always pritning none
when i try to implement authenticate in login fucntion
you should show us some code or something
Hello guys , can anybody here help me with a problem in webpy ?
Dear all, I'm writing a view that needs to open two links. How should I do that? thanks
whats up with it
whats your issue
can you describe more of what you want? you mean a views that open 2 seperate browser tabs with those 2 links?
Hey guys,
I'm trying to get a response of a webservice. I'm using the suds library.
My problem is that the response that I get is an "object" <Text, len() = 174>
I know that the response is there but I don't know how to get it!
Any help? ๐ฆ
hey guys, can someone have a look at my react/django project? i'm trying to do put requests in frontend/index.js, the request goes through but the database itself doesn't update when i drag an element (it snaps back immediately): https://github.com/hanyuone/kanban
frontend is on localhost:3000, backend is localhost:8000 rn
Hi oOoOkeem. I'm working on our CRM system and want to create a button that both opens a note-taking page in the app and calls a mailto: link
I've done this from JS before but now need to initiate it from the view
the mailto link is meant to use the default mailing client to create a email draft from a template which the use then finishes before sending
...so I can simply send the email from within the view
class Job(models.Model): # Create table
title = models.CharField(max_length=100) # Create column # Create Title Field (small text field)
# location =
job_type = models.CharField(max_length=15,choices=JOB_TYPE)
description = models.TextField(max_length=750)
pub_date = models.DateTimeField(auto_now=True)
Vacancy = models.IntegerField(default=1)
salary = models.IntegerField(default=500)
# ctaegory =
expirience_years = models.IntegerField(default=1)
error
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['โโ value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
any idea?
error from pub_date
@final sequoia so your API request is successful but it's not being saved to the database?
does webscraping count for this chat or is it only #unit-testing
This would be the right channel for webscraping, yeah 
alright, well im simply just testing now, but I ran into a problem "object of type 'Response' has no len()" does it refer to the links im scraping which needs a limit?
line 19-20 does nothing for now
Yep, at least thatโs what I think is happening
hi all
i just wanna know
how can i check if a mail idactually exists
without sending a mail to the mail iD
anyone can help me on this ???
or stepto verfiy the Mail addres
Any module for it ?
id actually *
use source_page.text in bs4 parameter
https://stackoverflow.com/questions/36709165/beautifulsoup-object-of-type-response-has-no-len
Hope this will clear why u should do it my friend
@final sequoia can you send some code
hello
this gives me a 400 Bad Request
spent 50 mins debugging - help
backend
y'all this is a beginners level error please have a look at it idk why im getting a bad request ples halp
im having issues using flask migrate
for some reason my app isnt being imported correctly
@wild echo We need a bit more info, what is the error explicitly saying?
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'name'
Ok, so let's start with KeyError: 'name'.
I'd print request.form to the console to see what it is and see whether it has the attribute name or not.
i did
dump() shows all variables in the frame
and it says request is nothing
but why though look at my backend and front end, I submitted the form as a POST request
can you show us the complete view (function) for that URL
Ok, so you are rendering your form on a separate view and using that as an API for handling the form?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
hmm, okay, that's strange. I'd suggest you use url_for in the action of your form to redirect the request to that view. Try to see whether that helps, as it sometimes does.
thanks
action="{{url_for(safdsa)}}"``` like that?
Looks right to me. I'm more of a Django person so take it with a grain of salt
yeah shalt try wait up
Hello everyone, I'm having an issue and was hoping for some assistance. I'm building a quiz application in Django, where we ask a question and the user has 4 multiple choices they can choose from. Once they make their selection, it would take them to the results page which show them if the answer was correct of not with an explanation. The problem is that I'm unable to bring up the User's selection, the section just stays blank with no errors and no database entry. I have enclosed my code here @https://gist.github.com/RemeoLong/eb05b2a28df7d98f649fa20af4f00049 . Any help would be appreciated
didnt work, stil giving the same Bad Request error
Ok, and in your console, it's making POST requests to that URL correct? Or is the error before the request is made?
the error is after the request has been received, it visits the POST URL and then comes the Bad Request error
127.0.0.1 - - [15/Dec/2020 19:28:34] "โ[35mโ[1mPOST /fan/profile/settings/update HTTP/1.1โ[0m" 500 - POST request
Okay, do you know what line is bringing the error:
KeyError: 'name'?
Is it from retrieving the data from the field or setting data to the session?
newname = request.form['name']```
this is the line where the error happens according to my debugger
Okay. Correct me if I'm wrong but I don't believe that buttons have an action attribute:
<button class="btn primary" name="add_elem" action="submit">Update Profile</button>
They should have the type="submit".
<button class="btn primary" name="add_elem" type="submit">Update Profile</button>
haha I thought the same, did the same change, and still saw the same error, and btw yes i believe you're right
your inputs are also missing the type parameter
ohhhh thanks will try now
still giving the same Bad Request error
OMG
FIXED IT
THE ERROR WAS - the HTML never rendered the updated HTML, it was always loaded from cache and hence the old version of the HTML without names was rendered
and this too
yeah, I was looking over the code and I didn't see anything wrong. I was so confused haha
thank you so much y'all really appreciate all of you taking interest to assist me, thank you so so much! โค๏ธ
all good ๐
Guys, I will open a hosting company. I need a theme for this. I need help.
hello, so i encountered this issue where when i called a file outside of the folder, that called file throws import error (the error file is importing another file), but when i instead, just run the error file and not from the file outside of the folder, the import error disappears
here's my folder structure for brief
(file)main.py
(folder)app--
|--(file)app.py
|--(file)views.py
|--(file)__init__.py
so app.py import views.py and perform some tasks, when i call app.py, everything works fine, but when i call app.py from main.py, it throws an import error at the place where app.py imports views.py
@hybrid bobcat #โ๏ฝhow-to-get-help
ok
@hybrid bobcat are you using flask
can you show us the imports
and not just when importing view, i tried it for other files that are not even importing flask, still import error
sure
so this is my folder structure for other stuff
main.py
app ---
|-views.py
|-utils---
|---form_handle.py
so in the main.py, i call views.py, and views.py imports utils/form_handle.py's class liek this from utils.form_handle import RegistrationForm and then the no module named utils occurs after i execute main.py
and what's the import in main.py?
from app import app, views
app.app.register_blueprint(views.pageS)
app.app.run()
so i called app.py, added views as blueprints, and then in views. i import utils/form_handle.py, this is where the error occurs
So, in the file you want to import, did you create a Blueprint object? Did you then import that Blueprint object within the main.py and register it?
Because that is what has to be registered.
how to get a moving background like YAGPDA website
yes, in app.py , i defined blueprint
Does anyone sell themes for my hosting company?
Can I see what you defined as blueprint?
app.app.register_blueprint(views.pageS) doesn't look like you're registering the actual blueprint, but your views.
ok
how to get a moving background like YAGPDA website
and app.app is the Flask()
I'd rather see some code.
@formal vault
sure
this is app.py ```
from flask import Flask
app = Flask(name)
and in main.py
from app import app, views
app.app.register_blueprint(views.pageS)
app.app.run()
and views.py is just a bunch of views
i am sooooo anoyed
three js wont work with javascript when it is meant to uhhhhhhhhhhhhhhhhhh
@hybrid bobcat I'm not too sure on those imports. To simplify it, couldn't you register the blueprint in app.py?
boys, how do i make it so when i click my dropdown menu the buttons below are not showing ๐
and where did you initialize your blueprint object?
@halcyon lion using JS?
@shadow hornet
@hybrid bobcat That's not how you set blueprints though, unless I am missing something. Where did you initialize your blueprint object?
Why are you pinging mods
to answer i mean i will ping some helper
i didn't i just copied code from stack overflow, so i defined blueprints by app.register_blueprint(arg)
@sharp tusk
@hybrid bobcat looks to me like you're using blueprints wrong.
@gray stone that's not how it works
hmm but it works tho
except the import is not
Nah ill show
urs is more like a html/css problem, prolly not ask here
so it's not working
the blueprint?
aint this a web dervelopment channel?
Well, you're meant to firstly initialize your Blueprint object:
example_blueprint = Blueprint('example_blueprint', __name__)
Then in your app.py (wherever you Flask object is), you have to register that blueprint.
yes but it's web dev for python, like backend frameworks and python stuff
i see, so do you think it might be the cause for the import error in views.py?
This is a good channel for HTML / CSS help, but pinging everyone under the sun so they drop what they're doing to help you isn't good. If no one here can help I suggest you do some more research on your problem while waiting for a reply@gray stone
ohhh backend dang srry but the YAGPDA web site still cool tho..
ah i messed up, you can also get html/css help here but except not pinging people frequently
Yes I think you've made a mistake with the blueprints. I'd recommend following this:
ok thx
ohh ok ok how to get a moving background like the one in YAGPDA web page
u can try using bootstrap
u mean learn it or copy paste ?
๐คฆโโ๏ธ
what?!
bootstrap have like some css stuff that can prolly help you animate your backgroudns
damn u r profesh man
im not
anyways last question
yes u r
i cant even import a file
Can't you just set a video for your background
do u think web development will last for like the next 5-10 years?
Also it's unclear what you mean by a "moving background"
what?????
u move the mouse it moves
suh boddy
i think what he meant is like animated backgrounds moves depending on the cursor
That's a JS problem, bootstrap won't do that. Bootstrap doesn't really do animations, just CSS styling. There's some JS libraries for what you're talking about
yea prolyl
can you show the code?
sure
ok wtb the 5-10 years question
pageS = Blueprint('pageS', __name__) and then i access route() from pageS
bc i heard web industry is dying
cuz that stupid GPT-3 AI stuff?
and who did you hear that from? ๐
yes they said a new tech will poop up like every 20 years
20 years is still a long time lol
it's even less than 20 years, haha ๐
as a developer you should be learning what's new
keep in the loop and stay trendy
i mean web is here since 2010 at least right?
and also clients dont even know how to use GPT-3 so we're good for now
That will never replace web-dev
web dev has been existing for a long itme
and all GPT-3 does is frontend, it can't help you build more complex stuff
idk dude but i think for now is a bad sentence wtb after 5 years
There's wix, there's wordpress, there's shopify. How come web-devs are still getting salaries > $100K? Because they can create intricate and personalized solutions. You can't do that without coding.
im sure after at least 2 years everything will change lol look at wix
lmao wix is just a static site builder
Anyways im just looking forward to the future
bc im asking is it worth learning its stuff
web dev is not the only path, theres a lot more you can try, but web dev is not dying
they're different stuff tho
not really
like express.js and django?
yep
more opportunities with node.js technologies
the way you use it
but yeah django is better
like app dev and shit?
sorry i mean app dev and ml maybe
unless you like math ML won't be enjoyable
app dev like what? desktop apps? games? or automations? or a software?
but always give it a try ๐
app dev like android ios and maybe desk stuff windows maybe
web dev is also a form of app dev i think, if you actually apply some backend stuff
iv learned some SQL for ML before and it was hard af
even tho it doesnt need that much math but still
it does lmao, if you actually get into it
u mean SQL ? or ML ?
ML is more related to Computer Science comparing to web dev and shit
ML
yeah and shit. i know lol
im talking abt SQL its kinda not that much maths in it but its kinda tough still (
if you're tlaking about some simple app dev, it just require you to have some knowledge in the tools, but computer science is where the math is
Algorethim and shit right?
yes, like problem solving and approaches to solve stuff with programs