#web-development
2 messages · Page 122 of 1
Yes i hate this shit
is that for free or what?
the minimal amount of knowledge you need to do that is at least some knowledge in alg2
its free, its just practice and shit
omg that need some summer shit and stuff
i dont have that much time to focus on such a thing
i already have school
anyways im into web-dev but for now its just front-end
i have it too lmao , i still do them
determination = possible success , non determination = nothing
you should do algorithms and problem-solving, that's for sure. advent of code is running, that's a good place to start.
wait is it a Python server event?
not linked to this discord, but it's a coding event
ah
there's an advent-of-code channel in this discord discussing solutions too
front-end ?
plus it covers things which you probably won't come across often, such as regex, so it's a good way to learn something new
bruh
backend is easier
frontend is nightmare
you have to format those stupid css stuff
u mean python sql and these shit r funny ?
they're fun not funny
u better step the fuck up man '
this is feeling off-topic
idk LYC but i think front end do the colors and the fun parts
doing frontend becomes more enjoyable with frameworks like angular/react
they have nice libs (e.g. for animation)
tell him, Nut
what are you on about
I am following along in the Django for Professionals book and I am stuck at the first chapter where you create a django project and app
using pipenv and then Dockerizing it
when running docker build . I get the following error
=> ERROR [4/5] RUN pip install pipenv && pipenv install --system
I ignored that, made a docker-compose.yml file
and ran docker-compose build
and got this error
ERROR: Service 'web' failed to build : The command '/bin/sh -c pip install pipenv && pipenv install --system' returned a non-zero code: 2
This is my Dockerfile:
FROM python:3.8
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /code
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
COPY . /code/```
This is my `docker-compose.yml` file:
```docker
version: '3.8'
services:
web:
build: .
command: python /code/manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000```
Low key
Would never use pipfile
With or without docker
But even more so with docker
is anyone good with flask and jinga? would really appreciate some advice on a project thanks
its a super simple project. nothing complicated :D
Anyone want a site made for them? I'm doing this for hours and not money. I need volunteering hours
hi guys:) anyone could give me advice on where to learn django
Hey who does web dev for shopify here
lol cant believe they made an actual website just for this
Is it possible to call a function of a loaded JavaScript file from a Flask app?
I was thinking of creating an endpoint that the JS file constantly queries and that tells it what to do. But is there a more efficient way?
Can I mix 2 flask apps
JS is frontend, Flask is backend, wdym?
I want to modify DOM elements at certain times from the backend
I have functions in a JS file to do that
Is it possible to call those functions from the backend?
hey, i had an important HTML related question? can anyone help me with that?
you can ask here, if anyone can answer they will reply to you
good idea, um
HTML comes under #web-development i guess, which means you can skip straight to your question 😉
i have this quiz kind of thing that i have to solve, and i know one can get the correct answers through inspect element. it depends on whether the website is static or dynamic
but i'm not an expert in that field, so i wanted someone who can help me with that to tell me quickly if it's possible to get the correct answer of an mcq question on this specific website or not
which website
can i screenshare?
nah jus share link
it's a private organization
not a problem
don't think you can access
sure
LearnWISE is an integrated learning platform that helps colleges & faculty organize and manage entrepreneurship education
does this work?
wait up
aight
PM
anyone?
?paste
what
I would like to mix 2 flask apps, I was thinking of using subdomains but can't because the host I use pythonanywhere.com does not support subdomains in flask
look into SSEs or WebSockets
Thanks 😄
anyone could help how to handle files in this curl?
curl --request POST --data-binary '@/home/test.bin' http://xxx/api/SubmitWebLog/
i'm using django btw
here is what i got when trying to print
using .read() gave me error
you wanna curl in python?
Utility for converting curl commands to code
you don't request.body.read()
to test your curl
to implement in python
I believe not
I made a quick and dirty video of live editing of a webapp, a new feature in iommi: https://youtu.be/pflnp_PvLjA
@echo mesa can you show me the relate code and what object you are attempting to get the text attribute off of?
I already solved this but thanks ! I have another problem
Can someone help me with Flask, Jinja2?
I'm trying to set the onchange of a field created using FieldList to run a function with giving the parameters of it's id
Essentially making a table of SelectField which after each one changes it will trigger a JS function which adds it's it's id to a Hidden field that on POST I will get and update the corresponding things in my DataBase
Hey there! quick question!
I'm developing a DJANGO APP and there are some actions that have to be done one time every month. I need to save the last time they were executed and show it in the app.
My question is: how should I save that date? Should I write it in a file, should I create a model for it?
Thank you !!
Not Found: /styles/navbar_styles.css
why does it add / before the styles?
<link rel="stylesheet" href="styles/navbar_styles.css">
Hello, this question is regarding development
how to delete all the browsing session information such as history, cache, cookies, downloads, saved passwords, etc for an stateless webservice that allows one to interact with two web-browsers: Google Chrome and Mozilla Firefox such that the service should support endpoints /cleanup with a browser parameter which can any like chrome or mozilla?
for ex. http://<server>/cleanup?browser=<browser>
should clean up the browsing session for the given browser if has been stopped.
I think the Django documentation is the best to starttt
represents the root
okay
so how do I get around this?
Sorryy hehe. I just started learning Django yesterdayy, tried watching videos etc but im quite slow. Try some mini project like the polls/todo app and I think i get the concept of django bit by bit
nvm I just changed some settings
yes
What did you change?
well the path to STATICFILES_DIR was set wrong
I seee that is one of the way too
What i did yesterday was using something like this:
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
This is my files
yep and I also forgot to {% load static %}
So I have a list of items(rows) that a user can purchase, and it adds to the total price correctly when they add a new item, but when a user deletes one of the items, the price doesn't drop/update
function ListFieldRowCount( listField, totalField ) {
var totalRows = jQuery( listField ).find('table.gfieldlist tbody tr').length;
jQuery( totalField ).val( totalRows ).change();
}
function ListFieldRowTotal( formId, fieldId, totalFieldId ) {
var listField = '#field' + formId + '' + fieldId;
var totalField = '#input' + formId + '_' + totalFieldId;
ListFieldRowCount( listField, totalField );
jQuery( listField ).on( 'click', '.add_list_item', function() {
ListFieldRowCount( listField, totalField );
jQuery( listField + ' .delete_list_item' ).removeProp( 'onclick' );
});
jQuery( listField ).on( 'click', '.delete_list_item', function() {
gformDeleteListItem( this, 0 );
ListFieldRowCount( listField, totalField );
});
}
ListFieldRowTotal( 158, 1, 7 );
//ListFieldColumnTotal( form id, list field id, result - field id );
// enable dynamic population on field that is to hold result
</script>```
any ideas?
What is your gformDeleteListItem function?
and also you seem to be removing the event for deleting the item when you add the item. maybe it has something to do with that?
Hey guys! I'm looking for a solution in Django to live enable/disable models or views that doesn't require me to perform an 'if' check in the templates
Like enable_blog=False, hide it from admin and disable the view
if BLOG_ENABLED:
class Blog(ParentSomething):
... awesome code ...
Perhaps? Not sure about Django.
@slow shale tried that the main issue is that the server has all the source code cached in the background
which means I'd have to reboot the server for it to take effect
found a workaround for disabling the view while Live, but doesn't remove it from the admin menu 😦
Ohhh. You basically want Django to restart the webserver with different values.
I might have to
Hmm. They may have "hot" reloading but that's usually reserved for development due to possible performance implications I think.
pretty much my thoughts
I guess I'll dig into the admin html template and see if there's a simple way to modify it
{% if module.enabled %}
<a.....>
{% endif %}
Figured it out
# blog.admin
def blogAdmin(model.Admin)
model = Blog
def has_module_permission(self, request):
if checkModuleEnabled():
return True
else:
return False
@native tide when you use React with Django do you just use the standard NPM package with create-react-app?
I was reading a guide on how to use Django and React together and it seems to be just two servers running seperately, so React is rendering its own pages, while it grabs all that is needed by fetching it from the server.
So when using React really will I not be rendering anymore with Django just with React?
I see myself just using Django to return a JSONResponce and using that on any renders for any use of items in backend is this correct?
Yes use CRA. (create-react-app). You'll essentially have your front-end separate to your backend, with the React making API calls to your views.
Having your frontend and backend seperate means that you will have to use webpack (which CRA has scripts for) to bundle your static files. Then, Django can render your index.html of your React app and the rest is handled by the frontend. (this is done by just changing the STATICFILES_DIRS
However, you can also stick with templating and just sprinkle some React in there from the staticfiles in your Django project, that way, things are simpler and the frontend and backend are not "seperate". This would be server-side rendering while the other one would be client-side.
^ I've never tried this method but it'd be cool to know how to explicitly. Here's a cool article which helps:
https://mattsegal.dev/django-react.html
@haughty turtle
Thanks @native tide looking into it
That blog kinda goes through all the webpack stuff which is already included in CRA, so this is how you actually get the react / django to co-exist on the same server:
https://blog.usejournal.com/serving-react-and-django-together-2089645046e4
Django will just render one page and the rest of the routing is done client-side
@halcyon dragon what are you hoping to see when you run django-admin? Try django-admin-help to see available commands.
django-admin startproject mysite @halcyon dragon
@native tide I mean I actually think rendering from React will be better as it prevents double the work from being done.
Yep there's pros and cons to server-side and client-side rendering
on server-side there's better SEO and indexing by search engines
but client-side is faster
slower for the user?
with React, since you're just mutating the virtual DOM, wouldn't it arguably be faster for the user since they don't have to wait for the server's response?
They still have to wait for the server to respond
- the js rendering time
- the sub requests that still get sent
- the extra processing time required to route and load elements to be rendered
Jinja and Django both take less than 0.1ms to render your average page
And that's with alot of templating with inheritance and all that
Slimmer pages can easily go into the micros
well for the first render, sure, iirc with React apps the whole application is rendered at the first request, right? But then you save time due to not having to refresh the page and the virtual DOM mutations etc
Sure you have that once it's loaded its mostly done
But you still have that biggg load time at the start
Plus things like images etc...
Client side rendering is pretty much always more of an advantage to the server not the client
If the server is any sort of reasonable and consistent latency
then again there are methods to split the JS downloads so you don't download the whole application at once (not that it's really a problem for the most part) but I haven't had experience with it
I think web-apps should all have some JS in there of some sorts
it adds so much more.
How do companies do it @quick cargo ?
@haughty turtle I heard that a general rule is to not worry about performance until it's actually a problem
From a servers perspective client side is great
Cuz suddly you cna just have one large static content server
Cache everything
Low load, high output per worker
talking about servers & backend, I'm really stuck between choosing express.js and django
@haughty turtle also if you're doing react and you want some really cool animations
I've heard Framer Motion is good
I've also used react-spring but the docs are not as good as I hope for more complex animations, but for simple ones it's awesome
100% django over express
Litterally no competition
you know what's really confusing though
on a lot of jobs (referring to fullstack, etc.) employers want node.js. it's so confusing because what is that referring to? express.js?
then you go and search for express.js jobs explicitly and it's less than that of django
Node.js has its own HTTP framework iirc
Express is shit though
Slow, unreliable and inconsistent
so, node.js is a backend in and of itself?
I thought it was something that encapsulates lots of other things, like an umbrella term
It can be yes
It's significantly faster than express
Similar system as with go lang's inbuilt HTTP ext
hmm, so in that case it would be worth learning node.js?
Meh
It wouldn't hurt to get comfortable with js cuz front end
But backend wise I'm not personally massive on it
i'm pretty comfortable with js, it's just that I'm so confused when job listings want 'node.js'
Most will use it as a umbrella term
Cuz recruitment agency's just slap as many buzz words on as possible to get higher listings
yeah that's true
so I guess when they use node.js they are referring to npm libraries like react
or just js in general
Prob to npm libraries
is there anyway to both set and get to/from local storage using flask?
anyone know how i can have subdomains share the same app instance with the base domain in Flask?
I have a view function that redirects to a subdomain, so like sub.base:5000 (yes i am running locally), but apparently this will not work since subdomain is not a thing for localhost, I heard I can have a thing called matching_subdomain set the true to have Flask to match against. I also specified the base domain by using app.config['SERVER_NAME'] = "base:5000" and also a hosts file on my computer (I'm in virtual environment so not really sure how that'd work).
So anyways, I've got those done, and I nevigated to the subdomain which works fine and it returns and renders a html template as I have set it to in the views. The problem is, the app.teardown_appcontext thing is called after I nevigate from the base to the sub, which makes sense to me, does anyone know how to have the subdomain and the base domain (running as localhost btw) to share the same app instance so app.teardown_appcontext doesn't get called?
#Flask #Python #WebDev
anyone know if there is a Discord dedicated to Flask
all's I mostly see in here is people firing questions and getting no answers 🤣
"Node.js" can be shorthand for "JS as a backend language"
as opposed to React, Angular, Vue, etc., which use JS as a frontend language (running in the context of the browser)
Hey can anyone help me in using notebook script for website
I've made a speech to text code from scratch in colab
Now I want it to be hosted onto the web
How do I host the script and all the required libraries on the firebase
hello
show the code
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/aiohttp/connector.py", line 936, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 1017, in create_connection
raise exceptions[0]
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 1002, in create_connection
sock = await self._connect_sock(
File "/usr/local/lib/python3.8/asyncio/base_events.py", line 916, in _connect_sock
await self.sock_connect(sock, address)
File "/usr/local/lib/python3.8/asyncio/selector_events.py", line 485, in sock_connect
return await fut
File "/usr/local/lib/python3.8/asyncio/selector_events.py", line 517, in _sock_connect_cb
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 2333)```
My Lavalink Bot cant start. This is executed on a Ubuntu based v-server
Does anyone know a good tutorial for setting up a Virtual Enviorment in VS code for a django project/ django tutorial?
anyone who knows how to fix the "Getting default adapter failed" tried on google, loats have had it, can seem to fix it tho
im simply opening a website, literally nothing else, and it crashes down after 2 seconds (selenium)
put python before django
python django-admin startproject music_controller
@gleaming basin
I am using libmagic to check the MIME type of a file on user upload but I have 2 questions: 1. Do I need to check the file extension too? 2. as far as i know, even seemingly harmless files can be malicious (for example, mp4 can be malicious) how do I verify that the user uploaded file is not malicious? (I am using django)
Scan it with a anti-virus on your server? @fallen spoke
Or send the file to virustotal.com through selenium and obtain the response ?
I am not in prod curently, just local testing, but what anti-virus do you recommend that I can use with python when I go into prod
If their ToS permits, don't see why it wouldn't allow you to.
I think they have rate limiting?
They allow 500 request per day on the Free API and unlimited on Premium API
Up to you if you think you surpass the 500 request per day limit @fallen spoke
As far as local scanner I like Malwarebytes, up to you which route you follow.
Thank you so much, I appreciate it
Scanning your file locally is going to use up Resources, so your going to have to likely upgrade at some point your local server.
I see, thanks for the heads up, I think doing it locally would be cheaper than having to buy access to the virustotal api in the long run
do they provide a way to control with python? I looked online and they dont seem to have anything
hey guys, how do i make my webpage properly react to zoom?
right now i have this problem
67% zoom
the background img doesnt change at all, but all the other stuff
Normal, without zooming
@fallen spoke the paid version of Malwarebytes offers CLI Scanning, try looking for a anti-virus that offers CLI Scanning for free, if not look at automating this yourself.
hi,
def get(self, request, format=None, **kwargs):
quiz = Quizzer.objects.get(slug__iexact=kwargs['slug']) # case insensitive LIKE clause
questions = Questions.objects.filter(quizz=quiz)
answers = Answer.objects.filter(question=questions) # need help here
serializer = QuizzSerializer(questions)
return Response(serializer.data)```
how do i get all the(list of) answers object for the questions(list of objects)?
I want a serializer which will return all the questions and thier options for q quiz
Can you point me to a good resource about django async form validation. (no reload). ?
and , How do i verify a phone number by sending an SMS to it. ? any api's to achieve this ?
How to leverage django rest framework to achieve the form validation?
While still being able to get the csrf protection
You can use FETCH, send a request to you server where it sends a SMS and in your page you await for a reply with the code sent all this without reloading.
@near bison
This is just the basic idea. i was talking about how to acheive this with rest framework and how to validate on the go. (before submit)
@native tide yeah React is different from Vanilla JS, thought the difference would not be so huge but I can see why it would be hard to understand Vanilla JS starting from React
Ah I don't use the REST framework, and validate the code on the go would be done with JS on change state of the input field? @near bison I mean I would simply achieve all of this with JS and FETCH
Thanks 😄
@haughty turtle Is it necessary to render the form as a django form object ? Does this method prevent csrf atttacks ?
@near bison Are you using JS? If so, you can do form validation on the client-side and that would be easier & faster than having to wait for the server's response.
Yes. vuejs
@haughty turtle So with vanilla js were you using node.js?
@near bison So you could just render your form through vue.js and validate your inputs. If you need your Django backend to validate any inputs, such as whether a username / email exists, you could make an API endpoint with rest_framework and make requests to that endpoint from your frontend as soon as your form is submitted.
I recommend using the axios library over fetch, it has some advantages over it.
Also what do you mean by this:
"Can you point me to a good resource about django async form validation. (no reload). ?"
Meaning that when you submit the form, you want to page to not refresh right?
If I'm going to start a django project that will eventually be deployed somewhere, is it fine if I start using a private github repo with the default security settings? Or should I clean those up before I even start a repo?
@near bison Via JS you add a CSRF token directly into your request
Why the IF doesnt execute when i enter 1 in the input?
input always return a string, so when you type 1, the eleccion variable is actually '1'
Either wrap the input() in an int() (int(input('blah'))), or compare eleccion with '1' (if eleccion == '1':)
Thanks, I realized a second later 😅
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
list2 = [1, 1, 1, 2, 3, 5, 8, 13]
print(list2[list2[4]])
Hey guy
why the list 1 show me 8, i thought it was 5 and the list2 show me 2 but i thought it was 3, like we count from 0
@fleet heart You are accessing your index wrong
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
Here you are getting list[4] which is 5 then using that to get list[5] which is 8
It's like doing
list = [1, 1, 2, 3, 5, 8, 13]
x = list[4]
print(list[x])```
You are doing the same for list 2
list2 = [1, 1, 1, 2, 3, 5, 8, 13]
x = list2[4]
print(list2[x])```
btw is it recommended to name a variable with the name of a class?
NO
I mean is list an appropriate name for a variable?
list is built into Python, not recommended at all. @tacit flare
Thanks!
How to make django use normal user db for for superusers instead of auth_user?
wait why django is not enough for web development, why I have to use javascript? the tutor said so but everything I did was possible in django?
because websites are powered by js and JS opens new ways to interact with the DOM and more
You can't really make your page interactive without JavaScript. For example, you can't do dynamic fetching or sending of messages with just HTML/CSS
At the core, you need javascript for web development
@manic frost Isn't that what django do?
Django does not exist in the browser.
Browsers can only execute JavaScript.
The only way you can update the data on a page without JS is to reload it and simply get new HTML from the server
DOM = documeny object model its the way you interacte with HTML, CSS
from javascript
I saw a video on youtube where he updates the status of online/offline users without reloading the page
so basically the only way to do that is with javascript?
yes
nicee
Yes, basically, the browser page is stored as a nested tree structure. "DOM" is just a fancy name to make it sound more complex
Yeah, sorry for that, I am just used to the term
Wait so should I still use django ?
yes, I meant I am sorry for using it in this context :0
Django is used to do the backend stuff, for example, implement your application logic, do authentication and authorization, and talk to the database.
Can you link me to a tutorial where someone uses Javascript and Django together
Yes, you should but be sure to also get started with Javascript if you plan on developing a web application
Javascript is kind of easy I saw it once, hope I can get used to it fast
They don't connect to each other. For example a quiz that tell you the answers after completion can be made in JS. But for storing the results for further use django is the best option.
You understand?
They always go togheter, but they do different things.
Also, pesonal note that I haven't done and I feel sorry for it. Learn TypeScript while/immediatly after learning JavaScript.
It will make it much easier for you in the future.
It's just like C++ for C, TypeScript just adds more features.
oh
So, what you learn in Js applies to TypeScript anyway
Thanks btw, Imma spend this whole week to learn javascript
You don't have to rush it. 🙂 just have fun and build simple websites on the way
Start with JavaScript
React, Vue, Angular they are just frameworks you have to know JS beforehand
But as I mentioned, most of them work better with TypeScript (especially Angular)
You are welcome, my dude!
just make sure to have fun!
Semi-off topic, but whats the best way to install node js for a django app running on ubuntu?
I keep getting AttributeError: 'User' object has no attribute 'pk' when trying to use django admin site
How do I store something like a token on client side like a token? cookies? local storage? something else? and how do I do it on django ( I want something that works both on mobile apps and on browsers). this might be a stupid question but I have never used any of these before so bear with me please
What ID?
I literally go to the admin site and it errors
It started out of no where
How can I share a website over local wifi? For example I run a django server on my laptop using pythgon manage.py runserver. How can I see that website on my mobile (connected to the same wifi)? I think this can be done using ngrok but I want a simpler solution.
@versed python get the local ip of your pc that hosting django , add it to ALLOWED_HOST in settings, run the server with python manage.py runserver 0.0.0.0:8000 to expose port 8000, after that you can access it from your phone in the same wifi network with "your local ip":8000
type ifconfig in your console
I found mine using npm which shows it if i change the default host
your local ip will start with 192.168
however django doesnt
it does
what does npm have to do with this?
did you ran django with python manage.py runserver 0.0.0.0:8000?
I am working on an npm project. I just gave django as an example
@versed python then you need to find out how to expose port with npm
Actually you already solved it
I found my ip using the command and tghen changed the npm host
Thanks!
you are welcome
does this channel also include whatsapp bot development?
Django question => Lets say i want to render the same thing on all pages, I use a layout template
How do I now pass in some variables which are needed on every page.
This could be done when **rendering **something in the **view ** with the use of the CONTEXT parameter of the render function but that would be repetitive. Is there any other way to do this without repeating myself?
you can make your own base View class where the context value is predefined
like how the generic views do it
thanks
wait, lemme get the docs
this
do look up some examples online
with a simple google search
Now I am curious to see how generic views handle their context 🤔
I think another way is have a base view which inherits ContextMixin and define your own get_context_data method with some defaults in place
I have not tried it tho
but worth trying out
just like how they set kwargs.setdefault('view', self), you can do that for your values
a little more setup is required
I will try this method later and let you know
or just have a method like this
def get_context(**kwargs):
return {
"name": "someone",
**kwargs
}
``` and invoke it while rendering the template @smoky terrace
return render(request, template_name, get_context(some_info="idk", age=20)
web dev using python? 😂
that sounds horrible, my friend did it once and basically balled his eyes out and got nowhere
Would that be a good idea to make a website by using Django and using js in it? Or simply start with js?
Hey all,
I was hoping someone can point me in the right direction.
Basically I wrote a text based game in Python that asks for input from the player and prints to screen various text as part of the game.
Essentially like this:
What will you do?
walk
Player walks
What I'm trying to do is have people be able to play the game on my site. So essentially, on a page have a part where the user can input text and then the games prints to an area on the screen and this continues until the game is over.
I was looking into AJAX requests, and even having a Python IDE be rendered on the site as to run the code using Skulpt, but I'm still at a loss on how to implement this.
Can anyone point me in the right direction?
is there a way to extract all the clickable points
of a site knowing almost nothing of html
clickable points means get you to another link
already get
can someone pls help me with drf here?
thanks!
you can use Selenium or BeautifulSoup
im failed at both
then learn the basics
pls ping me when help, thanks!
just to use the methods defined in there..
you can share your code with us, wherever got stack
url_input = ('url:')
r = requests.get(url_input)
print(r)
print(r.content) # The output is too long
well let me format the code, I thought nobody would take it seriously
by clickable do you only want hrefs for button elements or all the hrefs
button elements
I believe you'll have to first understand how the buttons are implemented on the given site, but if they are just <a> tags with a btn class then it should look something like this.
`from bs4 import BeautifulSoup
body = requests.get(url_input).text
soup = BeautifulSoup(body, 'html.parser')
links = [a['href'] for a in soup.find_all('a', {'class': 'btn', 'href': True})]`
why do you think it sounds horrible
The issue is now closed
This really helped me a lot, thanks! I think its worthwhile to check, too, regarding drf serializers circular import errors
you can use django channel https://channels.readthedocs.io/en/stable/ to implement web socket and perform changing on the website, websocket is used alot to get terminal on website
or AJAX way with https://terminal.jcubic.pl/
i would use the websocket method if it's a game
just an example https://codyparker.com/django-channels-with-react/
@o0o0keem#9279
Thank you. I did take a look at jQuery but hit a roadblock. I'm going to look more into websockets!
Can i run js in console ???
@sinful helm yep web dev with python. It's extremely popular.
@strong umbra in the browser console? Yes
Ok . But in cmd or power shel ??
powershell is just different GUI of cmd, they are basically the same
sounds like jumping through a lot of hoops just to use python instead of just using a javascript based backend
not to mention u still need to code the frontend in javascript, so its not like u are gonna avoid learning js
like what hoops...?
havent used it much but it just seems like u will need to use python + js + html + css
which seems a lot more complicated than just using js + html + css
by that logic
you could say that the only viable backend language is JS
never experimented with it too much cuz my friend had a horrible experience just coding a dropdown list while i was already done with a fully functioning website with animations, graphics and backend
good for you, I guess
for web based backend, probably?
...but if said dropdown list was in Python...
that sounds like vanilla Django
not really sure how popular that is, and it's defo showing its age
we had to run an algorithm in the backend which took about 15 seconds to run on mine
there are definitely reasons to use other languages
and on his it took 60 seconds
sounds like bad code
cuz python was slower than js, also probably cuz he sucks at coding algorithms
pythons slower than js too
there are plenty of reasons to use another framework
/language
type safety
better abstractions
shrug
it's not that simple
typescript is a thing
it is, but at the end of the day it's dynamically typed
also, there are complex type constructs that you need effort to emulate in TS
although I must say it's getting there
idk if it has better abstractions tbh, maybe it depends on the user, but i always found js to have better abstractions than python cuz u could have finer/easier control with what u wanted to do
which means that the onus is still upon the dev to ensure proper typing
I don't just mean Python
I mean another language in general
e.g. higher-kinded types
you can't do that in TypeScript
it's based on how you code the algorithm, not the speed of the languages
gotta google that honestly, no clue what that is
and are you actually limited by the speed of execution...?
when its only 2-4 times as fast/slow, it also depends on the speed of the language tbh
oh yes, definitely, in the case of our webapp we were
it is rare that you are actually CPU-bound and it's language overhead that's slowing you down
and if it is, well
you have options.
Cython, PyPy, etc.
for example, the same code I wrote in c++ ran in 5seconds or so
true, depends on the application
but in any case
I'd say
if speed is that crucial
maybe Go or something would be more appropriate
I think that when building a web backend
Python doesn't shine particularly well...?
if speed is what you need, just code in assembly 🤣
Can I discuss stuff about selenium here?
sure
@stiff karma it's related to web so yeah you can
but if you're using it for testing then maybe #unit-testing might be more appropriate
😂
I needed some help with my code, can you look in #help-chocolate
it's not testing
It's more like fundamentals
It's giving me a stale element error
Even after I have used it to remove exceptions
tbf i got the algorithm to work under 100ms eventually
just for an example there already a web framework in python that can run as fast as nodejs https://fastapi.tiangolo.com/
FastAPI framework, high performance, easy to learn, fast to code, ready for production
it may also be because i dont like python as much, things like unmutable strings, and not being able to have a proper for loop still kind of frustrate me
Did anyone take a look at #help-chocolate
what do you mean proper for loop
as for mutability...honestly I prefer immutability in all things
maybe you not discovered everything yet of python, loop in python can have alot of implementation
but, yes, that's a preference
as in, being able to say, i++ in the for loop itself
perhaps
u dont use python to code front end do u?
I don't think many people do
Brython is the only thing that lets you AFAIK and that's experimental
like
for i in range(0,100):
if(condition):
i+=1
hmm
yeah in that regard Python is more functional
depends on how you want to write your code, I guess
wdym?
like
can u do that in python?
the thing you just post can be doable in python
no, "functional" in the sense of "functional programming"
afaik u cant, but if u can, thats pretty dope
hmm
hmmm
yeah
or C++
or java
or javascript
yeah, generally lower-level languages
hmm
if you look at FP languages (poster child: Haskell), there are no such constructs
thats why i liked javascript, cuz in that, u have for i in array, but u also have for(i=0; i<len; i++)
you can also access index in python
you use different abstractions to approach such problems
so, yeah, if you want to write that kind of code then at least in that aspect Python is not suitable for you
it like, combines the fine control u have from languages like C++ with the higher level language benefits
it's based on preference
i know, but that wasnt the issue
there are ways to do that in other languages
it's just a different paradigm
but yes, I suppose JS lets you do that
for one of the things i was doing, i wanted to skip the next iteration in the loop
continue?
so i would need to code a while loop
next interation
^
so u would need to make a bool, and then continue next iteration, then set it back to false
which is pepega
probably using a while loop would be easier at that point
hmm
it's like
okay e.g. in FP languages
the purer ones
there is basically no mutable state
AT ALL
big oof
which is probably not something you would want to work with, right
i dont get
but there are such paradigms
because immutability eases reasoning
just do both
why not?
you take away certain optimisation opportunities
makes no sense
such as lazy evaluation of everything
mutability -> side effects -> no pure functions -> you need eager evaluation
i think its the opposite isnt it?
cuz once u have immutability, all your code will be less optimizable
not necessarily
so if i want to change a single value in the string
NOTHING is eagerly evaluated (which is its own problem but I digress)
because EVERYTHING is pure
comparatively, if it was just mutable, i could do it in o(1)
it's only O(N) if you need to keep the old string
otherwise it can be optimised to O(1)
string = string[:-1] + "s"
ye so if there are no references to the original
you can optimise away the copy
ofc there are
and just modify inplace
and even if there are
there are data structures
which are optimised for such use cases
otherwise i wouldnt call it replace
such that you don't need to copy the string
thats what im saying
have both mutable and immutable data structures
and let the user decide
which they wanna use
the point is
some things are language-level
and built around the assumption that data is not mutable
at all.
and you can have immutable data structures for which modification is constant time, or very close
and let the developer deside
u are basically taking away functionality that could be there
by that logic
might as well include everything you can think of
which leads to bloat
sure, but that doesnt matter
it's pretty wild
not much at least
why does it not?
something being part of the standard library means it is part of the standard
because if its not bloating your program, whats the problem?
therefore there are upkeep obligations
that is why the C++ standard is so convoluted
and its not like python is particularly fast, so even if it did slow down a little, doubt anyone would care
and the language is so difficult to pick up
its difficult to pick up?
it's not about speed/size of your program, but the language
I would think that C++ is significantly more difficult to pick up and get good at than most languages
pointers are complex for most people
hmm perhaps 🤔
especially DOUBLE pointers
pointers are super useful tho
undefined behaviour is scary
it's not about usefulness
but about user-friendliness
they are orthogonal concerns
the point is C++ is hard to learn because it is close to the metal AND throws the kitchen sink at you
so basically pythons a language thats easy to code in, but not necessarily the best to code in?
that's what I would say
it's an excellent prototyping language
but not really something you want to build a huge project in?
I guess you CAN
like honestly
a super simple task
i guess i also particularly have a problem with it cuz we have to make a project in it for our college assignment
even for something like JS
and its pepega
to run or to code?
to code
probably something like
yeah
i pretty much only found it useful for data science and such tbh
okay, what would you write?
cuz of all of the useful libraries and math functions and matrices and tensorflow
3 to 9 right?
ye but the point is you need the array and the sum
array.reduce(function(a, b){
return a + b;
}, 0);
(reduce is a very FP thing btw)
mhm
yeah, that's 2; what about 1?
(JS has really nice lambdas btw)
yeah it does
in Python it's nice to have just sum(range(3, 9))
and you can prototype stuff REALLY fast IMO
although to be fair
JS is quite quick too
in terms of dev time
but JS also has really weird behaviour sometimes
[...Array(6).keys() +3]
e.g. coercion to string wy default when sorting
hmmm
it is
thats why i say pythons fucking lit for data science
but i doubt id wanna use it for much of anything else
that's a type error btw
well, not actually an error, but that won't give you what you want
cuz even if i wanna do something basic like skip the next iteration in the loop, id have to go through a bunch of hoops
you could map the result
if python had mutable strings and good for loops, it would literally be my favorite language ngl
yeah Python is not really built for that kind of thing
I have almost never had to write that kind of for loop
what trouble of using a simple 1 line of continue?
I will note that Python's strings are bad for in-place modifications, though
but then again my question is
u cant do that if u want to skip the next iteration
sec, ill see if i can find my code
you mean this ?
for i in arrays:
if i == a:
continue
print(i)
fuck, i think i lost it
nope
no
something like this:
for element in data:
if skip:
skip = False
continue
result = process(element)
if result is None:
skip = True
i was basically trying to make a calculator that takes a string as input, for example "22x3+33(3x9)" and gives all the steps leading to the answer
thats pepega
use while loop instead
I was illustrating
and then?
had to do a lot of string manipulations that would have been easier with mutable strings
or rather, you would have
even something as simple as trying to add a value to the end of the string
means that u have to rewrite the whole string
afai can tell
probably not the way I would have solved it
which doesnt seem efficient at all
it's not
how would u do it?
but that's the consequence of solving it that way
parse the expression into a tree of nodes and recursively simplify
shrug
- would u be able to take into account the order of operations
- recursive algorithm :cringe:
depends how u implement it i guess, the way i have seen it done seems very inefficient
how would u implement it?
implement which part
building the tree
okay, that seems a bit overengineered for this problem unless you're doing it for fun TBH but
not sure if python has a tree data struct, if it does, i havent used it yet
split the expression into tokens
yeah, how would u do that?
regex
but I think (not sure though) there is also a Python implementation if the C module is not available
wouldnt make sense to manually code it in for loops and such
well
for certain edge cases Python regexes take exponential time
(not a problem specific to Python)
oof
but in this relatively simple case, yes, would be fine
but more than efficiency...it would be more comprehensible IMO
btw, how would u use regex to tokenize it, the issue too is that u need to split it but still include all the operands
but thats what im asking 😂
parentheses, operators, and numbers
how would u still include the numbers and the operators, if u split it, wont one of those be gone?
no
you can split on boundaries
!e
import re
print(re.split(r'(?<=a)(?=b)', 'splitabsplit'))
@vestal hound :white_check_mark: Your eval job has completed with return code 0.
['splita', 'bsplit']
like that
but over there..
splitting on the boundary between 'a' and 'b'
you might not
22+33
but you know the class of characters it can be
u can have 23+44 too
sure
is there a class of characters for +-/*^ ?
in regex?
cuz u can also have
22+sin(45)
python basically seems like, shove everything into one line and use a bunch of inbuilt functions/libraries to do it (not saying thats a bad thing, tho it reduces the control u have over your own program sometimes imo)
you can make one
this is a bit more complex
hmm
yes
this is the philosophy
batteries included
thats the issue i was running into
which can be problematic
but then u end up with 1 line code thats basically unreadable
because you lose sight of what the abstraction conceals
like, the fuck does this even mean 😂
return stringExpression = stringExpression.replace(i, str(evaluateMathFunction(
mathFunction, eval(i.split("(")[1].rstrip(")")))))
i have no clue 😂
and i wrote it lmao
!e
import random
import re
operands = ['+', '-', '*', '/']
regex = r'(\d+)([+/*-])(\d+)'
exp = f'{random.randint(0, 99)}{random.choice(operands)}{random.randint(0, 99)}'
print(exp)
print(re.split(regex, exp))
@vestal hound :white_check_mark: Your eval job has completed with return code 0.
001 | 29+49
002 | ['', '29', '+', '49', '']
hm I should get rid of the leading and trailing spaces
yeah probably 😂
(which occur because I'm splitting on groups)
but yeah that's the basic concept I guess
of course if you want to handle parentheses it grows more complex
and it would probably make more sense
to use a regex to find tokens
than split like that
evalis dodgy though
import random
import re
operands = ['+', '-', '*', '/']
regex = r'(\d+)([+/*-\(\)])(\d+)'
exp = f'{random.randint(0, 99)}{random.choice(operands)}{random.randint(0, 99)}'
print(exp)
print(re.split(regex, exp))
what if u did this?
it is
did what
and im not gonna use it in the end
oh
to seperate at parenthesis as well
probably not so simple
cuz u can have
because a parenthesis must be matched
22+(2*2)
in js or c++ i could just keep copying into a string till i ran into a "^-+/*()[]{}"
and then copy into the next element in the array
well thats something u figure out once its tokenized
well, at least thats what i was gonna do
but i was also using stacks, probably wouldnt work with recursive trees
a friend is asking me for help, so im sorry if i take longer to reply
basic question: how do i make the transition smooth when maximizing/restoring for all the UI elements in general ?
async?
i tried applying it to body element(to apply to every element) but i don't see any change
not sure what that is honestly tbh man
i just know that if u dont want your UI to hang during a lot of processing, u either load it off to server side or use async programming to do it
sorry if i'm not accurate with my terms.
simply i'm applying a transition effect on width change
ohh
u would use a library that does it for u
or
use css
(easier to use css tbh, much easier)
.divclass {
transition: width 0.5s linear;
}
UI doesn't hang but when resizing to a smaller window or to a larger window, few of the elements take little time to adjust and appear stuck for a sec
and yes im using css
so u want it to be instant?
i tried body { transition:width 1s ease-in-out; }
try less time duration
and maybe use linear
ease in out will be slow in the start and the end*
ohh
so try transition: width 0.5s linear;
but it seems like it didn't apply at all i didn't see any change
will simply applying to body apply to everything ?
probably yeah
smh
but it depends
if your sections width is defined by the body
for example, width:100%
then it will probably adjust to the body too
but pretty much everyone uses css grids now, which is what i would also recommend u to use
i tried linear and 0.5s that makes the main window transition slighttly smoother but within elements don't resize instantly and appear stuck for a sec lol
so ig i've to make changes to every element lol
and also @import doesn't work for loading local CSS files
why ?
nobody uses that to load local css files tbh
@import "navigation.css"; like this?
never used it so i cant say tbh
i always used sass and compiled it into minified css or just used a front end dev framework like svelte or react to manage my css
u dont want to create too many files as that increases load times, use sass and compile it into a single minified .css file
or just include it directly into your html
@sinful helm thing is there's no HTML and only css. Is there a simpler way of including local css files into the main CSS, web files work well
i applied that to some of the components and it improved it very slightly
Hey guys, I have a django related question
from django.db import models
# Create your models here.
class Meta:
db_table="Newpost_db"
db_table="Newnews_db"
class Newpost(models.Model):
url = models.CharField(max_length=100,default=None, blank=True, null=True)
date = models.CharField(max_length=100,default=None, blank=True, null=True)
desc = models.CharField(max_length=300,default=None, blank=True, null=True)
target = models.CharField(max_length=100,default='_blank', blank=True, null=True)
class Newnews(models.Model):
url = models.CharField(max_length=100,default=None, blank=True, null=True)
date = models.CharField(max_length=100,default=None, blank=True, null=True)
desc = models.CharField(max_length=300,default=None, blank=True, null=True)
target = models.CharField(max_length=100,default='_blank', blank=True, null=True)
``` this is my models.py. I'm trying to create a table for my news posts as well as my 'post' posts.
I also used django rest to create an API to automatically create these posts, and it all seems to work except for one part:
Only one table is made sadly, and 'newnews' table is nowhere to be found. I did the migrations, but I'm unsure what I did wrong.
Does anyone know where I can start troubleshooting?
have you actually added the models to the admin page?
Oh I did not, thank you :))))
what type of website would the following be?
it has login facility
it has articles/blogs that can be written only by admin/owner
i need the name for the type of website so that i can research in future?
If you need a website for articles/blogs which is super easy to setup I'd just go with Wordpress to be honest.
Most cloud providers have a pre-installed image for a wordpress website when you host an instance with them, making it reliable and easy to setup.
Hello folks, maybe one of you can help me. I'm fighting with Django's ORM to be able to write the same kind of query as this one:
select id, max(coalesce(last_validation, creation_date)) from transactions group by user_id;
The closest I got is with the following queryset:
Transaction.objects.annotate(last_updated=Max(Coalesce('last_validation', 'creation_date'))).values('user', 'last_updated')
The problem is that the group by clause encompass all the model fields, not the one I select from values
i agree but i want to make my own website from scratch and all
so i am using flask also can you help me on how my blueprint should look like ( i am not sure how blueprints work so can you give me some learning resource link )
found my solution, in case it is on anyone interest: Transaction.objects.values('user').annotate(last_updated=Max(Coalesce('last_validation', 'creation_date')))
I needed to indicate earlier that I'm interested in user. The values() will force a group by by all unique combination of the given field
I'm not that well versed in this all, so I'm not sure how to help you Ranger, sorry.
I tried creating an API for my 'posts(not POST)'/news requests. For some reason, my my posts are being saved, but my news is not.
api/newpost is saved, api/newnews is not. Anyone have an idea where I should start looking?
they were implemented identically as far as I know
Found it! Typo somewhere 😉
hey all
question for you guys if you can help
i have a form i'm trying to render onto my homepage, but i want to place the code for the form in another html
my views calls that nested html from page
my home page includes the nested html page
however when i load the server the code, the object doesn't pass into html
Hey, I was creating a web app using flask that uses ml model to generate a file so when a form is submitted by a user with the relevant data I used a function to transfer the data to the model and the file was generated and used the send_file() function to send the file to the user to download but the generation of file is taking 30 secs or more and the page keeps loading as the file is sent after the function call returns which generates the file. The time to create file can't be reduced as model is slow but I don't want this reloading as http response shouldn't take that much time and its bad practice. Can anyone provide me with a alternative?
I just want to first render a html file that says generating your file and when file is ready I can send it to the user to download. Please help
@native tide So with React I only have one html file? this being index.html? so if I want to change the content in my webpage entirely this is done by unmouting the current component and mounting a new component on click? So if its like this my url never changes I imagine then, if my url was google.com it will always be google.com no matter where on google.com I am navigating?
@haughty turtle Yep, if you want to have different routes you will use react-router library. It will just show a component when you visit that URL
Hello
I am reading about Django and React integeration. All the videos and blogs that I went through were using "Django rest framework" for building REST API for backend and communicated using AXIOS in frontend.
We can build a REST API on Django without using Django REST framework.
So I was wondering if we could use axios POST/GET in the react frontend and connect it with REST API at the backend which is NOT built using DJANGO REST FRAMEWORK?
I am wondering the same thing also, I am building it without rest, rest seems to be used for serialization purposes I believe
I think not using REST is fine, I will be doing the same thing.
maybe the problem was your friend's proficiency and not the language.
yeah, I've done that before. JS frontend, django backend
Perhaps, but doubt it, his main language of use was python
And he was decent at it and could do other stuff fine
Just wanted to avoid having to code in HTML css js but had to learn it in the end anyways
But I think he still didn’t use css so the website looked garbage
small question, what does DEFAULT_PERMISSION_CLASSES in DRF actually mean? according to docs every one of the specified classed must be met for the request to be acted on by the server but using IsAuthenticated still allows users who are not signed in. can someone explain what it does?
And then he just scrapped it cuz mine was so far ahead in the development process and was a lot more polished
lmao, I dont think you can make a website without html, css, and js... Python was just for the backend
backends are usually either python, java or js frameworks
school project?
I would just use js unless u really need server side backend. Even then, I would personally still use js backend frameworks but u can use django if u want
oh, sounds cool
Yeah
Yeah
But if u have learnt js HTML css already, I don’t see why u would also use python for the back end, but I guess if u really love python that much
¯_(ツ)_/¯
Sometimes php 😂
Like our college websites 😂
For whatever reason they use php even tho it’s a relatively new college
my case exactly, I've been using python for a few months, nearly half a year... I've come pretty far... I'm not so good at javascript... pretty basic... currently use django just cos I'm doing an online course that requires it in 2 projects
I guess the devs are used to using old languages... or used a website builder
If u wanted to do frontend/UI based backend then u would still probably just use js or a js framework right?
Cuz of dom api or reactive frameworks
Hmm, not sure
yeah, you could use both
They use sql for databases and php to fetch em
Both as in js and js frameworks? Or js and django?
js and django, I guess the first case is also possible
but I also guess the reason people use frameworks is to be more efficient and easier than vanilla js
oh, I thought you meant backend of the entire system
for ui, i'm not sure django is used
Yeah
yeah, THAT
@kindred osprey axios is just a request library similar to fetch, it can be used with any backend
DEFAULT_PERMISSION_CLASSES sets a default permission class across all of your API endpoints, so you do not have to set permission classes per endpoint (per view).
If you have set a default permission class and it doesn't seem to work, show us a snippet of the view it's not working on so we can see what's up.