#web-development
2 messages Β· Page 32 of 1
@vagrant adder can I pm you so I don't clutter the channel?
I have a few questions if that's ok with you
@vagrant adder I get this error:
[SQL: INSERT INTO todo (content, "isCompleted", user_id) VALUES (?, ?, ?)]
[parameters: ('hello', 0, None)]```
This is my models now:
```class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True)
email = db.Column(db.String(50), unique=True)
password = db.Column(db.String(80))
todo_items = db.relationship('Todo', backref='user', lazy=True)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(200))
isCompleted = db.Column(db.Boolean)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)```
just a sec
ofc
did you do db.drop_all()
yeah
The problem is when I'm trying to create a todo item
if form.validate_on_submit():
new_todo = Todo(content=form.content.data, isCompleted=False)
db.session.add(new_todo)
db.session.commit()``` This is the code for adding tasks
@vagrant adder Oh yeah
Do you know if flask_login has a good way to get the users id?
Isn't it something like current_user.id?
yes
@vagrant adder I get this error SyntaxError: positional argument follows keyword argument
db.session.add(new_todo)
db.session.commit()```
Nvm fixed it
I'm just dumb
nice
anyone know if it's possible to build Q objects dynamically in Django?
for example if I have a list of fields I want to OR together like Q(exchange='blah') | Q(exchange='otherblah'), but exchange is a string in a list?
nevermind - got a solution - thanks anyway!
Is anyone nice enough to help me out with some django? I'm attempting to add a simple dropdown select menu where I have a list of all the choices already. I'm having issues figuring out how I can put the menu on the page and how to retrieve the data from the field.
Maybe model choice field?
yeah I'm trying to figure out how to use it
Anything I see online is either super basic or not what im trying to do
what im trying to do is make a dropdown menu, and then have a button that adds that selection into a list on the screen
@marsh canyon if you understand what I want to do could you send me a pm?
or anyone else
Sure, i will look into it a bit, just woke up π
Drop down menu in html can be done using section
Or
Lemme do some research
thanks, im about to go to bed actually so could you pm me anything you have?
Hey guys, How do you guys manage PKCE authentication? especially in Django?
Strange issue, getting __init__() should return None, not 'coroutine' with the following:
class User(Object, UserMixin):
_name = ''
_id = ''
async def __repr__(self):
"""
Output:
User('username', 'username@example.com')
"""
return self.__class__.__name__ + '(\'{0}\', \'{1}\')'.format(
self.username,
self.email,
)
async def __init__(self, email, password, username, *args, **kwargs):
self._id = username.casefold()
# Mandatory
self.email = email
self.set_password(password)
self.username = username
# Optional
if 'name' in kwargs:
self._name = kwargs.pop('name')
async def set_password(self, password):
self.pass_hash = bcrypt.generate_password_hash(password)
async def check_password(self, password):
return await bcrypt.check_password_hash(self.pass_hash, password)
@property
async def id(self):
return self._id
@property
async def name(self):
return self._name
@name.setter
async def set_name(self, value):
self._name = value
Any ideas why I'm getting this?
You cannot have an async __init__
if you want the same kind of behavior, you must implement an async __new__
Alright, cheers buddy
How do I set a default value for a WTForm?
Hello here
import os
ENV = os.getenv('GLITCHYWARE_ENV', 'dev')
if ENV == 'dev':
print('DEV')
from .dev import *
elif ENV == 'prod':
print('PROD')
from .production import *
This is the content of an init.py file
It's supposed to get an environment variable and execute a file according to it.
But both files are executed.
Here
It prints 'PROD' only, so it means that ENV == 'prod' and the first if is skipped, but for some reason it runs the code in dev.py
I'm using Wagtail a Django based CMS and deployed it on Heroku for information.
looks kinda like .production imports .dev ?
I have a list of all objects and I want to just display a delete button that I can click that would delete that entry in the DB, I can't for the life of me figure out how to do this
Still need help? @modest garnet
u need to use a backend framework to do that :/
well u will be storing the data in a database
the user will make a post request which will be captured by a function
lemme link u to a resouce which can explain better
While the front-end consists of everything the user interacts with directly, the back-end is the critical behind-the-scenes component behind every web page y...
Hello, guys, how to implement oauth2 with pkce ???
Hey folks. I want to store product info in a database in my flask project
Using sqlite and flask-sqlalchemy, I've got a little Model set up:
class Products(db.Model):
__tablename__ = 'products'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=False)
overview = db.Column(db.Text)
def __repr__(self):
return f"Products('{self.title}')"
So if I wanted to store multiline paragraphs in that field, are there any caveats/best practices I need to know about?
@hollow glacier
I'll show you when i get home
@pliant hound
Class name put in singular, and remove __tablename__, sqlalchemy does that for you by putting it in singular
Sorry- what do you mean by put it in singular @vagrant adder ?
class Product(db.Model):
Oh. Right I see
But other than that, It should be smooth sailing?
I'll be able to store multiline strings in the overview?
Yeah
Wicked. Thanks fella π
Will do
A book I'm reading sugested I define tablename because sometimes SQLAlchemy can get confused?
Nope
Exactly different
Sqlalchemy shits itself when users fiddle with tablanames
π
yo what do you guys think about DJango in comparison to ExpressJS?
is Django any better
honestly trying to get into Django so i can strengthen my python skills, a friend of mine told me a while ago he like Django better because it takes care of so many things for you
Express is a poorly documented pain in the arse
Assuming you want to do a standard CRUD web app then Django is a pretty good choice IMO
@rigid laurel but whatβs so good with Django though
Well, if you want to do Python web development, you have two options: Flask, or Django
Flask is a more lightweight option where you have to pick and choose exactly what you want, whereas Django is opinionated and does a lot of things for you
the main difference being that Django has an ORM (Object relational mapper) built in for database stuff where Flask doesn't
flask is like race car, you have to add some stuff to it
and django is like a lambo
But, both options are vastly better than JS
why what about sailsjs should I know about
ima try out django later tho
Iβm bored of express and JavaScript
Js can be an advantage if ur also a front end dev? I maybe wrong
Btw can anyone explain what can a front end frame work do?
JavaScript is necessary if you want to make a modern front end. But it isn't great for anything beyond basic backend stuff
Isn't regular js enough for a modern website? What do these front-end frameworks like react add?
A JavaScript framework is a way you can make a responsive application on the web. They generally handle the rendering of the actual HTML on the page rather than just letting the browser make a request, that way you can have the page change without refrsehing
So like live searches before I hit the search button?
I mean i am typing in the search bar and the results appear as I type
Yeah, thats one example
Can't that be done in regular js?
It can, but when you're doing a million similar asynchronous things then it becomes much easier to offload that work to a framework
Yes I know Angular already but Iβm bored of node lol
Okay, thanks for the info mate @rigid laurel :)
Especially if you end up with complex state that you need to manage
Oki
I have been wanting to learn JS from a long time but never really started, haha
Diving deeper into css
Did you check the docs on the library to see what those errors could be
Usually they have it listed
Sadly not.
Does the thing work if you try using it in a basic script file like without flask just the library
yes
Anybody know why this instantly closes?
from sanic import Sanic
from sanic.response import json
import asyncio
app = Sanic()
@app.route("/")
async def test(request):
return json({"hello": "world"})
async def startServer():
await app.create_server(host="0.0.0.0", port=8000)
def main():
asyncio.Task(startServer())
if __name__ == "__main__":
main()
asyncio.Task()'s do not guarantee complete execution, you would need to have an event loop actively running to make sure it stayed alive long enough to be processed
Can someone explain to me how to get Json stock data from IEX api?
Hey
Can anyone help me with flask...i am working on an API and got stuck in authorisation endpoints
ask your question and people will answer if they know it
I created this test file but when i run test JSONDecodeError is showing up....shall i paste the code so you can see what's the error ?
Yeah i'd like to see the code and full traceback
I am having a little problem in my django project on implementing likes and dislikes for a post, kinda complicated to explain, so is djangoner free to voice chat?
Not home :|
I need to make an application that i can give in dimensions in pixels and then it makes a window with a coordinate system in it(2D) and then i can give in an x and y and it puts a dot on that point. how would i go about doing this. i have some knowledge in python so i would like to do this in python. anyone have any tips?
it would be an web app
@native tide
As instructed in #help-<int> you can not make a web app in python.
Browsers do not suppot python language
https://medium.com/free-code-camp/structuring-a-flask-restplus-web-service-for-production-builds-c2ec676de563 @vagrant adder this is the link pls take a look.... Everything works fine except two things first running test after creating file auth_test.py and logout operation in swagger documentation
the way i see it is compute the dimensions in django based on request, and respond with the needed dimensions for js canvas
and make js render the graphics.
Am i the only one using flask here?
so i would need to use js to make it?
for web app yes
The only thing Flask or Django can do is render static HTML/CSS
the use of them is to load data or logic from a server into that static page
but it doesn't change the page after it has been rendered
no matter what you will need JS if you want to change the page at all after it has been initially loaded
guess il have to learn js then
REST API
adding Django or Flask into the mix is pretty pointless
and some form of REST for Django or Flask.
Backend here is not that important
What is a good language to make front end for APIs developed using flask?
the REST api adds no value to Hydrovo's problem
ReactJS, VueJS are two highly reccomended front end libraries
if you want to store the values??
Cool
nowhere has he mentioned that he wants to do that
and even if he did want to store the values
you can send them from frontend
it makes more sense to write hte javascript first
Can anyone look into my problem?
ReactJS, VueJS are two highly reccomended front end libraries
Not that...the link above it
@native tide
JS create app first and then you can decide latter if you need a backend or not
what is the actual problem @supple loom?
are you just using the code verbatim from the github repository?
Well i did some extra....but i am sure i didn't modified that part and it should work
The link doesn't tells to run tests...but since i added i naturally ran to check whether it's working or not
There is one more problem i mentioned above
The logout endpoint.....login is working fine...
But logout says please provide a valid authentication token
Say something
Check the link once
I'm afraid I'm not willing to install this random repository to see where the problem might be
and I can't really help just by looking at this code
Yeah...one needs to run to see what is actually happening
And i am sure you will run through the same error
I have posted screenshots in the issue section of same github repo
The link i send is just an article in which he has taught
so i have a django backend and django templates being served with csrf tokens in the POST forms to add models.
but i've made a vue frontend that queries the GET endpoint (only one in my app) and i'd like to add functionality to create records with it as well, but if i try to make a form, i get the error at not having a csrf token or whatever. what's the 'proper' way to do this?
Mention me if anyone checks on mine...thanks
@mint shuttle
On your POST method from VueJS you need to send the CSRF token along with POST data.
I have not done this in a long time but i can search for a proper method in my archive
CSRF is in the cookies
ok that makes sense, how do i get the csrf token? for my situation should i just disable that protection? (it's just an example thing, i don't have any sort of user authentification, and i just assume that everyone in the world has the same data to keep track of/there's only one person?)
url : 'YOUR_URL_HERE',
headers: {'X-CSRFToken': $.cookie('csrftoken')},
type: 'POST',
dataType: 'json',
data: {}
if the token is not there you need to create a method to retrieve it from django
i do not know how you setup vue to work with django
best way to find out is to load the index page and check it with browser developer tools if you have that cookie
ok, ty for the info! i think that'll be enough for me to have direction with my searches now (i was just getting a bunch of stuff on what csrf protects against and stuff, not practical stuff)
right now it's not really. i'm just using axios to send http requests
you are wellcome
although i think... it might be bed time right now lol have a good night!
Night
Within Flask is it possible to make something happen without editing every single route? So I can add a suspend function to user without adding a statement on all my routes.
Before request I think is something that can do that
https://stackoverflow.com/questions/34164464/flask-decorate-every-route-at-once is essentially the same problem
Do you know any Rich Text Editors for Django, that can be used for free commercially and dont have to pay for licence?
Oh, I found it
You can modify, integrate and use the Open Source CKEditor 4 and the Open Source CKEditor 5 in your commercial websites and products for free as long as our source code and your modifications remain open and accessible to others under the same Open Source license terms.
I have used tinyMCE, and CKEditor 4 and 5
MCE is alright and functional. CKEditor is better, in my opinion, but be wary that they have significantly changed things in ckeditor5 so that it no longer supports html source view
in CKeditor 4, we could write harmful html source code, could that be the problem
Well if it goes to customer, he doesn't need html view
Whether harmful html makes it through your editor onto your templates is a template design problem. My use cases required HTML input, however, so that was not an option
Django automatically escapes out html tags, unless you mark it with |safe, which disables auto-escaping
I didnt use CKeditor for the reason that someone could make alerts, I only used it if it was behind password
Yeah
|safe is a must, otherwise it shows html tags too
Well, I think its allowed to use CKeditor 5 on commercial websites
I sent them email just to confirm
If you want to use user-edited html-based code on your site, I'd point you towards https://github.com/marksweb/django-bleach
Which you can use and configure instead of django-safe, to only allow some tags
CKEditor 4 is distributed under three copyleft Open Source license options: GPL, LGPL and MPL.
CKEditor 5 is distributed under a GPL 2+ copyleft license.
It links to the GPL3, so I would suggest not using it for a commercial program in my limited experience, or at least discussing it with someone who is knowledgeable about licensing
Anybody know how to get user input into forms using Sanic? Here is the code I currently have in the main py file;
@app.route('/data', methods=['POST'])
def handle_data(request):
cid = request.form['cid']
print('cid')
And here is the html:
<form method="POST">
<input type="text" name="cid" placeholder="CID" action="/data">
</form>
But whenever I send the user input, the page in my browser then says; Error: Method POST not allowed for URL / & in console I receive the error:
[2019-10-02 16:58:21 +0100] [17566] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/'
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/app.py", line 920, in handle_request
handler, args, kwargs, uri = self.router.get(request)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/router.py", line 407, in get
return self._get(request.path, request.method, "")
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/router.py", line 447, in _get
raise method_not_supported
sanic.exceptions.MethodNotSupported: Method POST not allowed for URL /
[2019-10-02 16:58:21 +0100] - (sanic.access)[INFO][127.0.0.1:50035]: POST http://localhost:8000/ 405 40
@peak thicket action is set on the <form tag, not the inputs
Thanks but now I get:
[2019-10-02 17:07:58 +0100] [40530] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/data'
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sanic/server.py", line 442, in write_response
response.output(
AttributeError: 'NoneType' object has no attribute 'output'
[2019-10-02 17:07:58 +0100] - (sanic.access)[INFO][127.0.0.1:50162]: POST http://localhost:8000/data 500 28
that's an error in your server code somewhere, you haven't shared it so I don't know what's wrong
That specific error I believe is that you are not returning a response from your code, so perhaps that function needs to return an httpresponse
from sanic import Sanic, response, request
from sanic.response import json
import fortnitepy
app = Sanic()
cid = ""
@app.route('/')
async def handle_request(request):
print('/')
return await response.file('buttonclicker.html')
@app.route('/data', methods=['POST'])
def handle_data(request):
cid = request.form['cid']
print('cid')
@app.route('/skin')
async def handle_request(request):
await skullTrooper()
return await response.file('buttonclicked.html')
#if __name__ == "__main__":
# app.run(host="0.0.0.0", port=8000, debug=True)
client = fortnitepy.Client(
email='',
password='',
net_cl=''
)
@client.event
async def event_ready():
print('----------------')
print('Client ready as')
print(client.user.display_name)
print(client.user.id)
print('----------------')
await app.create_server(host="0.0.0.0", port=8000, return_asyncio_server=True, debug=True)
client.run()
Yes, you need a return response.etc for your post too, since when the browser submits the form it uses the response from the post request as the html to display
Thanks!
It works but /data never loads, it just says waiting for localhost and load forever.
Stopping me from doing anything on the website like click links as well.
Nevermind after like 5 minutes it says: Error: Response Timeout.
Fixed it by exiting debug mode.
something i've never seen in a django project that just came up -- test data is being written to the live (well, dev, so, it's kind of ok?? but still) database.
database test_appname is empty, but database appname has a bunch of extra rows with data from factory_boy (using --keepdb to make it easier to inspect what's happening)
if i run tests for an app without --keepdb, and connect to test_appname via psql, it cannot delete the test database, but it still has not written anything to the test database.
new rows have appeared in the "live" db instead
How tf do I make a button be stuck to the right side of the page?
I've tried float right & pull right but neither work?
Don't use weebly.
Use herokuapp.
I think the websites run 24/7?
Hi all
Can someone help me with my training Django project?
Somehow I have to reactivate my venv every time I launch pyCharm, and even after that, when I run commands in shell, it tells me that I have to specify environment settings. Despite website and all of its functions working fine.
I've been working on it for several months now and not sure how I managed to break it tbh.
@peak thicket
Free tier at heroku goes to sleep after 30mins of inactivity
I need to know what all APIs i need to create to make a basic movie ticket booking system.
@dense slate We talked about HTML rich text editors, Not code editors
I am using flask, and I wish to redirect to a URL and pass along URL params or other vars using redirect. How could I do that?
I've seen it before im pretty sure i just cant remember where
return redirect(url_for('some_func', form=SomeForm(),name=some_name))
@opal radish ^^
Hello
Hi
Alexa what's the weather like
How can I add sanic to an already existing loop?
hey guys, i have a django project, its a social media site where users can post stuff. I also have likes for a post. A user can like a post which is from other users. So when i click on like button, the page refreshs and goes back to starting. I dont know js yet but it will be cool if anyone could give me a code snippet which i could use for not refreshing the page when someone clicks on the like button
u can make a PR to my django repo if u want to
do you have the endpoint set up in Django to handle the AJAX yet?
i guess not, not sure how AJAX works π
So what you want is a button on the webpage that the user clicks that will do something with Django models to say that X post has been liked by Y user?
and the button doesn't refresh the page
the button is functional and like feature is all working, the only problem is the page refreshs and goes to the top
kinda yea, on clicking the button, page should not refresh
kinda like a instant update?
in posts app
there are 2 templates
detail-post.html
display-posts.html
and u can see the view in views.py , should be the last one i believe
so depending on the user if he/she has liked the post, i change the icon, like solid thumbs up if likes and outline if not liked
I'm not familiar enough with Django - def like_view(request, slug, destination): does that handle a get, post, or any request?
get
it handles when someone clicks the button, the button is basically <a> tag, which goes to an endpoint handled by like_view which again redirects the user to the same page making it refresh
I'm not sure on the correct way to do AJAX with Django is the thing. But from the JavaScript side its relatively simple.
what you want is a new view, or just rewrite like_view that returns a JSON instead of HTML. Then the JavaScript will make the AJAX request, which can be almost as simple as fetch('http://your-domain/like_view');, and make any necessary visual updates to the page
I'm not familiar enough with Django to know the correct way
ohk
and the JS kinda depends on the specifics of teh Django
oh
but someone who knows Django can probably explain it better than me. The actual JS side of this problem should be relatively minimal though
is there any models field that I can use to only get number but it can start with 0
because when i use IntegerField it keeps removing the first 0 which something that I need it to be shown
Django
If Iceman is still looking, or someone else is trying to figure out how to do this
You bind an event handler to your "like" link, that sends an ajax request to your server. It may first increase the vote count, or it might wait for a response before increasing it or setting it to the new number (if it has changed server side since then). Jquery has some methods that make this easy, $.ajax(some_things). You generally have an endpoint defined for this, something like yoursite.com/post/like, and you do a POST ajax request from there. On the django side, you hook up the view to the post request, making sure that the post ID and other details you need (like authentication) are in place, which you should have already from setting up the precursors
The view would take the post request and handle "liking", and return a reply depending on what you want to do in the javascript (a JSON response with the new number of likes is an option that many use). The javascript then parses the response from the ajax request and updates the button
It'very easy
Can u PR plz
Hello, is there any way to manage user permissions in DRF?
I have a ModelViewSet of a Task model, and I would like it so only the user associated with the model can DELETE, GET, PUT or PATCH it, while any authenticated user would be able POST on the view.
Change the a href=url to a data parameter, and using jquery, you'd want the template to look something like this:
<a data-like="{% post.slug %}" ...>
$(document).ready(function(){
$("[data-like]").click(function(event){
$.getJSON('/like-this-url', { like-item: $(this).attr("data-like") }, function(data) {
$("span.count", this).text(data['count']);
});
});
});
Then you set up a view at /like-this-url, which takes a GET request with a parameter of like-item, does the "like", and returns a json result that includes an object with "count" equal to the new count
I don't actually have the spare time to fully tie it in, but that should be enough to get you where it ought to be workable
If you want it to be a post request you can adjust it to use this instead, which should just be a code rearrange:
(shamelessly stolen from stackoverflow https://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript )
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
I have a AJAX call that returns some JSON like this:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'v...
If you're looking for a more structured approach, you'd end up giving each of your "post"'s their own divs, which would then allow you to operate on them by id, which is the usual and easiest way of going about it
$() accepts css selectors, $(this) is the current element (in our case, the one being clicked), and if you do $("selector", this) you search under the current element
.text() changes the text
Hey ....how do i use column of one table in function of another table ....in sqlalchemy ?
Hello
hi
help pointed me here
Can someone help me with django and gunicorn?
i am using 18.04 ubuntu on aws ec2 instance
following this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04#creating-systemd-socket-and-service-files-for-gunicorn
DigitalOcean
How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu ...
i am stuck on gunicorn
pastebin coming
https://pastebin.com/8esEr4wa
Pastebin
ubuntu@ip-172-31-43-53:~/myprojectdir$ sudo systemctl status gunic...
gunicorn[11094]: ModuleNotFoundError: No module named 'website.wsgi'
i mean module exist why gunicorn cant find it
?
with
(env) ubuntu@ip-172-31-43-53:~/myprojectdir/website$ gunicorn --bind 0.0.0.0:8000 website.wsgi:application [2019-10-05 00:41:52 +0000] [11150] [INFO] Starting gunicorn 19.9.0 [2019-10-05 00:41:52 +0000] [11150] [INFO] Listening at: http://0.0.0.0:8000 (11150) [2019-10-05 00:41:52 +0000] [11150] [INFO] Using worker: sync [2019-10-05 00:41:52 +0000] [11153] [INFO] Booting worker with pid: 11153
works fine
here is my gunicorn config file
Hello, people of the internet
Can someone please help me understand json requests? I feel really dumb but I for some reason I can't even find a proper tutorial on google.
For example, rn I'm trying to find how to add headers and all I can find are either specific API documentations for google and atlassian, or SO threads with errors.
While I'm trying to find general information on how to do it.
requests.get("https://google.com", headers={"User-Agent": "ME"})
Ok, thanks
But can you perhaps recommend a tutorial or article on how to json?
Also, since i'm working with Django, I get ALOT of rest framework info that I don't need rn.
requests with json. In particular, sending api requests to third parties
I guess requests then
This seems like a decent general introduction
it is python specific though
(REST requests are language agnostic)
As long as it's a general guide and not related to a specific API or rest framework
Since I want to understand the concept first, before moving on to rest
REST is the concept though...?
But that's a framework...
REST is not a framework
Essplane pls?
REST is a concept of represeting methods of getting, modifying and deleting data
it is implementationless
The guide I linked above does a decent job of at least introducing the concepts of what REST requests are when appropriate
Ok, I'll read it
@native tide I believe your issue is that your wsgi file is in /project/project/wsgi.py, and gunicorn is being told to look under project/wsgi.py. Your manual run starts in myprojectdir/website, not myprojectdir. Also, you didn't actually post the gunicorn config file, so I can't confirm that suspicion.
I just say your #help-orange post, pretty sure what I said is correct
Also, for some reason, your lines have 183 spaces at the end
Hi all again
I have another question regarding Django.
I have a webpage with a form. Upon submit, it sends form data to the db, and also when pressed, js opens a "thank you" modal window. There's a method that checks submitted form and I'd like to return the result into that modal window, essentially to js so it can print it in that modal window.
How do I approach this task?
I assume I should do it with json, but that's just a guess, so I'm asking here.
Hello I have question, how do I connect React.JS and Flask in my project ?
I am creating a simple To Do App
well, you have to run your api and frontend processes separately and figure out how to make requests with js
oh alright, so I create web UI and HTML shit with React JS and Flask is there for DB connection and handling logic for API ?
@vagrant adder
well, you can integrate both react and flask into one server just like one of my classmates did
one server ?
wdym by one server ?
Just like start Flask or you need React and Flask working at same time ?
@native root Thank you for answer, ill was afk and managed to solve it myself, problem was "working file" part of gunicorn configuration!
Thank you mate
Allo
So I'm making a flask app
and it includes some modules that "do a thing", for instance there is a module that text to speeches a lump of text to an MP3, and there is another module that converts e-books into a bunch of snippets for text to speeching
what should I be calling these 'modules that do stuff'. I feel like they should go in a folder in my project structure
I was thinking that the folder could be called 'services'
but that's probably not right...
usually the folders are named after a design pattern. What is a design patterny name for 'classes with a specific responsiblity'
I'm feeling like the correct answer might be 'your libaries that do stuff should be in their own repos, so the flask app can just be a flask app, install, import and use them'
My opnion, services is just fine. Since that is what they are, services provided by your flask app. Separate repos is probably overkill for them--they aren't going to change rapidly, and are probably not big enough to be worth the management hassle
There is a balance to be struck between complexity and modularity. One end leads you to massive files, slow processing times, spaghetti code, and unmanageable branching and merging. Too far towards modularity and python begins to look and act like Java-tons and tons of boilerplate, modules that do nothing but import other modules and call singular functions
The reality is, if you go too far either way maintainability begins to drop
thanks, sometimes it's nice to have permission from the internet to call things stuff
I ended up trying to fix a firefox pluggin that was written as one of these... apps with classes implimented as one big file full of functions that do stuff
and it's much worse than I remembered
by slicing things up, you hopefully end up with really small scopes and not many variables in them. I think this, horrible lump of javascript I was staring at would have seemed normal back in the day, but having got used to "functions only use variables that turn up as parameters, no global variables"
There is an optimal amount of complexity that ought to be shown on screen and considered at once. You can spread it out via classes, and abstractions, and you can bring it together with long procedural functions with variables
turns out a variable that belongs to a class is really just a global if your class is big enough
@native tide i agree with bast, i'll call them services
but don't isolate them from your flask app tree
Can I design my flask application like this: https://gyazo.com/b5ff6ccd04ecf95b8dffaded338042e3
using blueprints
is there a quick guide to django? I checked pinned messages dont see one
U can check out YouTube tutorials like Corey, freecodecamp, coding entrepreneurs
Will do, thanks
Someone help me with models in sqlalchemy pls
I made a model in which i created three tables
I am having problems in creating relationship and putting data in those models
What kinds of problems, and what kinds of relationships?
:incoming_envelope: :ok_hand: muted @supple loom until 2019-10-06 06:58.
!unmute 449446855491846145
:incoming_envelope: :ok_hand: Un-muted @supple loom.
you got muted by our spam filter for attachments
for long pieces of code, please use
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
^ that website
Ohh
Sorry
And thanks
this is the model code
and this is the service code
i am trying to achieve one to many relationship on two level
Does anyone have any idea as to why my flask session variable is being reset in between requests?
I modify it, print it at the end of the request and see the difference, however at the start of the next request it has reverted
Looks like I had to set session.modified - True
Can anybody help with Flask blueprints?
Currently getting an error AttributeError: module 'blueprints.general.login' has no attribute 'name'
post the code
app.register_blueprint(login)
from flask import Blueprint, render_template
login = Blueprint('login', __name__)
@login.route("/login")
def login_func():
return render_template('login.html')```
@fossil swift how does ur folder structure look like?
hi guys, Im reading book TDD with Python and got to the chapter 16 where the author recommends Javascript: the good parts book for complete beginners in JS. It's from 2008, but the recommendation was written in 2015. Is it still not outdated?
config.py,database.py, init and TODO are all in templates folder
get them out and rename init.py to __init__.py
is there much benefit to using libraries like flask-bootstrap as opposed to just setting up the static imports manually?
yeah
i would rather link it on frontend since those miliseconds aren't noticeable
and flask-bootstrap just adds complexity on the backend part
Is there any benefits for using Flask or Django besides Flask is easier to learn?
easier on resources(not something you should twist your head for)
flask's ease of use is just something django can't beat
it's modularity is good too
if my goal in using flask is to just quickly throw up webui's for some python code I'm running in the background (in other words, personal tooling and not public web facing)
any relevant libraries I should take note of?
Depending on how usable you want the UI to be, probably a lot of JS stuff you should be aware of like possibly ReactJS or Jquery
Can't escape the JS π’
blargh
so i have a table to keep track of a many to many relationship between two other tables, all using django to form the modles.
I have a modelform that lets you make the assignments to populate this table with the proper relationships
but currently it uses a drop down and shows modelobject(n) instead of something like the object's name. but I'm not finding the right search term to have this expose model.name instead of model.id. any ideas?
i feel dumb, i just had to implement str
hi everyone
hi evryone
any one using django
btw i am trying to deploy django web app on heroku
but there is error
when i try to push on heroku master
weather_app) C:\Users\Deepak\Desktop\weather>git push heroku master
Enumerating objects: 174, done.
Counting objects: 100% (174/174), done.
Delta compression using up to 4 threads
Compressing objects: 100% (170/170), done.
Writing objects: 100% (174/174), 574.03 KiB | 2.02 MiB/s, done.
Total 174 (delta 40), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to deepweather.
remote:
To https://git.heroku.com/deepweather.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/deepweather.git' ```
please help me
A requirements.txt must be present at the root of your application's repository to deploy.
To specify your python version, you also need a runtime.txt file - unless you are using the default Python runtime version.
That's the error message you get when you forget to specify requirements.txt
now i am getting
something different problem
when i try to run app on heroku i am getting ```
2019-10-07T08:26:19+00:00 app[api]: Build succeeded
2019-10-07T08:26:32.789867+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=deepweather.herokuapp.com request_id=2d66b796-1c62-411b-a10b-47ff03436c08
fwd="42.109.196.154" dyno= connect= service= status=503 bytes= protocol=https````
Use a Procfile, a text file in the root directory of your application, to explicitly declare what command should be executed to start your app.
Currently you aren't, so it's not running any applications, and thus you get that error
hey guys, I just change all my hardcode link on html into django url {% url 'homepage' %} ...The thing is how to navigate with django url that works just like http://127.0.0.1:8000/#hotel-container
hey guys ....i am getting data in list of registered users while nothing in list of registered theatres
this is swagger documentation
@primal drift i am really beginner, but have you tried {% url 'home' %}#hotel-container
i registered user and it's data shows in list of registered users....the same way i registered theatre but the data is null in the latter case
@supple loom What are you using, Django or Flask?
flask bro
i structured both the same way but i don't understand why there is no data
Side note: screenshots are awesome
sorry.....they are downloaded from whatsapp actually
Hi all
I have some weird problem with launching my website. It works fine except it won't update html content after git pull
I have restarted the server itself, nginx and gunicorn and checked that files are actually new. And it still shows the old version.
Can someone help me find what I 'm missing please?
If you have not done a full refresh, it's likely the browser is caching the old files
On desktops, control-shift-r, or shift-f5, of cmd-shift-r triggers a cache-refreshing reload
On mobile, you'll generally have to go into the browser settings and erase the cache
Refreshing with cache, it became a habit once I got into web development XD
Also tried in another browser
@native root
Do you have cloudflare between you and the app?
nope
What are the headers you're getting from the server?
You can find those in a network tab of some dev tool in the browser
Hm.... where exactly? can't see them
can you make a screenshot? I'm using FF and Chrome
response:
HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Tue, 08 Oct 2019 03:26:17 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Frame-Options: SAMEORIGIN
Vary: Accept-Language, Cookie
Content-Language: ru
Content-Encoding: gzip
request:
Host: 93.85.88.35
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,ru;q=0.8,ru-RU;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
odd
Well, I think with that we can probably rule out a user-facing cache
Which means that nginx probably is serving up the old files
the question is why
Something up with your nginx.conf, maybe?
Hm... idk. last time I checked everything was fine. And I have actually been updating code with git pull before.
What's the systemctl status of gunicorn?
The question is whether the restart of gunicorn failed, which could leave it running the older versipon
That would put errors in the logs if it's configured correctly
hm
and failed: 0
I did restart the whole machine after all
and after that I had to restart gunicorn anyway. didn't set it up for auto launch
uh... how do I quit status?
control-c?
@native root can you please take a look at my issue
Oh no wait... now I have old files
Yay we found the problem !
apparently project did't get updated for some reason, even though it's been raising migration error when I tried to launch it earlier without migrating
That's weird
@supple loom post your current code for the result fetch?
odd
And how did you add them?
lemme show u
Just to be clear, I have to activate venv, then git pull, then run migrate and collectstatic, right?
def get_all_theatres():
return Theatre.query.all()
def get_all_users():
return EndUser.query.all()
both in different files
in their respective service
but the data is null
in theatre
i will try one thing
will ask u if that doesn't works
Make sure you've run makemigrations or are committing your migrations too
Those requests seem fine, what's the code you're using to create the theatre and user objects?
def save_new_theatre(data):
theatre = Theatre.query.filter_by(name=data['name'])
if not theatre:
new_theatre = Theatre(
public_id=str(uuid.uuid4()),
name=data['name'],
description=data['description'],
base_price=data['base_price']
)
save_changes(new_theatre)
response_object = {
'status': 'success',
'message': 'theatre successfully saved ',
}
return response_object, 201
else:
response_object = {
'status': 'fail',
'message': 'theatre already exists.',
}
return response_object, 409
def save_new_user(data):
user = EndUser.query.filter_by(email=data['email']).first()
if not user:
new_user = EndUser(
public_id=str(uuid.uuid4()),
email=data['email'],
username=data['username'],
password=data['password'],
registered_on=datetime.datetime.utcnow()
)
save_changes(new_user)
return generate_token(new_user)
else:
response_object = {
'status': 'fail',
'message': 'User already exists. Please Log in.',
}
return response_object, 409
def generate_token(user):
try:
# generate the auth token
auth_token = user.encode_auth_token(user.id)
response_object = {
'status': 'success',
'message': 'Successfully registered.',
'Authorization': auth_token.decode()
}
return response_object, 201
except Exception as e:
response_object = {
'status': 'fail',
'message': 'Some error occurred. Please try again.'
}
return response_object, 401
have used token base authorisation in user
You're missing .first() in the theatre code
still null
theatre = Theatre.query.filter_by(name=data['name'])
vs
user = EndUser.query.filter_by(email=data['email']).first()
did that
You've run the creation code again, to populate the db?
π
What happened is a query object is probably not falsy, so not query was always returning false, and therefore never adding anything to the database
what does error means....."message": "Failed to decode JSON object: Expecting value: line 5 column 17 (char 73)"...
https://paste.pydis.com/ocinezezoq.py this is my database model ...........if it's allright then i want to add the primary key of theatre into it's data which displays in list of theatres.....how can i do that?
I started a graphic design and web development studio and we are looking to expand our logo, identity, and web design portfolio. If anyone you know needs any creative services, we would always appreciate a referral! Check out our website at https://sleepycloud.me Thanks! UwU
mhm, so this is a commercial service?
@bpi.route('/<public_id>')
@bpi.param('public_id', 'The audi identifier')
@bpi.response(404, 'audi not found.')
class Audi(Resource):
@bpi.doc('get an Audi')
@bpi.marshal_with(_audi)
def get(self, public_id):
"""get an audi given its identifier"""
audi = get_an_audi(public_id)
if not audi:
api.abort(404)
else:
return audi
@bpi.route('/theatre_id')
@bpi.param('theatre_id', 'The theatre id')
@bpi.response(404, 'audi not found.')
class AudiT(Resource):
@bpi.doc('get an Audi in a theatre ')
@bpi.marshal_with(_audi)
def get(self, theatre_id):
"""get an audi given its theatre id"""
audi = get_audi_theatre(theatre_id)
if not audi:
api.abort(404)
else:
return audi
same function but i get this error (TypeError: get() missing 1 required positional argument: 'theatre_id') in Audit function
AudiT class
can someone tell why?
You are not capturing the theatre_id, but adding the word theatre_id as the actual route/url:
@bpi.route('/theatre_id')
vs
@bpi.route('/<theatre_id>')
I think that's it
I'm not sure what you're using, though, but that looks different
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. You have requested this URI [/Audi/1] but did you mean /Audi/<theatre_id> ?"
i did what u said
now it's this error
idk where i have requested this URI [/Audi/1]
Wild guess, but you may need to have two different endpoints, one for the top function /<id> and one for the lower function /audit/<id> (or something), since otherwise it can not differentiate.
nice. which package are you using? I don't recognize it
right, I was just thinking that.. I've never really used flask and only ever used the @app.route standard form
With Django, I frequently have models with FileFields or ImageFields. When the model is deleted, the files are not deleted automatically. This means that for each model, I need to listen for the post_delete signal, and iterate over the files and delete them from the storage backend. This results in a bunch of the same function, but with different fields and listening for different senders, which is easy to forget to update if I change something. Is there a better way to handle this which would attach the logic to the model itself?
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.delete gives the recommendation of a custom management command to purge orphaned files, but I can't find an example of this
with django:
I have a model for items(cyphers) and a model for decks (lists of cyphers) its a many to many relationship.
I have DeckCypher which assigns cypher and deck ids.
I'm trying to write code that will generate a json object where the key is the deck name, and the object is the cypher. I have
data = {}
for k, v in DeckCypher.objects.all().select_related():
if k.name not in data.keys():
data[k] = []
data[k].append(v)
json_data = json.dumps(data)
return Response(json_data)```
but it doesn't know how to unpack model.objects.all().select_related() and I don't know how to perform the join operation later if I wanted to just track the ids for the loop. Any suggestions?
Is your goal to select all pairs of decks and cyphers @mint shuttle ?
Here has a method of grabbing the ciphers, and attaching them to decks in a manner you could use to process them: https://stackoverflow.com/questions/4823601/get-all-related-many-to-many-objects-from-a-django-queryset
You can get a selection of Decks and all their component cyphers via Decks.objects.prefetch_related('ciphers').all(), with filtering wherever you'd want
If you can have duplicates, .distinct() is your friend
ooh ill check that link out and look into those methods ty!
π
How do I add custom fonts to Django ckeditor (Google Fonts ect.)
I found it! Here's the code if anyone needs:
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'toolbar_Custom',
'font_names': 'Roboto;',
'toolbar_Custom': [
{'name': 'Font', 'items': 'font_names'},
],
}
},```
I have a flask app and I have this custom Jinja2 extension ```py
from flask import url_for
from jinja2 import nodes
from jinja2.ext import Extension
class StaticfilesExtension(Extension):
"""
A class that allows serving static files in the format {% static 'file/path' %} over the built-in {{ url_for(...) }} method.
"""
tags = {'static'}
def __init__(self, environment):
super().__init__(environment)
def parse(self, parser):
next(parser.stream) # we have to call this
filename = parser.parse_expression()
return nodes.Const(url_for('static', filename=filename.value))
and it works as expected here ```html
<link rel=stylesheet type=text/css href={% static 'css/reset.css' %}>
<link rel=stylesheet type=text/css href={% static 'css/style.css' %}>
<link rel=stylesheet type=text/css href={% static 'fonts/Overpass Mono/overpass-mono.css' %}>```
but when I have this ```py
<source type=audio/mpeg src={% static 'sound.mp3' %} >```
I suddenly get a syntax error ```py
File "D:\wowe\yert.pink\yert\templates\error.html", line 35
)'/static/sound.mp3'```
any ideas on what is going on
the error is less than unhelpful
i've made a updated my website a week ago and i want to know your thoughts on this
what should i add and remove?
you might get more tracktion in #303934982764625920
@native root i just wanted to follow up and say ty. i was trying to manually work a join table and not just use a manytomany field but your guidance pointed me in the right direction. ty!
I got a problem with bottle.py. It somehow caches everything and is still showing files that I have edited 2 days ago. Can anyone help? Debug is set to True
https://paste.ofcode.org/33PB9B6TquhXZKg4CLGVdPB
Example: 10.10.10.1/:12 GET http://10.10.10.1:5500/js/render.js net::ERR_ABORTED 404 (Not Found) That was removed 2 days ago
HTML: <script src="js/render-plugins/bars.js"></script>
I am using the browser in incognito mode while doing webdev and this happens across all browsers installed, so I doubt it's that.
.hero-image-home {
background-image: url("images/sailaway.jpg") !important;
width: 100px;
height: 100px;
/* Set a specific height */
height: 50%;
/* Position and center the image to scale nicely on all screens */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: relative;
}
.hero-text {
text-align: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
}
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="hero-image-home">
<div class="hero-text">
<h1> Hello </h1>
</div>
</div>
{% for card in cards %}
<div class="card bg-light mb-5 mt-5">
<div class="card-header text-center h3 font-majormono">
{{ card.card_title }}
</div>
<div class="card-body">
{{ card.format_markdown|safe }}
</div>
</div>
{% endfor %}
</div>
{% endblock %}
The background image in .hero-image-home isnt showing
ive been trying to figure this out for too long.
If anyone has a clue, help would be greatly appreciated
I'm using django if that is important
Here is my base html as well https://pastebin.com/N1AkJZ4F
That wouldnβt work in your css, but your css is currently pointing the image at my site.com/images/sailaway, but the image is under your css folder tooβsite.com/css/images/sailaway
Or perhaps /static/css/...
If that doesnβt help, take a look in the dev tools network tab in your browser, usually gotten to via right clicking an element and βinspectβing
That will tell you the resources requested and received
That would, yes. Interesting.
It is possible your image is so big that βcoverβ causes it to get lost in unclear colors, but Iβm not sure
I think it is a fairly large image
well
it is 1920 x1080
when i hover over it in inspect element, it appears as 100x0 on the right
x0 means that it's not displaying because the height isn't working
This depends on what's inside it, but if you've absolutely positioned the text inside, the container will have 0 height, and not show the background
Can you review the source code i have above?
html {
/* To make use of full height of page*/
min-height: 100%;
margin: 0;
}
body {
min-height: 100%;
margin: 0;
}
``` I also have this if this matters
position: absolute;
If you want to center your hero text inside it's container
In all honestly I would suggest flexbox
ahh it worked it shows
?
yep
tysm I've been banging my head on this for a long time
nw!
I'mma point you here: https://yoksel.github.io/flex-cheatsheet/
but good luck!
tyty
Hi, I'm learning Web development with Python, and I stumbled upon this course from Real Python: https://realpython.com/products/real-python-course/
Is it worth the price ? Real Python is usually producing good articles, but the price is high so I need feedback.
Thanks
@rare notch The website itself is trustworthy, they have many useful articles. But I doubt there are many people who can tell you if that course is good.
Hi all. I have a question regarding launching an app on a live server.
I've tested it out on my local machine first, and everything seems to be working fine on live server as well except one feature. Is there a way for me to see full log, like I can see it in terminal on local machine?
That is not a simple question to answer
I already have backend ready
a api which responds to messages
but I cannot figure out the front end part
Still, the concept has so many variables
see here
when you click the chat application it opens a side bar
If you have backend ready, it's down to javascript to make front end
I wanna do that
yeah exactly
can you send a github or a tutorial link
where I can learn
I made AI backend
but I am not much into front end
JavaScript (), often abbreviated as JS, is a high-level, interpreted scripting language that conforms to the ECMAScript specification. JavaScript has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.
Alongside HTML and CSS, J...
JS is a language.
That I know
As I was saying, there's no simple answer to that
I wanna see some example code
where you can click on the chatapp logo in bottom down and it calls an API
and shows the response of API
You should try and look for webchat interface tutorials
That's probably the closest you can get
There are no ready-to-go out of the box solutions
Okay
Thanks
I'll see some tutorials
I found one
how ot oview pdf files
how ot view pdf files from s3 bucket
in webpage
is it possible
What might be a good (simple) implementation to track link/button clicks in Django?
Hopefully without using third party packages.
Django can't find my media files from ImageField
The is the media root when i print it
/home/kanelooc/code/personal/python-projects/youkaneduit-django/media/
Output when image isnt found:
Not Found: /media/blog_pics/4k-wallpaper-beach-bird-s-eye-view-2049422.jpg
Any idea what I can do to fix this?
Hey i've got a question about Django Admin
I have to create a page to make a new object (Intersticial)
but i have to call a special script when the object is created
what can i override to do that ?
@ripe mango Django signals ?
Hmm not really
the "script when the object is created" is to creating an other object lol
so its just one-line
Django signals allow that
yep but why using a signal ?
i can simply override the function called at the creation of an object
and insert my request to create a new object after the commit
so, the real question is: the function hmm
@ripe mango signals are functions created at the creation of an object
def add_view(self, request, **kwargs):
super(IntersticialAdminForm, self).add_view(self, request, **kwargs)
print("Adding new object.")
print(self.fields['add_subarea'])
this is good ?
Oh a form
Yepp sry
I thought you were talking about a Model instance
i have not mentionned that is a form
nop, i'm in the form /add/ on the admin panel of django
and after that, the object will be create π
So you want to add fields to the form right ?
hmm, i have self.fields that contains a list
and for all elements in this list, a new object will be created (in an other model of the form)
thats why i need to do that manually
What are these βnew objectsβ ?
The form is set on Intersticial model, and I have to create new objects in GeoExclude model
Okay, well in such case you have to work that in the form save method I guess
oh its save ?
Yeah, well to me that's save's responsibility
Or a Django signal if you want to generalize the behavior beyond that model's admin interface
def save(self, commit=True):
intersticial_obj = super().save(commit=False)
if commit:
intersticial_obj.save()
for geo_exclude in self.fields['add_subarea']:
# Creating here my new object
return intersticial_obj
what you mean of that ?
(edited)
Could you please explain what Intersticial and GeoExclude are, and why do you want to create GeoExcludes objects after Intersticial here ?
Hmm, ok
an Intersticial can have some exclusion
like if you want to exclude the France country
you can have a lot of exclusion
Please don't exclude my country
Les franΓ§ais s'excluent tout seul, c'est vrai π
aha
Intersticial model contains all informations relative to the intersticial.
GeoExclude model contains all country excluded, with a foreignkey to Intersticial
are you sleeping down on your keyboard ? π @unborn terrace
@ripe mango I was typing a long βsolutionβ but I just remembered something
Why not using inline forms ?
Well, inline admins*
hm what is ?
You'll get a nice dynamic form where you will be able to add all foreign-key associated objects you want
its mentionned "to edit", it work for add too ?
Yes
it sound really better lol
βto editβ is in the sense of βthat you'll be able to change in the form as any other formβ
Yeah, that's the βstandardβ one tbh
i will try first the method with save override
No please try this method first
π¦
That's much much less technical debt
my lead dev are not online aha
and im seeing he has already using inline method, so he know it
but he don't say me to use that
Whatever, if that suits what you want to achieve that's very probably the best way to do it
hmm im beginning on django
i don't know how to use this inline method
i have read the doc but it look complex
That's in the tutorial if I recall correctly
@ripe mango here you go https://docs.djangoproject.com/en/2.2/intro/tutorial07/#adding-related-objects
Hi all. I have a question regarding launching an app on a live server.
It works fine on localhost, and for the most part on live server as well. But one feature doesn't work properly. Is it possible to have terminal output like I have on local machine?
is django dev server single threaded or just single processor??
if you dont deploy it to apache or nginx
If anyone has any experience with POST/GET requests in python , let me know!
I'm trying to work out a sort of pattern a website is using to generate their links when adding an item to cart
Feel free to DM / Mention me as i'm AFK
@rigid lily multithreaded by default https://docs.djangoproject.com/en/2.2/ref/django-admin/
But you can disable multithreading
!ask @mild spade
Asking good questions will yield a much higher chance of a quick response:
β’ Don't ask to ask your question, just go ahead and tell us your problem.
β’ Try to solve the problem on your own first, we're not going to write code for you.
β’ Show us the code you've tried and any errors or unexpected results it's giving.
β’ Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
!ask If anyone has any experience with POST/GET requests in python , let me know!
I'm trying to work out a sort of pattern a website is using to generate their links when adding an item to cart
Or if anyone has experience with anything similar let me know thanks π
Asking good questions will yield a much higher chance of a quick response:
β’ Don't ask to ask your question, just go ahead and tell us your problem.
β’ Try to solve the problem on your own first, we're not going to write code for you.
β’ Show us the code you've tried and any errors or unexpected results it's giving.
β’ Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
@mild spade please read the text in !ask
That was for you
Especially the first bulletpoint
If anyone could help me with sockets, I'm having a weird problem with them #help-croissant
You guys. what is the best IDE for HTML and CSS?
i need recommendations
i used Webstorm and i liked it. but now i need to pay to use it so
we broke up
take a look at adobe brackets
Don't really need a specialized ide
Just vscode and "live server" (extension for vscode) usually does the trick
notepad and http.server π
but yeah, vsc is good, live server just does automatic reloads
which I β₯
VSCode
i now use brackets. i like the animation
Anyone have expertise with python Babel? I have a question: specifically, is it possible to have multiple messages.pot? Our main pot will be human translated while we have some other translations that we would like to use a predefined definition coming from another source that gets updated frequently.
Is this the right place to ask? Canβt find anywhere in docs how I would achieve this. Tried asking on Github and got no reply either. What if I ask on the subreddit? Is that an appropriate channel or are there better subs for it?
Thanks! βΒ please tag me if you reply
hello again.
when i visit my website on my phone ,the letters are black.
the background is dark so the text is pretty much unreadable
this is the website https://kenny-hoft.herokuapp.com
but when i tell other people to access my webpage .the text appears as it should.
in white color
i use google dark mode on my phone and i think that causes the problem.Is that true? if so.. How do i fix it?
Well your css is very non-standard and has no proper colour control (scss or similar)
All I can say
!ask Hello, I was wondering what is the best Python IDE for web development?
Pycharm Pro is great, since it includes all the features of Webstorm, but it's unfortunately not free.
VSCode with the right plugins also works.
I use both.
For VSCode what plugins do you recommend?
There are popular plugins for all the major languages you're gonna be using, like Python, JS, TS, CSS, etc.
It's easy to find in the extension browser, just make sure to use the ones with a lot of downloads.
Okay, thanks again!
Hey. I have a question if anyone uses gitlab. idk why but everytime someone wants to visit my website (even I once) has to login to gitlab first. Is it needed? Or it's cuz it's private repo?
nvm i found the error
What is the best Python framework for a beginner? I was looking at Django but Flask seems to do what I need.
does anyone know html and js here?
not sure if my script is loading into my html or what might be up
PM me the code
did you block me? the messages will not come through
how are you loading in your js?
<script type="text/javascript" src="./Assignment2.js"></script>
just inside</body>
what's in the script?
`(function() {
var add_row;
$('#add-row').on('click', function(e) {
var table_body;
e.preventDefault();
table_body = $(e.target).data().table;
if (table_body) {
return add_row(table_body);
}
});
add_row = function(table_body_element) {
var $cloner, $new_row, $rows, $tbody, count, inputs;
// Get some variables for the tbody and the row to clone.
$tbody = $('#' + table_body_element);
$rows = $($tbody.children('tr'));
$cloner = $rows.eq(0);
count = $rows.length;
// Clone the row and get an array of the inputs.
$new_row = $cloner.clone();
inputs = $new_row.find('.dyn-input');
// Change the name and id for each input.
$.each(inputs, function(i, v) {
var $input, $label, checked;
$input = $(v);
// Find the label for input and adjust it.
$label = $new_row.find(label[for='${$input.attr('id')}']);
$label.attr({
'for': $input.attr('id').replace(/[.]/, [${count + 1}])
});
$input.attr({
'name': $input.attr('name').replace(/[.]/, [${count + 1}]),
'id': $input.attr('id').replace(/[.*]/, [${count + 1}])
});
// Remove values and checks.
$input.val('');
checked = $input.prop('checked');
if (checked) {
return $input.prop('checked', false);
}
});
// Add the new row to the tbody.
return $tbody.append($new_row);
};
}).call(this);
`
just used to grab the table thats above it and then clone it when the button is pressed
in basic
are there any errors in the console?
i dont know how to do that id be assuming no
i thought i just had to code it? is it similar to using pandas in python that u have to call it
ah
it's like using a module in python without importing it
i shall look into that π
ok π i used it and now the consol has no issues
but my button doesnt work :>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
thats what i used
but i think the button not working is my fault
Hey anyone interested to buy a website
This is a wrong place for that.
@dawn drift
I would say flask because django has difficult to understand view routing and mapping
I started with flask and now i'm experimenting with quart
@vagrant adder
Instead of quart try fastapi
It's way better
Here check em out
I'm using django and some of my CSS that are in the same file dont work and some of them do
they work in development
but theyre not working in deployment
Define 'don't work'. Have you checked to see if they're being requested?
wdym requested? When I look at my sources through inspect/chrome dev console the classes are there
Here is an example
@gleaming herald what's that
That's good enough. The dev console includes a "network" tab, that lets you see if the files are being requested by your page and handed back by the web server
Hm
And the new css visible in development is being loaded by your browser, and not applied to the page?
wait actually let me correct myself
the classes dont appear in the dev console
sorry i thought it did
they ARE in the file though
Also, if you go to the network tab, you can view the raw file being served by your live environment. Is that file different than what you've got on disk?
and i did collectstaic
let me check
it is the same file
with the missing classes though
Ok
So what we've established is that the live server is giving out old copies of your css
Next step is to check the files on disk in the live environment, to see if they're up to date
It is up to date on my VPS
And in the collectstatic folder on the vps it is up to date?
my css dir is in my staticfiles dir
which i use manage.py collectstatic
So yes? If that is what you're asking
yes
Ok
Well, that means apache is serving the old response, or if you've got cloudflare or similar? That would also be serving that old response
Wait i found a stackoverflow solution saying to clear static files first so im going to try that
1 sec
Okay that worked
Thanks for being here though!
π
@vagrant adder Actually the performance and documentation of fastapi is better
if you just are good enough in flask
and looking for a change
I guess you should try fastapi instead of quart
its also async api
The thing with quart is that it is compatible with almost all flask extensions
Because it's built on top of flask
And that's what got me intrigued
Also, async ability is just nice
Hello, if anyone uses django-rest, do you prefer django rest token auth, django rest knox auth or django rest jwt ?
Oh Okay ! @vagrant adder
@gleaming herald so i can build quart app but i can incorporate flask-sqlalchemy
Yeah
That sounds like a good start
I thought if you are learning async backend
FASTAPI would be a good place to start
It has way more functionality
Yeah
Such as ?
Hi! Anybody got an idea how to make a online purhcasing bot with selenium and chromedriver?
or any examples
depends on your use case
server rules mean nobody on here will help you with stuff that breaks ToS
https://pythondiscord.com/pages/rules/
We're a large, friendly community focused around the Python programming language. Our community is open to those who wish to learn the language, as well as those looking to help others.
Either way, simply following some basic selenium tutorials will teach you more than enough to get started with that
@robust vigil no its a program that will check out supreme automaticlly
hi seeking asistance to finsih this last part of the javascript to run my website
the if statement runs perfectly fine
but for some reason the while statment doesnt seem to be
even though they are both meant to run
if it helps the same code that the while is running
controlled by a different part
works fine
im just not sure, its just that the while statement lets me iterate instead of click im just not sure what might be incorrect
@fathom sapphire
You're returning inside the loop, is that intended?
That will end the loop
oh, π
even still it doesnt seem to return
i have one table
which is what it adds a row to basically by cloning it
it doesnt add any extra rows
how would i get it to call the function without it being a return?
that's the table
and when i add a row
but i dont want the button
i want it to take from the value and loop till it gets to the number of times
since that how many people there are
yep
I'd also suggest indenting that } the line after, it's misleading as it appears now
that's what i ended up doing but it unfortunately still doesn't run
π I'm thankful for the help so far though
hopefully you can see what I cannot unless its something bigger than that
Is there anything in the console about it?
empty consol