This guy did it. https://github.com/Py4Js/PyScript-React
#web-development
2 messages Β· Page 229 of 1
hello guys, can someone help me?
I develop a CustomUser in my another app
of course, I already register my another app in INSTALLED_APPS
but when I try python manage.py makemigrations dashboard
only my first app migrated not my 2nd app (dashboard)
it only said No changes detected in app dashboard
Do you have any recommendations for learning django as a beginner except the django project website
?
Resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
pillow do not allow/cannot edit data inside images it can just draw on images
Draw the data on the image at request time?
would adding react to my python, flask, html, css, js, postgresql, docker project be an overkill?
No that would be just tons of stuff in your application
It isnβt worth it, donβt do it
If you want to, use c and make your own prog lang
Lmao what
hi does anybody know how to stop flask from redirecting to my website root, e.g. i click a button and it redirects me to website.com/login instead of website.com/flaskapp/login
Does someone wants to team up to make api's?
Why would flask redirect to the root project? Does your button html contain a link? Does your views contain a redirection to your project root?
Corey Schaeffer youtube serie on django is great
Using jwt tokens. pip install jwt. Update django settings.
yeah me
just modify the @app.route
or maybe you have login_required in your code
or something like that
ok fixed it i had href "/" instead of href url for index
there any good frameworks that can be used to make frontends based off of rest apis? or is it even possible to use something like flask admin with rest apis rather than database calls
I guess the right answer is really 'use a javascript framework/library' but I don't particularly enjoy working with it.
Usually people combine django with react. You could make the front-end + backend on a django server and make requests on flasks apis
did u try python manage.py migrate
any suggestions on a course or site or youtube channel to learn django?
i know python but i cant say i master it but i plan to just wing it learn as i go and want to build a sample website while learning django
is there big difference with django 3 vs 4?
Check out dennis Ivy hes a good teacher
not much it shouldnt even mater
This guy dennis ivy is a good intructor he makes minor projects like a to do list just watch the video and when you are lost check the documentation
I've googled myself into decision paralysis π I'm seeking some general advice on framework selection... The last project I did was a while back and I used bootstrap + backbone.js (and a few related libraries).
My initial thought was just to do the same, but there are many new options... backbone itself is still updated, but many of the extensions are not.
I'd rather not reinvent the wheel... but what I'm looking to do is to keep things simple.
this playlist is what you mean?
If you're looking for a backend framework, django is pretty nice.
I'm using pydantic for my models and using OpenAPI to make them readily consumable.
does most of the weightlifting for you so you can focus on making the app
I also want to have dynamic updates of progress bars and such, so SSE or websocket.
I'm heavily using asyncio (FastAPI on the python side) to handle concurrency
With backbone I'd have to re-create the models in JS and handle all of that myself
hmm, if you're relying on asyncio then django might not be for you
I'm not asking about django π
yea i was just dismissing my earlier statement
and I'm looking towards the JS framework side... the python side I'm pretty settled on π
ahh, then this might not be the right place for JS frameworks
Vue seems popular... but it feels like a sledgehammer
What I'm looking for is something that will play well with python
Minimize me having to reinvent the wheel and keep things DRY
I can use pydantic to spit out a JSON schema... but it's unclear which frameworks that might just be 'plug and play' with
or they could use OpenAPI to create the scaffolding
personally i dont have much experience with using js frontend frameworks with python backends, but i've seen people use Vue and React
a to do list to start with would be nice
I've found dozens of frameworks and the basic tutorials seem to be far from DRY
Checkout my new Django Course!
https://dennisivy.teachable.com/p/django-beginners-course
To Do list app with User Registration, Login, Search and full Create Read Update and DELETE functionality.
What are Django class based views overview video: https://youtu.be/RE0HlKch_3U
Related Article: https://www.dennisivy.com/post/django-class-based-vi...
It's like... here you deploy your front end on node.js and create a whole set of MVC
and here you create your back end with python and it's own MVC
and... magic
This is basically a dashboard
It's not that I don't understand JS frameworks... though, some of the new 'compile' to JS models are going to take a little learning
It's that I have limited time and want to choose something that is known to 'just work' and not require a whole lot of duplication
Vue, as far as I can tell, can use build and just use a static endpoint from python
I -do not- want to deploy a nodejs front end
in that case your options are quite limited
How so?
most frameworks require you to deploy a node.js server too
I thought that might be the case, but Vue documents an 'npm run build' as a publish to static that can be served from nginx/apache (or python static)
And then there are 'JS Only' frameworks... such as backbone... but there are DOZENS now that all purport to be 'modern' and seem to each lack different features
you could use vue.js or any frontend framework which can be installed via a simple <script> tag import. I'm not aware of any frameworks that can do this other than vue
Is it possible to add a button to a model object detail django admin page ?
to do what
You can add actions in the list view fairly easily but I think adding them to the detail view is a bit more involved
maybe that helps
thanks
Is someone free to help with something that should be an easy fix in django?
I'm trying to call a dictionary from a view function in the html
But it's not finding it for some reason
really basic user index:
def index(request): user_count = User.objects.all.count() context = { 'user_count': user_count } return render(request, 'dashboard/index.html', context=context)
but when i call the user_count it doesn't display
<div class="mt-2"> <h6 class="">Total Users</h6> <h2 class="mb-0 number-font">{{ user_count }}</h2> </div>
is there something i'm missing?
i've also tried it with User.objects.all().count()
and User.objects.count()
Anyone using HTMX in their projects?
HYello, is it better to learn React first before Javascript? or Javascript first then React?
hey, hows it possible serialize a datetime object? in my consumers.py im tryna send timezone.now() however i get an error of TypeError: can not serialize 'datetime.datetime' object
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
"username": username,
"date": timezone.now()
}
)
popular approaches are to convert it to a timestamp (number of seconds since 1980) or to a ISO string (in the format "yyyy-mm-ddThh:mm:ss.mmmmm")
Ah ok
Ill try it when im home and see because i wanna make sure its similar to the datetime i save in my database which is timezone.now(). I will also need to do this in javascript and also make sure all the datetimes are the same
Format that is
Although iv never worked with datetime in JS, ill look into it
Javascript is a programming language. React is a library that uses Javascript to provide a set of tools for building user interfaces. You should learn Javascript and be relatively comfortable with it before moving on to React.
how to apply an external stylesheet for only one part of the web page
SALAMANCA
BATEMAN
Does anyone have docker experience?) I need to make a container that exists while server is powered on
And I wonder if it's possible to deliver updates of sw to running container
I want to run a web server in a container but update server prog from time to time remotely
When git repository is updated
How can I achieve that?)
guys I need simple VScode help - when a line autocompletes the cursor is behind the semicolon; and if I press Enter it moves it to the next line....
how do I start typing on next line π¦ with a shortcut or something
Link it to that specific web page only
I am looking for a module which will help me to login a certain website.
Any recommendations which to use?
If selenium, is there something better than that? Like light weight or simpler since I just want to check the tags and stuff after logging in.
Ping me please.
Most frameworks just compile to js that you can serve via say nginx, no?
working on my app, what do you guys think, which looks better?
i think the one without the black bar looks nicer
It's up to you but I prefer the nav with the gray bar. Looks more professional idk why
My views.py is getting out of hand and it's hard to maintain. I have kept everything except requests in my models.py but still views.py looks massive. It only handles one job but it's getting huge. Do you recommend using views folder with __init__.py or seperate python files all together and just call it on views.py?
How can I get the host where the django server is running at?
Any django developer here? how to learn django?Help
does any body here has django for beginners 4.0 by william vincet
Book
You can start there --> https://docs.djangoproject.com/en/4.0/intro/tutorial01/ and after that start reading the docs of django and try to build something. There are a lot of helpful tips if you get stuck.
you cant really section off a style sheet to one part of a page, just utilize classes and stuff for styling
This is also valid, you don't need multiple style sheets for small app, because you can just use classes and ids for declaring styles to that specific html element.
How could I make this div disappear with a animation
I want to play a fadeout animation before setting display:none
It's a nav bar...
I tired toggling class with animation but adding a new class for animation and then immediately setting display:none with J's causes no animation
Hello i am using the new py-script that uses javascript and I encountered an error since py-scriipt gets imported from the CDN.
i am trying to use Element() class and it worked at first. However, whenever I import the file that uses the Element class it gives me this error than its undefined, is there a way to fix that? maybe with py-env or downloading the source code?
JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in File "/home/pyodide/App.py", line 7, in from the_file_that_uses_element_class import *, line 3, in container = Element("container") NameError: name 'Element' is not defined )
class Placement(django.model)
Foreign Key to class Block
class Block(django.model)
pass
blocks = Block.objects.filter(
id__in=tuple([placement.block.id for placement in tab.placements.all()])
)
is there a way to make less ugly request?
on which website can i find good free bootstrap home page templates?
i have a django app made locally and i plan to deploy it on heroku,
but the problem with that is that the new data i put in after deploying will be gone after a while. (deployed using sqlite), will changing the database to postgres solve this problem?
sqlite is file based storage, if you are allowed to change the file, you shouldn't have problem. Heroku might not be the best place to use sqlite if you want permanent storage database
so either you change the way your app access to sqlite file (which might not be simple) or you use a database not dependen on your app file system access
Heroku offers a way to easily use PostgreSQL. You might want to check pricing first
How can I replicate the behaviour of current_app or request in flask? Is using werkzeugs LocalProxy correct outside of a wsgi context?
Not sure if this is the right channel but in web3.py how do I wait to see if a transaction succeeded IE:
nonce = web3.eth.get_transaction_count(walletAddress)
txn = contract.functions.mintTierFor(
owner, tier, nName
).buildTransaction(
{
"from": walletAddress,
"gasPrice": web3.eth.gas_price,
"nonce": nonce,
}
)
signed_txn = web3.eth.account.sign_transaction(
txn, private_key=config.private_key
)
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
WAIT HERE TO SEE IF THE TX WAS A SUCCESS
I don't fully understand your question but check if this is useful for you - https://flask.palletsprojects.com/en/2.1.x/testing/#tests-that-depend-on-an-active-context
can i host django projects in github pages
what you are trimg to do
No
ghp only does static sites. No backend.
did you play chess
It natively supports jekyll, but you can push an index.html and use that.
i.e. you can build a react app
Here's a site I wrote that does that.
https://github.com/killjoy1221/website
it's not react, but it's the same concept. Build a bundle, and host it on ghp
ok thanks
the is a github action that actually publishes to the correct repo
receiving all blocks related to querySet of placements in one SQL request
If I use httpOnly cookies instead of headers for authentication (using django-rest-simplejwt) will i even need an access token?
i dont think access tokens will even be needed in this case
I am writing my own none web framework, I want to handle one 'event' or 'request' at a time and want to be able to import a single variable which always references the current even
I think the one without the bar looks better, but I also think that left-aligning the tabs/nav-tool will help balance the page left-to-right.
You have all this negative space on the left-hand side. It's like it doesn't even have to be there.
Negative space?
And then, since it will be in the lighter region, I would invert the color scheme.
Its an app, full responsive if thats what u are talking about
Yeah, I don't think it makes sense to center-align that toolbar.
you can do placements.related_flied.all()
And if you left-align that toolbar, it might actually make sense to center-align the title.
That way you would have a linear diagonal going from upper-left to bottom-right.
Although that would mess up the contrast between the colors if you were to do that.
But maybe you could left-align the github thing, too.
I'd try a few different alignment schemes and see if it feels balanced.
Yeah im going to tweak the design, just have some final steps in the flask app itself
Also have to switch from sqlite to postgresql
I think center-aligning the title and then left-aligning the navtool would probably be the best aesthetically, at least for this screen size. But I'd just play around with it and See what feels best. Right now it feels unbalanced.
Yeah i know. Im working on this project for my upcoming internship interview / conversation
Thanks!
np
Can someone pls tell me hot to import .csv file in treeview using python tkinter
How*
that doesn't look related to web development or am I missing something?
alright, I have what is probably some dumb thing I'm over looking. I'm running a django app locally. I have a text box and a button, I want what I put into that text box to display under the button...
in views.py
context['testvar'] = str(address_in) ```
in my html
``` <h1>
Test
{% for key, value in context.items %}
{{ value }}
{% endfor %}
</h1>```
it looks too easy π€
I need to write a test for this now xD
Its got to be something dumb... actually let me put the full function from views
context = {}
address_in = request.POST.get('address')
context['testvar'] = str(address_in)
return render(request,"address_intake.html",context) ```
Is the color scheme too bad?
I like it, the bars in the graphs at the bottom could use more contrast imo
no but font choice might not be the best
<input type = 'text' name = 'address' placeholder = 'enter your address'/>
<input type = 'submit' value = 'submit'/>
</form>
<h1>
Test
{% for key, value in context.items %}
{{ value }}
{% endfor %}
Yes... I'll be changing them...
Thanks for ur opinion
Okay.. π
...new to web development so bad choices... will look for something better...
Thanks for ur opinion
im new too
anyone have any ideas on the Django HTML issue?
I've got some HTML/SVG best practice questions
But tbh, the Javascript server is useless. You guys are the only ones with real brains on your shoulders
So here goes:
Lets say I have some sort of complex vector. A pie chart for example
Building this chart in illustrator seems to be the way to go, and using either an img tag or an svg tag to display it will give you both your clearly stated semantic intent for the element, while also scaling quite nicely
What if theres text content that needs to go with it β labels for example
Do I: a) create separate elements for this content and position it (painstakingly) over the image; or b) place the text inside the image, wherein it becomes more or less invisible to e-readers and web crawlers
And on the top of svgs β what if the content of the svg needs to be dynamic? Using a singular image tag with an external SVG will hide the yucky internals of the svg, which I think is desirable. And I can probably style external SVG content with css, as well as give it functionality with javascript
But for such content, is it better to use an inline svg? The battle for semantics is quite fierce. As programmers, we want the code to be self documenting, which means putting anything that is "content" inline. For accessibility reasons though, e-readers shpouldn't have to wade through the gross internals of a complex vector (having your ereader read out all the individual paths in an SVG wouldn't be super helpful to someone who can't even see it). And web crawlers β meh, they probably don't care either way
Thoughts?
Sorry for interjecting. Looks great!
How to build this?
I know everyone was worried... but I got mine figured out
first taste of web dev, any tips?
Hey could someone help me to figure out how to scrape the value of "rarity" from this website?
Never did that before and cant figure it out.
https://nftpaperproject.com/wallet/nft/0x04eDC606B0D60e843528422619C6d939be8a2fcF/7958
Thank you π
^^^ thanks
thank you so much for answering my question sir
Hello
this is a votes model on django
it has a one-to-one relationship with the Post model
- in the upvoted_by and downvoted_by i used a different way of pointing at the user instance which one is right.
2.this is the first time that i make a model that has more than 1 relationship with more than 1 models so i feel like there's something wrong idk what it is so can you look at it and any advise would be appreciated.
Anyone familiar with tables welcome #help-mango
Is anyone here familiar with abstract models in django?
I'd like to create a view that unions all child models with *.object.all() and response that to a request
Does anyone if it's possible to run scripts I made in Python in an interface in Django? Like I have a script that takes some input, and in Django to have a form that sends the input to that script and run it?
Is there anyone who could help me switching from sqlite to postgresql on heroku with flask?
Seems like heroku doesn't recognize PostgreSQL module in my app
App is done, dockerized it but can't understand whats wrong with PostgreSQL. Heroku is so fuckd
it is possible but have in mind that is a security risk
what's the error?
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgres
did you check this? - https://stackoverflow.com/questions/62688256/sqlalchemy-exc-nosuchmoduleerror-cant-load-plugin-sqlalchemy-dialectspostgre
Yeah, but cant change the DATABASE_URL in heroku
But i didnt have the time to mess with it
But i will this weekend
Are you familiar with it?
no, also found this - https://stackoverflow.com/questions/35061914/how-to-change-database-url-for-a-heroku-application
I'm familiar with a search engine though π
Hello, I've been trying to find a solution for corshead issue for 2 days can some one help "Django vueJS cli"?
in html image maping we need coordinates of a image how to get it tho
I have a Django project with a custom user, in that custom user I have a display_name attribute on top of the default AbstractUser's attributes, code:
class CustomUser(AbstractUser):
profile_picture = models.CharField(default="/static/users/default.png", null=True, blank=True, max_length=1024) # will be changed for production.
display_name = models.CharField(default="", null=False, max_length=64)
...
```I have a user registration form with this code, || I def didn't steal this from Corey Schafer blog because I'm too lazy to write it myself ||
```py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = CustomUser
fields = ['username', 'email', 'password1', 'password2']
I'm rendering this with this code:
def register(request):
if request.user.is_authenticated:
return redirect('home-home')
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('home-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
How can I make it so the display_name attribute of CustomUser will be defaulted to the same value assigned to username?
I should add, the code I provided works for everything but what I said.
Update:
I found a solution, I overrode the save function with:
def save(self, *args, **kwargs):
self.display_name = self.username
super().save(*args, **kwargs)
Initially I had tried that, but it had removed my initial definition of it
display_name = models.CharField(default="", null=False, max_length=64)```
anyone with CachedSession and threadpoolexecutor knowledge ?
#π€‘help-banana
regarding HTTP GET calls
hello , i'm using drf_social_outh2 module in django i to login with facebook ,i made all configuration that doc says ,i'm using react in frontend and i've installed facebook_login package to implement facebook login on my own website,when i'm trying to login i type my email and password but in django ,he throw an error that states:
oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) User inactive or deleted. <oauthlib.Request SANITIZED>
can anyone help me please ?```
and what is the differences between drf_social_oauth2 and django-rest-framework-social-oauth2?
Can I get python into script-tag? (python variable)
i don't know if i get it right but ,yes you can use py-script
If youβre using react front end, next auth api handles signing in with Facebook for you
That may not be desirable for you since it probably changes your tooling, but itβs an option
I used it for my log in with discord, and it worked very easily and did all the JWTs, staying signed in, and all of that under the hood with little effort from me
i'm using facebook-login package
but i'll give it a try
Hey everyone, I made a blog with django, if you want to take a look at it
https://github.com/francofgp/Engineered
how can I make django-rest-simplejwt to use httpOnly cookies instead of headers for authentication? will this also mean that the access token be removed and only refresh tokens used
hello python community! I have a little question.. since it is possible to setup a flask uwsgi and nginx server with certbot to geet https too on debain 10, is it also possible to do the same with windows server?
Without seeing the code for get_user_mode() I cannot comment upon that. However, the rest of the model makes sense to me.
If you're going to make the most of Django get used to working with Models. Your approach of sharing your approach is a good approach π
Now for an observation. My approach to model design is about function, of what it's purpose is. Form (the model design) should follow function (what it does and it's purpose). When it comes to Votes as a concept, I am left wondering if upvoting and downvoting...belong in this model. What I mean by this is kind of tricky to put into words...because it's a subjective and abstract concept. But the words that come to mind are as follows.
If the Vote model (and I would use a singular name, and add verbose_plural_name to the class Meta) contains votes, then I could see that posts (or whatever data entity is being upvoted and downvoted) is the entity that is upvoted and downvoted.
However, it doesn't end there. Because the reality is, I can count votes, up or down, for a Post and derive the total of up and downvotes. This is made clear through the Post FK as the first attribute for the model.
If the above is confusing...I get it. Design is not a trivial matter. And there is no silver bullet. When I'm designing models I like to take a step back and think about the design within the bigger picture. And I aim for entities, where practical, to have a clear focus. A vote reflects an opinion/decision by someone about something. Looking just at the model alone does not cover enough ground.
@wind dove I can see why you might be stumbling. I stumbled across the very same issue.
I have used a post-save signal to create a custom object related to the user (let us call that a Profile). Your signal though would have to either leave display name blank or guess at it from the user name. However, programmatically such a guess is going to lead to a poor result. This is why I ditched using post-save signals to create a profile and seal the relationship.
That said your view is referencing one form (the built-in user reg form). Another approach I have used is to require the completion of more than just an username, email and password. After playing around with signals to create the object, and then being vulnerable to missing profile information, I opted to place the user and profile forms within the template. This would result in a change to the view. I'll give you a hint to get you started (but not solve this for you as you won't actually thank me in the long run):
def register(request):
if request.method == 'POST':
user_form = UserRegisterForm(request.POST, prefix='user')
profile_form = ProfileUpdateForm(request.POST, prefix='profile')
...```
Do note that I am importing both views from `forms.py`. I am a big fan of `forms.py` to manage data input. π
What is your purpose? Why would you want to bring python code into a script tag?
Can you? Yes, by passing a string variable (containing a python snippet) into a script tag within the template (and dink around with py-script, etc.).
Should you? Well, how would a browser know what to do with said code? That is, unless you're doing something altogether more exotic...
How can I not have this? I have a button which displays a joke on click, then I want to reload the page
I use POST
possibly without having to redirect or refresh something
Instead of returning the html, use a 307 redirect
a 307 redirect, thanks ill check it out
The method and the body of the original request are reused to perform the redirected
request. In the cases where you want the method used to be changed to
GET, use 303 See Other instead. This is
useful when you want to give an answer to a PUT method that is not the
uploaded resources, but a confirmation message (like "You successfully up...
Actually, use a 303. It changes post to get.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303
The HyperText Transfer Protocol (HTTP) 303 See Other
redirect status response code indicates that the redirects don't link to the requested resource itself, but to another page (such as a confirmation page, a representation of a real-world object β see HTTP range-14 β or an upload-progress page). This response code is often sent back as a resu...
Wait, could you explain me the difference between post and get?
Nvm, post is for changing stuff and get is for viewing something
thanks!
A paraphrase...A user GETS a page, and then, assuming it's been programmed for, POSTs something to it.
yep
You can also use the messages library from django.contrib import messages in Django to post flash messages to the page in response to user activity. I prefer messages over pop ups personally. But it's a matter of taste.
I use Flask
what I was thinking of is just passing the list of jokes as a array in javascript and then just take a random one out, not sure if that would work tho 
I had fun with Flask. Great for simpler pages/sites. no doubt.
Yeah I wanted to start off with that before actually starting with django
Flask gave me a great foundation. Then I moved to Django. I've never looked back and have a couple of meaty projects deployed. Working on my third π
Hmmm...Personally, using JS is something I am very judicious about. JS has a place, but where possible I prefer to process logic on the server, and save JS for behavioural responses. That said, even then there are frameworks such as htmx that can support partial page refreshes with only minimal JS. JS is a bit of a pig to code with (IMHO it's messy), adds a lot of client side weight, and comes with risks.
i see i see
That said, if I want to hide fields on a form based on a condition (and user behaviour) then JS all the way for that π
thanks for the opinion, gonna think about the code 302 then, because I am not quite happy with the "Confirm Form Resubmission" error when reloading
I never did get into Forms with Flask. Once I realized I needed meaty authentication, and what DJango Admin does, I knew I had to step up. A great learning experience may be to nail this project in Flask and then replicate in Django. That's what I did with the start of my first project.
But yes, any error when submitting a form is a definite no-no π (unless of course there is cause for the error).
Yep, thats my plan π
same as my plan was The moment I got to the third app, and navigating the logic in a flat file...done-ski π
Enjoy Flask...and...when you switch to Django it may well blow your mind for potential. Django is an outstanding framework.
π
The authentication and admin feature in Django...worth the price of admission.
π
Can someone help me position my buttons and text side by side in a way that is both browser and mobile friendly please?
HTML: https://paste.pythondiscord.com/ohejatosof
CSS: https://paste.pythondiscord.com/ihokoridiv
ah i seem to have found the right section for what my flask - react project
currently having issues because when i serve the react app with flask, when i load the app through the flask port (and thus the website domain), the react router seems to get interrupted by flask api
going to go on voice chat to work on it
π€
Flash messages library in flask
has anyone used bootstrap with vue.js before?
cuz im unable to get carousel to work with vue
Bro there's Bootstrap vue
but that's outdated
Can react.js(frontend) be used with django(backend)?
Is it a good idea?
i see, ill check it out, thanks!
afaik it should work and I wouldn't say its a bad idea at all its just a preference thing
Oh ok
Was because I am trying to get data into the script tag of an html document. (Through Flask)
But I don't know.
How do I make nonetype values not break my whole code?
I have a WHOLE bunch of them and there are get queries linking to them. And I can't start writing multiple try-except blocks. This is ALOT of code
Eg x = Friend.objects.get(friend=user )
When friend is empty it causes problems
i have a video file on my aws server, how do I open that video from the url with python?
I think you kind of have to check if the object != empty tbh.
can i chat related to html?
i m getting this error
yes
This error comes when something wrong happens.
shrey
i have the video file on my aws server, how do I open that video from the url with python?
It's scary just thinking about it.
very
it's a common stack
@dreamy shadow can we not use js backend?
And what is angular react
How does this work
we can using Node.js
Oh like package?
ok
but you should bootstrap using npx create-react-app
thx
np
So there is a way to create a flask application connected with a domain with debain / ubuntu using uwsgi and nginx.
Are there any ways to do the same with for example vscode or pycharm?
In most cases you use frontend frameworks with some kind of REST API on backend
Django could be used to build REST APIs, but i personally would prefer something like FastAPI
Is blink and gecko based on webkit?
i tried changing the height attribute didn't work
Just wondering why do people serve their web static files from cloud storage? I have an AKS cluster that hosts my Django website and the containers have a copy of the static files. What's the use-case or the benefit of hosting directly from Azure Blob or Amazon S3?
one reason being you don't need to send the request to the app server for static files because they're... static i.e. no logic needed before serving them
and a distributed CDN is good for that if your users are also distributed geographically
@native tide The cause for the above is css not working as expected. You would need to share styles.css for others to suggest fixes.
A few thoughts:
- I learned to use a css framework (I got started with Bootstrap and I hear good things about Tailwinds). A good css framework will simplify executing what you're trying to do.
- I use a css framework because as a full stack developer I want to focus on function. I find css to be a very messy language to work with. Bootstrap can also be messy, but it's mostly much more coherent than vanilla css (which at times breaks my brain)
- I recommend commenting your code, particularly the header. Not commenting code makes it much harder to read. For example, I am not sure what animate.min.css is intended to be doing, and more importantly what you are trying to accomplish with it.
- I can see that you are calling a static file
styles.css. One possible cause is that when you run the web server the static file is not being served, and thus none of your css is being applied. - I recommend reading up on how to ask a good question when getting help from other devs. State your objective - How the objective is not being met - What you have tried. You have stated your objective, but not explained what you have already tried. This will slow things down. Vague questions tend to not get answered or get vague answers.
presumebly there's no real downside apart from a tiny fee for hosting?
For further clarity. I do not know if the first image is your dev server (which would have no problems serving styles.css) and the third image is production (where the css static file is not getting served).
In summary, asking a good question can really save everyone time. When explaining the problem provide all relevant files (styles.css is most definitely relevant) and explain the context. Is this a dev environment? Is it both dev and prod? Is there a difference?
well, I mean there would be unnecessary calls to the app server for static files (unless you have configured a good caching policy)
Hosting static files is an interesting situation. I've come to conclude that for the pros and cons of static file hosting, when deploying to production, I can simplify things by storing static files in an aws S3 bucket. I am currently not charged any fee for hosting these files. If that changes it will be because the web site is much busier #FirstWorldProblem
If you host your own static files in your app server (running collectstatic for example with Django) then you also need a web server to serve them (nginx is a common approach). In a deployment environment this will require another container at a minimum, as well as additional complication in deployment. If you host your static files with a provider designed for it then you are in solid shape. The good news is that since static files don't generally change they can (such as css and image files) be cached by the client browser on the first visit.
In short, until I am shown a better approach I am leaning into hosting static files with a dedicated provider. The time saved with this approach is incalculable. Yes, I should still run collectstatic. However, once I have done that the first time (this applies to Django admin static files in particular) then I can actually share a static server across sites if need be (particularly if it's a stable and redundant service such as AWS S3).
I advise reading up on the art of asking a good question. The way you are asking questions is unclear.
Trust me...a great question will get better answers. Search "Stack Overflow asking a good question" and read up.
If anyone has aspirations to be a professional developer...the art of asking great questions will pay off. A vague, poorly constructed question is less likely to be answered because you're forcing others to ask you questions to understand your problem. That slows things down and shows you've not invested the time to really be clear. If you're not willing to invest the time why would others?
using fontawesome?
You can use display: flex; justify-items: space-between; on the container div
Hey guys, I've made a small Django app with a view that gets some data from an API and displays it in a table. I was wondering if and how it's possible to have the client have the new data displayed when its available in one of the django db tables? I've read in some places that AJAX is used, can somebody perhaps point me in the right direction? I've seen a lot of websites that have dynamic content, such as like the dollar to eur ratio, live displayed, without reloading the entire webpage every x seconds. How is this done exactly when using django?
Feel free to @ tag me if you can help me out, thanks! π
js has a function setInterval that runs a callback every x ms
You can use that with the fetch function to make a request to a webserver and modify the DOM using data from the result.
@calm sable
ex: ```js
setInterval(async () => {
const resp = await fetch("/data");
const data = await resp.json();
document.getElementById("something").textContent = data.something;
}, 10000); // every 10s
@frank shoal I've been using this;
However, it reloads entire page, rather than just data
I might be a noob, but idk what DOM is
The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a documentβsuch as the HTML representing a web pageβin memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.
basically the document object
So basically
By calling:
document.getElementById("something").textContent = data.something;
}, 10000);
you get the "something" element, which can also be a table, then replace the data
If it's a table, you would have to traverse further into the table to replace the precise text
and you continuously update the data?
and since it's a table, you could use the datatables library.
from your code above:
const resp = await fetch("/data");
const data = await resp.json();
how does ajax know what /data is?
is that a context variable?
it sends a get request to the /data endpoint defined in django
ah I see
So then in the /data view you can implement logic to return the updated data
Yes.
Is there a good way to periodically run some API requests in django to then save in a database?
So that when I fetch /data I can just take the latest database state
Sure.
instead of making the API calls in the view
Since the API calls take quite some time, like 5s, and I think if I'd fetch from database, it'd be much much quicker, like instantly
maybe do some filters to process less data.
it looks at quite a bit of data and then compiled it into sort of a "report"
I was thinking if I just save the latest report in database, and just serve the latest report to the user
then every x time, generate a new report and save to db
but idk if this is a stupid idea, not much experience with django yet
idk if I can filter much, maybe I can profile my code as well and see if some parts take too long and perhaps they can be optimized
Sounds like I need to get more familiar with Ajax either way, thanks for pointing in the right direction @frank shoal π
Hi Guys π, What could be the best courses to learn Django? π€
@calm sable I'm not working with Django, but for my last Flask project I combined it with HTMX. It's like AJAX integrated directly into your HTML and allows you to swap in snippets of HTML that are returned by your backend.
https://htmx.org/docs/
I used it to update table data and add search functionality, maybe it's what you need.
So, I wanted to not have "Confirm Form Resubmission" when someone reloads the page, on a form, and I was told yesterday that I should a redirect with code 302, I tried that, but it didn't work:
@app.route("/joke", methods=["GET", "POST"])
def joke():
message = ''
if flask.request.method == 'POST':
message = 'Hello ' + flask.request.form['name-input'] + '!'
flask.redirect("joke.html", code=302)
return flask.render_template('joke.html', joke=message)
Can anyone help?
return flask.redirect(...)
thanks!
doing the simplest mistakes?
btw, is it smarter to do this client side or server side?
@prime marsh I followed this multi-part tutorial, found it quite good
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Django_Blog
Flask Tutorials to cr...
How can I get a JSON object from Python through to HTML script tag with Flask?
hiii, need some help real quick:
so I have an application i'm hosting over at heroku
this app has been running for a while and everything worked fine until recent, now, even though my forms have defined a post request, it's only doing get requests.
tried reloading my app, not working, created new app and moved the code over, not working. Checked my code and there is nothing that points my form to send a get request. Nothing off on the server side either.
Anyone know how to fix this issue?
it says GET even though I defined a post request...
nevermind... this is a heroku issue
yep
youβd have to request from javascript to a python function
and return info back
Hey, I'm looking for the best and cheapest way to run a Python script 24/7 that will feed data to a Siteground SQL database. Does anyone know the best way to archive this? Is there some way could run the script on the Siteground server itself?
But how do I do that? (I've tried using Jinja, but that does not work inside of script tags)
noo youd have to use javascript
maybe seartch up a video on javascript fetching to a flask api
Oh, ok. So when I try to fetch a JSON-file, it just tells me that it can't find it. GET http://ip:port/jaso.json 404 (NOT FOUND)
the url youβre requesting isnβt found then, maybe you put it in wrong
oh wait you mean a literal external json file???
or a call to a flask function that returns in json
Yes, a literal file.
jaso.json which is in the same folder as the html-file.
with flask, you would usually put static files, like images and so on, but also your static json file, into the "static" folder. and request it using the /static/... path in the url
Oh, it worked. Thank you. Both you Sani and @obtuse robin.
my app keeps getting a overflow error with sqlalchemy,
"TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30"
and i have been told to change the sqlalchemy engine options
and sure it stops the actual error from occuring on the site
but
it doesnt stop the overflow
and my site ends up running very poorly after a certain amount of requests
which makes me need to close the tab and open it again which obviously would be a nuisance for anyone using it
Hey, im about to start implementing a feature whereby users can send friend requests, accept them or decline them and also cancel. I just wanted to know if special things or modules are required for this type of thing or can i just do it normal with django and like 2 models with some logic in views.py and template?
Hi does anyone have experience using Flask-User library?
can anybody help with bootstrap?
hi
^^^ thanks
Let's say that somebody would set up a local Flask-webserver on his own local IP on school wifi. How much can the school know about this guy? How can they identify him?
They need your local ip to enter the website and later with that ip find the computer and the person who made that
anyone here familiar with cs50w and can maybe help me doing a project for that course? or maybe any good django tutorials for working with forms?
Can some one help me cors header issue cors headers blocked due to policy
What I already checked:
Backend:
Dependencies
Cors_allowed_orgin
Whiteliste
Frontend:
Axios
Router
Headers
Hi
Try to check if your frontend applications is ever receiving the original OPTIONS request from the cors policy. If you're using a reverse proxy, you can probably just handle CORS at that level
I'll check that and be back and let you know thx
is it okay to write CSS without any frameworks these days?
hi guys, i can i add screen reader feature to my html ?
how would i modify the same origin policy using js or something so i can download stuff from other pages
If you want to e.g download something from wikipedia within your page, then CORS is sorta designed to stop that. The only way that might work is if you try to disable CORS for the specific request
but you probably can't make that request from your frontend
thats what the browser does right
the browser enforces the CORS allowed-origins that is specified by the server
Imagine a bot is a picture?
so i have to make the server tell the browser cors shouldnt be enforced for a certain domain?
yes
adding Access-Control-Allow-Origin: * in my nginx config doesnt work though
im seeing it in the response headers
check: does your browser send the options request, what does it receive back?
that is assuming that it's not a simple cors request
are you setting the mode to cors in your fetch request?
i have a link to a page hosting a plain video that can be downloaded if i manually opened the context menu and clicked "save as" or by using the python requests library by just "get"ing that url. I want to link the video on my page and be able to download it by clicking an element (i want the browser to download it immediately after clicking). If i put it in an anchor tag it just opens the page with the video player, so how would i do it?
basically im trying to do this
im doing it with this
<a download href="vidlink">
download
</a>
but the spec says it only works with same origin
the request doesnt say anything about cors / access control
someone said it'd be the other page that would be in charge of the cors policy.
add download="filename.mp4" to your anchor tag
oh
no no
yeah, you can't do that simply
here's a stack overflow post explaining what you can do instead
thanks
I adding this to a list element which is a hyperlink but the blue underline is still not going:
.topicitem{
list-style: none;
text-align: center;
text-decoration: none;
font-size: 20px;
}
And I can't add color
Ping me pls
add it to the a tag
whatever has the href attribute
the a element
Ohhh
<a></a>?
The style attribute?
add a class attribute to it with your css class
a class="yourclass"
Don't work
Oh wait
Works
It works
@native tide thank you
Hi everyone, I have a problem about relational table in django. This is my models. I want to add a new data to Module model, but I get an error. How to solve it?
This is my error
This is my function to add a new module
This my input form
just solved my sqlite problem with flask, so it works perfectly fine now on heroku with postgresql
damn
thats why i love programming
the feeling when u solve problems
I use MySQL for my database
i was using sqlite for my app to test it on localhost
but now it works with postgre on heroku
@brittle trail you assign the program.id (an integer) to the Module program field. It expects instead a Program instance. So you should probably query the Program with the given id and use that object as the program.
can any one please help me in django
Alternatively you could also create your Module like this:
Module.objects.create(
program_id=request.POST[βprogramβ],
# all other fields here
)
I meant like what can the owner of the wifi/router see about the device where its hosted. If that makes sense.
So, I need to change my code from line 6 with your instruction? @gilded moss
Yes. And no need to call save if you use create.
I dont really understand, sorry
Nice, it's work. Thank you guys
Ohh I still have 1 problem again. This is about ternary operator in django templates
I want to choose the select option otomatic if the data has the same value with the option
In php look like this
And I want to implement in django template at the same case
This my code, but it still wrong
<option value="{{ p.id }}" {% if p.id == m.program %}selected{% endif %}>{{ p.name }}</option>
What information does the router get, when someone is hosting a web there?
You compare again an id with a program instance.
if p == m.program or if p.id == m.program.id
Ohh okay, it's work. Thank you
The problem because I haven't write space ( ) between the condition
i would recommend asking about the specific problem instead, then you might have more luck with getting a reply
So I have a django model or a table, and I added 5 items into that table and deleted them all, then I added another one and I expected the id of the item to be 1, since it's the only item in the table but it's actually 6. I think it's something related to saveing the table, not quite sure, can someone help?
Thatβs how DB tables work.
The id keeps incrementing, irrespective of items being deleted.
hello all i want to ask about JSON POST from javascript to Flask. Is anyone had experienced Bad Request Error while triggering the ajax and it send a form instead a json file?
this is the script that triggered by clicking a submit button
<script>
$('form').on('submit', function(event) {
if ($("#class_room option:selected").val()=="none"){<<-there is actually a none option in the selection
alert("PLEASE FILL CLASS");
event.preventDefault();
} else if ($("#hours option:selected").val()=="none"){
alert("PLEASE FILL HOURS");
event.preventDefault();
} else {
$.ajax({
data: JSON.stringify(
{
"class_id": JSON.stringify({{ class_id }}),
"homeroom": JSON.stringify({{ homeroom_id }}),
"class_room": JSON.stringify($("#class_room option:selected").val()),
"hours": JSON.stringify($("#hours:selected").val()),
}
),
type: 'POST',
url: "{{ url_for('send') }}",
dataType: "json",
contentType: "application/json"
})
.done(function (data) {
alert({ response })
$('form').trigger("reset");
})
}
});
</script>
and i declare the send function like this:
@app.route("/update_class/send/",methods=['GET', 'POST'])
def send():
if request.method=="POST":
json_data = request.get_json()
return None
whenever i trigger the ajax it always said 400 Bad Request, even the if- function for prevent the form is work as expected
i found the data sent to function are not a stringify json but a form (class id and homeroom are not included). i have set the url as same as in the route and so in the html form
hello everyone
suggest me a laptop with 8gb ram and 500gb ssd
I am confused, there are so many in the market
large screen( full edge)
i know it's not responsive as well
thanks
what background?
oh you mean the black background color?
What do u need
i am getting this error when i am trying to use a proxy, but when im not, no error is there
@unique hemlockif you look closely at the error message, you will see that it has a suggestion
Yeah
You can pretty much solve every error just by the messages
Simply Google it
as i said, i have no prior experience with python, i barely started
i tried to follow the link explanation, but with no luck
i have been trying for the last 48 hours
or, just read the message π the suggestion is fairly plain π
if you can help me, that would be very much appreciated
I use flask and web development so I cant help u with this but good luck mate
π
@unique hemlocktrying to help...
thank you very much my friend, i will dm you the code, maybe you can fix it
I have a better idea, maybe YOU can fix it π
Btw the issue is with your proxy, its not HTTPS supported I assume
I heard you when you said you have little experience... this is a good learning experience
Which is related to SSL
that part, I'm not that experienced with personally; I wouldn't know what to do (but I'd try to research it)
so give it a shot... read the message... for now, you can gloss over the parts that may be technical, preferring to see what the suggestion is
it is https supported, when i use firefox and add the proxy there it works fine
Guys I was wondering here if some of you know any dashboard or cms template free or open sourcing what would be valid Iβm creating a backend CMS with Django and Iβm willing since Iβm new with the atmosphere of web development perhaps someone may know any of those ? Appreciate such help thanks or link provided
What is the best way to create a url?
http://127.0.0.1:8000/something/ or
http://127.0.0.1:8000/something without the slash?
django is weird
and what do we use to, let's say going into a post in the index page. There should be id in the query string right? Or is it different in django?
I found a good video explaining it. It's a bit different but hella cool.
When html becomes java:
div#container.container.blackbg*10
does creating a Friend Request feature whereby users can send and accept friend requests in Django require Django Channels or some other module? or can is possible to do with just normal Django?
Hi! I would like to add dynamic charts to my web page that will display several variables changing in realtime. Which microframework would you recommend for that? I don't want to mess witch css ans js, something fast and ez to implement like semantic ui suff would be great
I don't know what Django Channels is but I don't see why you would need it. I would just use a DB table to track which user ID is friends with which
HTMX might be sufficient. Otherwise you probably will need JS of some kind
Thanks for heads up mate, I'll google it
Hey, ye i already done it. Had to rethink the logic because i was thinking of a more complex approach but after some thinking etc i managed to do it. Just got few more things to implement tomorrow like cancel and decline.
Guys I was wondering here if some of you know any dashboard or cms template free or open sourcing what would be valid Iβm creating a backend CMS with Django and Iβm willing since Iβm new with the atmosphere of web development perhaps someone may know any of those ? Appreciate such help thanks or link provided
is exposing a simple flask api to the internet generally safe or do I need to take extra precautions to make sure it isn't abused?
I want to just set up a small service that ingests webhooks from clickup and does some actions based on the endpoint
considerer using a production WSGI server instead of flask run. you can import your flask app as a WSGI module in for example apache, with mod_wsgi
then take appropriate steps to harden your WSGI server
google apache hardening techniques
hey guys do you think you can completely replace js with py-script and if it would be a good idea? (for developing web pages)
Django-cms i guess
using drf-spectacular to generate swagger documentation is going towards hell, is there alternative solutions to this?
@unique hemlock Software development is hard. The simplest description I can think of is that it is about taking a big problem you are trying to solve and breaking it down into lots of different problems that can be solved more easily. To be a successful software developer requires that you know how to research solutions to problems. Sending your code to others and asking them to fix it will not help you. If anything, such support will slow your learning down. I appreciate that while you may feel stuck and unable to proceed, the responses inviting you to research the error message is actually the best support we could give you. Assuming you continue on your journey of learning how to engineer software, you will encounter problem after problem.
That said, I want to offer you one more piece of advice. I recommend this article. Asking a good question not only enforces this suggestion to research, but it also sets you up for getting support when you really are stuck. https://stackoverflow.com/help/how-to-ask
Hey, community! Is there anyone who uses or is planning to use AWS Aurora or other Postgres in the cloud? Would you be willing to tell me about your experience? I'm working on an open-source serverless Postgress project and trying to understand what's the most useful thing to build at the moment π€
Open question: If you were running websockets on a React/Next frontend and needed to save the chat to the database (will be using django), would you save every X minutes, or save on each message submission?
or neither...
This is going to be for a shared-storytelling site for long-term written games, but it would need to be able to handle real-time chat if people are playing concurrently.
For chat, a database might not be the best option.
You'll end up getting very large numbers of rows
Try an event log service like graylog or similar.
AWS has cloudwatch, google has operations. Azure has some too.
How do I put it so that instead of
Green
Education, itβs say
Green Education on one line
@civic thicketI've had some experience with postgres, but not putting it in a cloud... I've built postgres many times, but lately, I've just installed it from packages (I run latest stable debian)
How can i fix this error
Hi, I have a code like this:
surveyposts = Survey.objects.annotate(votecount=Count('question__answer__vote')).order_by('-id')
But I need GROUP BY on user_FK_id in Vote table. So it won't give me the count of votes. I want the count of people who participated in the survey. What should I do to achive that GROUP BY?
(votecount variable name in annotate will be changed)
I am moving to a help channel
Found it. After 3 hours, FOUND IT!!!
annotate(participations=Count('question__answer__vote__user_FK_id', distinct=True))
If you are wondering.
why doesn't this work? i'm trying to make a rectangle move across the screen
function move() {
const rect = document.getElementById("rect")
const move = window.screen.width - rect.clientWidth
rect.animate({marginLeft: "+=" + move + "px"}, 10000)
}
move()```
why do you have '+='
i dont think that can work with that
because its like css but inside javascript
so you have to follow css rules
if you want to make the rect element move more left by those pixels then you should find how many pixels the marginleft of rect is then add that to move
instead of trying to do '+='
Anyone here use Postgresql as an SQL database?
How can I find my databases username
I'm trying to connect to it
yes, do you use pgadmin4?
Yes I do
well when you make a database in it, you have to choose its name?
where did you make the db
from pgadmin4 right
Correct
well, theres your answer
Could the username be postgres?
oh
so when you try to put in your database uri youd want to do something like 'postgresql://postgres:{your account password}@local host/{name of database}'
oh oops
I should put that in my VS Code HTML?
no your python
I don't have python written out though
oh are you not using python
I'm writing in HTML/CSS
i assumed since this is a python server lol
you cannot connect a database to just html css
you need a backend
I want a button to pull items from a database when it's clicked
I was going to use PHP to do that
oh alri
<?php
$db_connection = pg_connect("host=localhost dbname=dbname user=username password=password");
?>
This is what I was going to use for it
oh are you confused on the username?
When I open PGAdmin though it only asks me for my password
initially when you first use pgadmin, did you not have to initialize an account?
I installed it some months ago so I'm not entirely sure
hm
I'd assume so but I dont remember to be honest
you can probably find your acc username somewhere when youre logged in though
ah i see, unfortunate
That's what I thought too, but I looked around in PGAdmin and I wasn't able to find anything in particular that said "username"
this isnt the first thing that pops up?
oh
click the little menu icon the top right
and then click the last item in it, then click 'users' and it should show what you need
I know my password though so that's not an issue
i see
Do you mind if I message you real quick? I'm not going to keep bugging you about this username thing lol but I had a different question about SQL
if you mean to ask me about how to use sql specifically, i wouldnt know how, i just use sqlalchemy to interact with it, but if its another question then sure
It's just regarding some web development stuff if you know anything about that
oh yea sure
Does anyone know is it able to render a template while do something on background in Flask? i try to render my template first while in the same time
as in perform a flask function after rendering a template?
yep similarly like that
so what i want to do is like this:
@app.route(/my_url/):
def something():
task a << while doing this, return render template
return render_template('page.html')
I using waitress for my apps, when i declare def something() as async function, and await at task a, it brings error that my python and greenlet unable to do async process
Hi, anyone is both expeirenced with Flask, and Django ? I have Flask service that want to change to Django.
paid , of course. π
then you could edit views.py to make the function that returns the page...
then you can make the template file (whatever.html) and go back to the view, and make sure you return the output of render(), that refers to the template file
kinda vague, and you probably need to do more than that to get the flask app ported to django
you probably need to learn about some of the django classes and objects in order to make that happen
you might do the 7 step tutorial and a few others to find out how to do the django thing, it shows you how to make a page and url
have fun with it
I can
Btw don't post paid gigs here it's not allowed
just added an animated background, what do you guys think?
opinions?
disproportioned UI
how?
hey people. I want something up pretty fast. Can anybody suggest something? There should be a left pane. Easy to add items there. Classic About Us, Quickstart right-top side options etc.. Also customizable. Don't really care about the color palette. Easy to integrate social logins. I would really like it to be django.
Flask
I was asking for something specific with some frameworks / themes in it
What do you mean mate?
who is better django-allauth or django-oauth-toolkit?
Looks great but you should colour code the tasks as a whole
Oh, thats actually a very good idea. Thank you.
You need to add the proxy to your environmental varibles for python.
Installing packages behind a proxy:
pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org <<module-name>>
To install a certificate for your proxy:
pip install --cert C:\Users\Administrator\Downloads\cacert.cer virtualenv
Other:
Using a certificate in a pip.conf
Create this file:
$HOME/.pip/pip.conf (Linux)
%HOME%\pip\pip.ini (Windows)
and add these lines:
[global]
cert = /path/to/mycertificate.crt
Ignoring certificate and using HTTP
$ pip install --trusted-host pypi.pyt
i sent you a dm
I think so, im not sure
My opinion (and this is but one opinion) about the idea of implementing an animated background is...*why? *
By animating a background you are creating a visual competitor with your foreground content and focus. While an animated background may look interesting, and could make sense in some contexts (such as a page highlighting a single concept, such as a product release for example), having an animated background behind what appears to be a task list would feel...distracting for me. In short, any animating will call for attention. This could end up being a distraction from the app's purpose. The more functional and interactive the page's purpose the more distracting an animated background is.
Yeah, it wasn't animated before. I was wondering about what to do with the background and came up with this idea.
Maybe I should set it to really slow?
Or just off the animation?
I would ask why animate the background? How does animation improve the user's experience?
Ah...the user experience was buried in the grave of "it looks cool" once more ;D
No one will use this because it is just for my internship interview, but I understand your point.
Don't get me wrong. As an experiment to learn, I commend it. π
What do you recommend?
By the way, do you have anything else to add? I'm curious mateπ
Well, as I mentioned previously, I could see potential use cases. I recommend considering the purpose and function of a page to help make decisions on form (such as animated background).
Form should follow function. π
Or function should drive form. π
Yeah I get ir
It
Its just my first web app and I'm not really expert at this. Thanks for the input, really appreciate it!
It's a solid start. π If you can nail full-stack development your value as a developer grows exponentially. Practice in aligning back-end with front-end is a useful foundation. It's something I've made a great effort with for my web projects.
Learning how to juggle css is a science and an art. css can be very finicky. Learning how to manage web page style effectively to improve the user experience is always going to be valuable. And in my opinion, this is not something that can be completely taught. It's something you evolve into.
Thank you dude. I used python, flask, html, css, bootstrap, PostgreSQL, JavaScript for this. Thinking about dockerizing it and deploy it with docker-compose to heroku. I want to overkill this project for the internship. π
Excellent first project mate π The practice of using Docker will be invaluable. I wouldn't deploy a Django app without Docker now that I use it. There is no overkill in expanding your toolkit.
I spent about 1.5 months with Flask before I moved to Django. But then, my first project had 9 apps. When I saw how brutal the application file was becoming I realized Django was the way. However, when you unpack Django you'll realize why it's so well regarded as a framework.
Django is truly amazing.
Built a few e commerce platforms with Django. Really scalable and reliable
The more I use Django the more amazed I become. I'm shifting to build full-on automation web applications with Django. When they bring async into Django that will seal it IMO.
Interesting, what would be the benefits of using async views?
Oh my goodness...the potential of async processing is astonishing for me. Now, I can't speak to how async will ultimately look (as I'm not on the Django core dev team) BUT, if they even begin to offer asynchronous processing of tasks I'll be blown away. In other words, currently, Django is driven by requests from the user. I find Celery and integrating async functionality to be onerous. Having that built in... chef's kiss
Django is a framework, python is the main language used in Django for the backend
Django is a framework that uses Python to get things done. If you want to code logic for something to be done, it'll be in Python.
You use a stack of html/css/js and even can inject python code into the front end. An easy way to link the backend with the frontend
ohh interesting
Pretty cool actually
So it is a way to run cronjobs essentially without the use of celery?
iβm learning Wails right now (binding for Go and web app frameworks) kinda wanna learn django though too
Like scheduled scripts to run in the django app
I can't answer that for sure. BUT, if they add cronjobs into Django...dang....
That would be amazing. I have to resort to running scripts on a separate EC2 with scheduled tasks at the moment so that I don't overload my main server
Especially for tasks revolving crawling of data and updating data on the database.
I have my database on a separate RDS server in a private network only accessible through an EC2 with the same security group. With this stack you can launch other EC2 to run scripts
Sounds nifty. AND I would love that type of functionality included into Django. If they do that it'll catapault Django into a true web application territory.
Yeah man. Cool thing about django is that if you think of it, you can break down a django app into micro services with a central database
Technically each app can be a microservice, hosted on a separate server.
That's my jam right there. I'm literally in the process of architecting this approach into a series of web sites for an organization. There will be 4 different front ends all sharing the same DB.
That's awesome!
Of course, it's a bit intense getting my head around it at times π
RDS is a life saver lol. I remember the good old days of hosting my db on the same server hosting the django site. If that server was hacked or taken down, gg data
I assume with this approach your django app is completely cloud, no writing of media related data to the hard disk of the server
A nice S3 to host all media/static files
Nah. Static files on an S3 entity all the way.
Nice, I can already tell you're a good django dev
Learned the hard way, bruh. A practice project was Corey Schafer's blog app. Profile pics in a media DIR broke my brain π
Curious to know, are you using react for the front-end or html/js/css with python code injected?
html/css with minimal JS. I use JS VERY sparingly. Where possible, I process server side and push to the client. I've got a couple of my projects listed in my profile. They're FAST...and JS is VERY sparingly used.
Fair. Recently I started using function-based end points ALOT for optimal user experience. (Ajax to make the call to the endpoint to execute certain code and return the response and the required data)
I do have an application I will need to use React for, but that may have to wait until we expand and I can hire a React expert.
I've managed to dodge using Ajax. HTMX has been a life-saver to replace Django's inline forms (which, let's face it, are brutal UX).
Hmm interesting, will definitely look into HTMX
Yeah exactly, no one wants the page to be refreshed each time you are performing a CRUD function
terrible UX
HTMX is astonishingly simple AND powerful. It's not a silver bullet, but it does partial page updates for parent-child forms REALLY well...
HTMX...those green plus symbols...click it and the child form opens in-page.
I was just checking out your sites in your bio haha
Like this...
you can use nextjs for the rfreshed pages it is the most usefull framework in this part i think
Make a change and save...result:
Interesting, yeah react is also pretty popular
HTMX let's you accomplish a partial page CRUD. Very useful for inline forms.
yeah
I see it allows you to send get and post requests
Cool
Want to see my django e commerce site I built?
Not sure if were allowed to share our site here
I post links to my projects in my bio, and let the conversation inspire peeps to click them.
Fair i'll update my bio now
It's the safe route π
Links in your profile are fair game π
updated, would love your feedback
Its a purely django based tire e commerce site here in Dubai (my startup)
I have a copy of django design patterns and best practices, and I wonder what the opinions are on that book
Nice landing page. appreciate you factored ultra wide monitors.
Thanks man, yes def made sure it is responsive for all resolutions
Using React for that?
Nope, no react
Solid work, bruh
My stack is html/css/jquery and bootstrap of course
With lots of custom css coding, custom design, etc
to test a tire search search the size 255 55 19 for example
I'd refine the font for the menu. It looks out of place with the rest of the font choices.
Good eye, I used a different font for the menu was testing it out, will probably revert back to the normal font family used throughout the site
Great use of css
the best font for me is robot
Oh yeah, you will see in the CSS code that I really used the min-width and min-height to make sure it looks good on all resolutions haha
Good tire selector. Given the purpose of the site, it's a very solid search implementation with solid UX
Thanks! I'm using wheelsize API to get the tire size data and vehicle data
Excellent. I was just going to ask how you're embedding search parameters.
Cool thing about this project is we have 0 inventory. We partnered up with major suppliers in the region to give us access to their live data, cost, stock, etc, to provide a large selection of tires to consumers
So basically we are offering millions of $ worth of inventory without having a single tire in our warehouse
Solid idea and approach. There's value in being able to simplify search in practical ways
Thank you π
My apps tend to be more complex. But my latest solution is doing things no other event management solution currently does. Exciting times. It's in alpha right now, so still smoothing out the kinks. But so far so good.
Interesting im on your site right now
It's not super sexy like yours. But then, my passion is function. Build great function with solid UX and they will come.
I think we both should change our admin paths π
LOL I haven't honeypotted Admin yet. But I will when we shift to full prod
the admin panel is actually terrifying if its hacked. I am thinking of creating a 2fa for accessing the django admin
its literally the engine to your DB
Exactly everything is step by step, if you have a really good product, you can always improve the design and such
But the product must be good π
Well, Whurthy will be separate apps and DBs for each client installation. So, hacking risk is contained per application/client.
Yup really good design
The starting question for me...is this solving an urgent, pervasive problem? Yes? Then it's valuable.
So this is a SASS product
Whurthy is doing a few things that no competing app is. Automated discounting, wait lists, automated cancellations by host/venue.
Yes, SaaS all the way
Man... I love SaaS. One of my dreams is to try to create another SaaS company down the road
The potential market for Whurthy....well, any retail service outfit, through to festivals.
I had a fintech SaaS product coded in PHP for the front and partial backend, and java for the major backend (this was years ago)
I loved it, sadly it didnt workout as planned but SaaS in general is awesome if you get it right
Interesting I am reading the features right now
Well, it's early days for us. We are inviting a few close clients to alpha. From there we will get to see how it works out in the real world. It's a great idea in my head yet to be proven.
Awesome you have clients lined up for an alpha. It will be a good time to seek out major bugs and such
Bootstrap made it possible to make Whurthy look like an app on your smartphone...without the app overhead and limitations π
Yup. We even have a fully baked-in support ticketing system to take suggestions and manage issues through to future requirements
I wish you the best of luck man, I love seeing other entrepreneurs making their move in tech, especially SaaS
π Thanx
So someone sent me an image and CSS file for text that's supposed to be entered there, how do I use that?
Hi π I'm trying to deploy my Django project using Nginx and Uvicorn by following this video
https://youtu.be/TLhkmXnmguI?list=TLGGEl1xogJ6zPQyNDA1MjAyMg
to sum up the video, this is all the commands that are used
https://gist.github.com/zaemiel/edfc6c176b2c9d210e3ebe02caa76834
I used the same approach before and it operates fine for more than a month, now I'm trying to use it again with another project but it gives me the error.
2022/05/24 18:43:50 [crit] 5992#5942: *1 connect() to unix:/tmp/uvicorn.sock failed (2: No such file or directory) while connecting to upstream, client: **.40.***.8, server: thebeauwow.me, request: "GET / HTTP/1.1", upstream: "http://unix:/tmp/uvicorn.sock:/", host: "www.thebeauwow.me"
and I have no idea why there is an error with tmp/uvicorn.sock
here is my conf files https://ideone.com/i75LwC
This is a good guide:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04
Skip the Postgres part as I assume you may be using another db
I would prefer using Uvicorn for now
Oh apologies didn't realize you're using uvicorn, thought gunicorn
no prob, thanks for helping
I'm trying to decide whether to stick to a Next.js+Django with SSE setup or to instead begin with Next.js+Node with websockets for a web app that will allow mutliple users to have a chat-like experience with storytelling. Mostly users will be playing async over days/weeks/months/years, but there should be a somewhat real-time ability for players to play together at the same time if they want to.
Anyone have recommendations of food for thought I could look over to steer me one way or the other?
This is a great idea.
I have an element which is supposed to be invisible (opacity 0) unless a companion element is hovered on
So I've got a css transition that works perfectly fine, except
When the page loads, the element isn't transparent yet, and so it fades out as the stylesheet is loaded
I know I could solve this with javascript, but I feel like there should be a css only solution
for Flask, how do I check that a request came from localhost (without bypasses)?
currently I have request.environ.get("REMOTE_ADDR") == "127.0.0.1"
but idk if that would work or not
using uwsgi + nginx using https://github.com/tiangolo/uwsgi-nginx-flask-docker/ if it matters
excuse me, I need some help about upload file in django form. How to store the file after upload with form into my local storage of project?
this is my folder structure
You are trying to upload files from a form into your local database and store the file itself in your media folder correct?
To upload a file in django, you must ensure you set a column in your model to store the file location such as this:
file = models.FileField(null=True, blank=True,upload_to='orders/files/vault/')
Also make sure in your urls.py of your project folder, you have the following:
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in settings.py add the following:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Now you can easily upload files. If you want to use a django form, simply add the fields you want to enter into your model in the form, and on the front-end make sure you have the following code in your <form> tags:
<form id="id_of_form" enctype="multipart/form-data">
{% csrf_token %}
</form>
In that form you'd put your django form by injecting it or manually adding the upload field and such for a more controlled UX
for making POST request in it use request.FILES.get or request.FILES
- for accessing it use .url on last at the orm
yes like that
this code is to store the file has been upload from a form to my local storage right?
Yes it will save the file into the MEDIA folder
ohh I see. But if I want to process the store file in the views.py not in the models. What should I do?
When you upload files in Django, they are saved in your model and stored in the MEDIA folder
Otherwise you will be uploading random files with no way to access them
import time
import config
from functools import lru_cache
from fastapi import FastAPI, Request, Depends
app = FastAPI()
@lru_cache()
def get_settings():
return config.Settings()
async def get_ip_details(client_host: str, ip_info_api_token: str) -> dict:
url = f"https://ipinfo.io/{client_host}/json?token={ip_info_api_token}"
# Logic to fetch ip details from 3rd party
# Sleep simulating the delay
time.sleep(10)
return {"ip": url}
@app.get("/")
async def root(request: Request):
client_host = request.client.host
return {"ip": client_host}
@app.get("/detail")
async def ip_details(request: Request, settings: config.Settings = Depends(get_settings)):
client_host = request.client.host
ip_info_api_token = settings.ip_info_api_token
ip_details = await get_ip_details(client_host, ip_info_api_token)
return ip_details
When a client hits /detail I would like to make a request to a 3rd party API and reply with results. But right now if /detail is being served then / hangs too and only serves when /detail is resolved for other client. How can I do this in truly async way?
@lime mist This is flask?
fast api
my true question is, how can I make a function from scratch that I can await properly
How I run my scripts in Django is run them through a thread so that the server isn't waiting for the process to complete to serve the request, and when the process completes you can save the result in the database, and have your frontend constantly waiting for the process to complete for that user, and when it detects it, grabs the data, but again this is fastapi so not so sure
yup, I am aware of that method, used to do it with flask
but async seems different than that, so just wanted to try it out and understand it
Ah okay
ohh okay, it's fixed, thank you for your help
[crit] 5992#5942: 1 connect() to unix:/tmp/uvicorn.sock failed (2: No such file or directory) while connecting to upstream, client: .40..8, server: thebeauwow.me, request: "GET / HTTP/1.1", upstream: "http://unix:/tmp/uvicorn.sock:/", host: "www.thebeauwow.me"
from flask import Flask, redirect
app = Flask(__name__)
new_url = 'http://amir.rachum.com'
@app.route('/')
def root():
return redirect(new_url, code=301)
@app.route('/index.html')
def anypage(page):
return redirect('{new_url}/{page}'.format(page=page, new_url=new_url),
code=301)
if __name__ == '__main__':
app.run(host='10.0.1.10', port=5000)```
so i have this code i would like o use redirect with virtual host so it redirects me to the main index.html
Ok, and what happens when you try it?
Yo , anybody uses Kafka events stream here ??
it works ok
Hi, I just bought a domain name yesterday and deployed my website on GitHub pages. It says DNS check in progress? What does that mean? Is it the propagation? Is there anything I need to do on the domain side?
I have a FileField() (using django here) from where I upload a file, it is storing it inside the MongoDB database. When I visit the admin panel and try to visit the image url, it throws a 404 error. It is not saving the file in my directory. I have updated the settings and urls and still somehow its not saving the file.
This is my models.py
grid_fs_storage = GridFSStorage(collection='images', base_url=''.join([settings.MEDIA_ROOT, 'images/']))
grid_fs_storage_video = GridFSStorage(collection='videos', base_url=''.join([settings.MEDIA_ROOT, 'videos/']))
# Create your models here.
class Uploads(models.Model):
uploaded_file = models.FileField(null=True, blank=True, storage=grid_fs_storage)
uploaded_video = models.FileField(null=True, blank=True, storage=grid_fs_storage)
Using this in my urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And my settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Folder Structure
Hello, I install nginx wordpress on aws ec2 working, but after few hours got 502 bad gateway
This doesnt work
sudo systemctl enable nginx
hey if I wanted to just deploy a website
in django, where could I find a website
where they provide really customizable templatess etc.
https://Tailblocks.cc @lofty sentinel
Ready-to-use Tailwind CSS blocks
How do I refresh ajax if new data is added to the database in django?
Can anyone clear up to me how does 1em equal to 13.333?
Shouldnt defualt 1em be 16? im banging my head 30 mins already and i cant find an answer
after cloning a project i'm trying to run
python3 manage.py makemigrations
but i'm getting an error
django.db.utils.OperationalError: no such table: auth_user
Steps tried:
- I have tried deleting db.sqlite3 (does't resolve)
- Clone the project again (does't resolve)
- python manage.py migrate --run-syncdb (Does't resolve)
Can anyone provide me some assistance?
try 1rem... its always 16px
Yes I know that
But i'm trying to figure out where does 13.333 come from
Could it be that button default font size is 13.333?
try playing with it
<form action="" method="post" autocomplete="off">
<a id="Download" href="https://cdn.medal.tv/39995498/720p-319900249.mp4" download="MedalDownload" name="Download" class="Download" value="Download">Download</a>
</form>```
Instead of downloading the video, it opens it in the browser. How do i make it download?
How to open a url silently without getting a 403 error code, anyone can help ?
You shouldn't have run makemigrations. Simply run python manage.py migrate
Because the migrations have already been created in the initial project, you want to migrate them locally to your database. Afterwards, if you make changes to any model, you can run makemigrations, but you need to initialize all the tables first
and when you do that make sure you delete the old database, create a new database then run the commands
If you don't do that, your django_migrations table will mess things up
thanks @uncut trellis will try
Also why not use MariaDB, so much better
On my development server on my local pc, I use HeidiSQL to connect to my database to visually see the tables and data for easier coding flow, and the db I use is MariaDB
You can use bootstrap for your front end, there are many customizable templates to choose from
Check your NGINX error logs to diagnose the issue
Hi, I'm working on my js homework and for some reason elements placed inside div class 'product' are aligned horizontally. Is there any reason for that? I know it isn't python question but it probably counts as web-dev. Screen for reference.
What do you mean aligned horizontally, you mean centered?
insted vertical elemnets are in one line
i mean inside class product not products wrapper which is flexbox
Can you share the css code for .products
And how would you like them to be positioned?
#products
{
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
without it it works the same
Well this css code is for the ID productions, not the class inside
i know
any code for .products{
}
?
Ah
i don't want them to be in horizontal line
but they are for some reason without using float left or anything
Im still confused lol
so you want the product under it to be beside it?
you want the bottom image next to the tv on the left?
i want content of product to be one uner another
I think you just don't want flex
Oh
can you check dm pls ?
Yeah honestly use the styles tab in your element console and try to remove certain css code/add til you get it to work
hmmm, some work will be done. Thanks for your time π
Good luck!
Thanks
On a lot popular websites their class names get randomized/obfuscated is this easy to implement on Django?
I don't think you need that, plus it might have to do with compilation process in different frontend frameworks
Why would you need to do that? Most of the processing is happening in the backend anyways
I assume you are referring to the front-end code of your django web app, because users will not be able to see your python backend
I could imagine big sites might do it to discourage scraping
I think I've seen it just as a by-product of using certain libraries like in react. Some libraries do css in js and you just define variables that refer to styles and use those in your jsx -- then a byproduct of this is randomized class names I think
Hello, I added second domain to django config and now static files don't load anymoe
Hello
I developed a web app using HTML CSS JS BOOTSTRAP and FLASK. Add the login functionality. The login tab shows in the nav bar when I go through index.html but when I open the app using flask run, it never shows the login option
i have a folder with html files i want to insert/include in my main document, how would i do that using js
the only way i know so far is to use the fetch api to get them and innerHTML
So long as the html data is structured, changing class names of JS functions isn't an issue for scrapers. Scrapers will be scraping html content anyways, the only time JS is important is if its loading data into the site, which at that point they may use the network tab to figure out the request that is loading the data and try to send a request directly to the endpoint to retrieve such data
masking themselves using headers to trick the endpoint in thinking its a normal user requesting the data from a browser (using selenium for example with scrapy)
And I love web dev β€οΈ
I'm on my third Django project...and enjoying it sooo much
Now THAT is something I've worked out how to minimize
So far I've build a couple of solid SaaS solutions with only minimal JS
how u do it
Well, that is driven by what you are trying to do
ya js is the bane of my existence same as c++ pointers
but I do use a css framework (bootstrap, where JS toggles nav with hamburger for mobile for example)
ok
There are other small uses. But I've managed to avoid JS Frameworks
htmx....very useful for inline forms
True
JS is not what I would call an...elegant...language π
I also fundamentally strive to do as much backend through the application layer as I can. JS is a slippery slope for confusing application with presentation. Certainly, there is some behaviour you often want to adapt for. But much of my focus is on functionality. I want to master that. Slick UIs can come later. π
An axiom for me....form should follow function.
π
If you don't like it, then you probably shouldn't get wont to it.
I also used to like it, now I hate it and write.
alright thank you
I will check on that thanks
If anyone is experienced at creating websites with flask, please come in the Live Coding section
I really need some help
Should I specify the technologies I've used for my project on my resume?
For example: Python, Flask, HTML, CSS, JS, PostgreSQL, Docker
or its not recommended?
don't use vanila js, use Vue.js js and u will enjoy it
Vue.js for the win ;b
I was working with vanilla JS for 6 months. It was a pain.
Go on
