#web-development
2 messages · Page 200 of 1
Why isn't my smtp code working on pythonanywhere.com if it works on my computer?
Does the service require you authorize certain IPs?
Or maybe an environmental variable isn't set correctly in prod?
hello, I am working making a web application with flask, I am trying to make a graph with chart.js, I am really new to js but I am not sure what I am doing wrong here
https://paste.pythondiscord.com/acetayijol.xml
the graphs should be going in the spaces
Hey everyone, I am deploying my django site using nginx and gunicorn. I am using this repository called django-social-auth-app which allows the user to login using any other third party apps or social media. In my gunicorn config I bind it to the localhost IP:127.0.0.1:8001, on which of course nginx is listening. So therefore whenever I go to the machine's IP, I can see the site, and everything works.
But the problem is, that when logging in using the above stated repository, after having logged in, and when it redirects you back to the site page, it redirects the user to 127.0.0.1:8001, and not the machine's IP. I tried binding gunicorn to the actual machine IP, but that breaks all the other functions that depend on the server IP (e.g. websockets, api requests, etc...), and also it is really not the best thing to do.
If anyone has ever faced some issue like this, can you please help me?
i think its unrelated to gunicorn
or nginx
its django
that produces invalid redirect
yeah, ik that it has something to do with the repository, which is what I am trying to work out rn
is that repo public?
yep
It's like the biggest social auth repo for python
You can use it on either flask, django or anything else literally
I have tried to change the login_url and redirect_url settings which the repo provides, but it didn't help
can you link the repo
I've used that repo and I don't remember setting anything outside of Django to make it work.
It should hit an endpoint in your backend that then redirects wherever you want it to.
@glacial yoke
Yeah I get that, but what I also realised is that when you try to login it sends you to the local host IP, even thought it’s clearly set as the machine’s IP in my settings.py
So it’s something with the redirect uri
Which is what I’m trying to figure out rn
ok, I fixed it
In the end I had to change all the SOCIAL_AUTH settings to redirect to my server's IP
I also had to add my server IP to the redirect_uri's
then I added a few proxy settings into my nginx config, and it all worked
Is django good for a microservice setup? My goal is to develop multiple tools to use for my personal game studio including:
User registration (via api, or via website)
User authentication (using Json webtokens or OAuth2.0)
Matchmaking service usinng buckets and websockets
Metadata server (holds server information, player counts, locations of datacenters...etc)
I've been reading mixed information online where people just give their opinions, but I'm looking for a legitimate answer, not just opinions.
Unless you can specify what factual information you are seeking, you're only likely to get more opinions here. "Is Django good..." is inherently a question of opinion. What does "good" objectively mean to you here, and what you are comparing it to?
If you're asking whether it is normal to use Django for the tasks you have listed, yes it is. If you're going to build a site with all those features using a Python framework, Django is the obvious choice. What else would you use?
Surely. Django works the best for your voiced goals in a Django Rest Framework setup
https://www.django-rest-framework.org/
Django will provide the FASTEST development.
The only disadvantage of django, of not working fully in async, which can be probably fixed in next version. Partial async support is still there though, just Django ORM is still sync. But really.... async is often not even needed in most of cases.
Even for async Django can work though. Django channels is an example of Async oriented Django to implement chat.
For pure async setup, fastapi is better.
Does FastAPI have the same amount of functionality as Django?
Django has a lot of stuff right out of the box, I have no interest in building my own user registration system, Django Admin basically has that right from the beginning.
Different amount of functionality.
in FastAPI you are going to setup ORM on your own, SQL Alchemy or whatever is your choice.
But FastAPI brings A LOT of out of the box too. For example auto generated interactive wiki for your REST API. Open API or smth like that. Fast API just brings different stuff out of the box
Ah I see
The only thing I worry is if this game I'm working on were to scale up, I worry that having a completely synchronous ORM could be devastatingly bad long term.
FastAPI has some sort of quirks with enforcing good static typing i think. That's one of the advantageous of it that enforces better quality. I heard only rumors about FastAPI, I worked closely only with Django.
Honestly though, I imagine it wouldn't be that difficult to just simply treat each Django 'app' as a separate microservice and then as for the ORM part, couldn't you just run each completely indiviudally?
Like I imagine you could just copy + paste the base directory + the app you want to a new machine and do that
Well... super high scalling up guys just don't accept ORMs... so it should be not a big worry, if it is sync or async 😉
that's not working in this way.
Django Apps bring just module separation for cleaner code organization/testing.
For real microservice architecture you need to deploy django applications to different servers.
quick question. Should I be using status code 404 or 401 for failed login attempts?
user not found/wrong password
401 sounds like much better to return.
that's the one I was leaning towards, thanks
I feel like there is no batteries included python framework for microservices
Lol
Django is fully battery included to the top. and DRF is exactly for microserves.
Some people choose to return just general error "Login or password is wrong", that prevents hackers from web scrapping correct logins/emails.
with having different errors, you could confirm them existing emails for scrapping emails or reducing difficulty to crack
What is DRF
https://www.django-rest-framework.org/ battery included framework, to make REST API out of django
To work purely as backend microservice that returns JSONS for example
Django, API, REST, Home
What I'm doing now is raising an HTTPException and returning "Invalid credentials" with a 401 status for both incorrect password and user not being found in the db.
oh i dont want to go that hardcore lol
i still dont mind server side rendering of views
im not willing to buy in on these front-end frameworks yet
like Vue and stuff
hehe. I dived into Vue.js, it is awesome
It's just not where I need to be right now
I'm trying to make a game, not a website lol
hardly seeing how you are going to make a game properly without reactivity that bring frontend frameworks.
I suspect you are going to reinvent the wheel in going vanila js and remaking poorly some frontend framework.
web games usually involve a lot of client side interactions
Not a web game. I'm using unreal engine.
I'm planning on using the website to store player data, authenticate users...etc
oh, so the game is for Windows platform then
Well for now yes, but I have experience on consoles
I've used PS5 dev kit and my co-founder has experience with the ps4 dev kit
But we need licenses to use them sadly
What do you mean?
programming language for the windows app?
C++
I got a weird question…. It’s about code (not Python code), but not exactly.
I’m learning JavaScript from W3Schools. Starting the tutorial or guide or whatever it’s called, they show a little bit on how to change elements on the page, and then go ahead and teach about variables and stuff…
I wondered if I can learn the stuff that really changes the page before I learn about the more technical stuff.
Will I get confused, or it’s okay for me to do that?
I want to start with these thing
Firstly I would say that w3schools is an.... online reference handbook
That's not really suiting for real learning, but good to use when u already know stuff
I would highly recommend to learn javascript from the book at the bottom
And going through its material in the order in the book
And yes, it matters to understand javascript concepts first before diving further in my opinion.
That book looks really old school 😄
It is really good one 😉 It helps to understand mechanics behind javascript
I see.
like... javascript implements half of other programmings languages concepts with just a different application of functions...
I don't see how it is possible to learn it without it
So I’ll just start with technical stuff (variables and stuff) and then have fun with the html stuff
?
yeah
I see. Well, that’s all I needed. Thank you!
/
subscibe my chenel
||please like and subscibe my chennell||
click only humans not bot
404 is page not found. I suggest a 401 as in this case it stands for "unauthorised"
Anyone familiar with using celery with a docker container?
Hello I have created a voting site to vote for some merch designs for my school, but it doesn't work on some apple products (some variables are passed wrongly or changed of value) does someone know why could that be occuring? Its a flask python web app
That's not enough information. It's like asking why the pipes in my friend's house are leaking even though in my house they aren't.
Is bigening spelled that way on purpose?
When I have more info I'll come back then
does JavaScript .length on a variable with [[x, y] [z,k]] return 2 or 4
I believe 2, as it's measuring the length of the outer array.
[0].length would measure the first array inside
<form method="post">
<label class="switch">
<input type="checkbox" name="cumulative" {{cumulative}}>
<span class="slider round"></span>
</label>
</form>``` how do i post it
Post what?
i wanna update a db and make it input on or off in the db when the flip the switch
im trying to figure out how to run the code when a user interacts with the switches
You need to use something like ajax if you're doing it from the html.
If you want it to update based on the DB.
You can just simply post it to the view and cause a css change without waiting for a return from the view though, which is probably better. So it only has to check the DB on a page refresh.
im using flask
i should be able to do
something like
if request.method == "POST"
then it can see what the values are
which will then run code
Ok, sounds good.
ok but why isn't it posting
show code again
What's the view look like
if you use request.args then change it to request.forms
<form method="POST">
<label class="switch">
<input type="checkbox" name="cumulative" {{cumulative}}>
<span class="slider round"></span>
</label>
</form>```
flask should say tho if it posts
even if i dont have the correct code to handle the post
Don't you need javascript for it to post onClick?
How else does it know to submit to the view?
you need a button with type=submit to submit the form
its a checkbox
he wants it to submit when it changes
I just don't think that can be done without an ajax call unless you're ok with the page refreshing after it submits.
hi everyone, what do I need to know to write a django website, other than django itself and html?
If it's backed by a database, which I'm assuming if you're using Django, some knowledge of data models would be helpful. You may pick that up along with Django, but it can be a discipline onto itself. A little css to make it look good would be great too.
solved, .path turned out to not be 'universal'
had to use .composedPath() instead as it is accepted in more browsers and devices
Yeah, using it exactly like that
any pointers to this?
I'm bashing my head, I've put celery same container as the fastapi app, but that's not a good workaround
thanks for good advice
😄
Check logs, what s writing your worker
Obviously with raising rabbit first
It does not receive any task
It should check report that it connects to rabbit
yes it connects to rabbit
U can manually connect to rabbit and check all values inside
otherwise I wouldn't be able to use celery container in local app
Hmm
"If I start the webapp locally on my computer, and don't start the padel-checker-web-1 container and only use the other 3, celery on docker syncs with it and works."
but it's not a framework issue, if you observe the last img of that post
I'm just invoking celery on the container
and it just hangs
Hmm
so it has to be some kind of problem in communication between containers, that's my guess
because "outside" if I use my IDE to use that celery instance, it works fine
Actually yeah, the celery code is almost not touching framework at all.
So framework is not issue
Anyway ...
First request all values inside rabbitmq, to confirm it did not write info it
Then I guess just debug your celery code, some issue there
How is that problem in my code if it works outside docker :d
Worker reports which tasks it discover, perhaps it is not seeing it
🤔 this problem I did not have for sure
environment:
- C_FORCE_ROOT=1
I'm even using this
it's a docker issue, but I'm not a pro in docker, so I can't get where's the problem
flower works, celery connects to rabbit, rabbit works, web app does not work
Hard to say, I used redis instead of rabbit 🤷♂️
ok ty anyway
Plus I did it without compose
Because I wished deploying them to different servers
For better worker scaling
Although I did it with compose in the past
I can give u my old compose for this
version: '3.8'
services:
web:
build:
context: .
dockerfile: dockerfile
volumes:
- static_volume:/app/web/build/static
expose:
- 8000
env_file:
- ./.env.${mode}
depends_on:
- redis
nginx:
build: ./nginx
volumes:
- static_volume:/app/web/build/static
- ./ssl:/app/web/ssl
ports:
- 5555:4000
depends_on:
- web
# celery
redis:
image: "redis:alpine"
expose:
- 6379
volumes:
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf
celery-worker:
build: .
command: celery -A core worker -l INFO
env_file:
- ./.env.${mode}
depends_on:
- web
- redis
celery-beat:
build: .
command: celery -A core beat -l INFO
env_file:
- ./.env.${mode}
depends_on:
- web
- celery-worker
- redis
volumes:
static_volume:
static-content:
I guess it is not really useful for your case, or may be it is?
anyway the best is auto generator of cycling tasks. I used it instead of cron in this case
u don't need the beat
I'm actually using something on fastapi to repeat tasks
Not using anyhing like beat or cron
@app.on_event("startup")
@repeat_every(seconds=60) # 1 minute
async def fetch_data() -> None:
for example
heh
my silly old compose had too many values hard coded 😉 Although since it is compose, it is not an issue
because compose stuff uses relative service name addressed links anyway
so there was no point to dehardcode the links
yeah
ok
if so ima make it a pop up on the bottom of the screen
maybe a long shot, but is anyone familiar with an audit log framework for python/django?
I've fixed it
something focused around the view level rather than the orm, because half of what I'm doing is using django as the frontend and talking to other non-dbms systems
weird. 😉
I am deploying them all independently to different servers without any order and it is all fine
dunno, now it works. It's weird indeed
please
any Js / apps script god
help me implement this https://github.com/tanaikech/DateFinder
my monkey brain just cant it wont work

i give up on the toggle switch
someone just make me a button that when i press it posts and toggles
like a check box
but without having to click on the check box and then click submit
make you a button...
i cannot find anywhere how to do it
I am trying to make an assignment organizer, in this assignment organizer, I have an app called calendar which has a model events, I have google authentication. I added a method to add events but each event shows up even when logged into different accounts. How can I fix this
i found out my problem is it only posts if i have a submit button
how can i automatically submit
I told you how to do it with ajax.
or post without it
But it's up to you.
where
i see it
onClick
but how do i make it work with the switch
When you have the view, you can filter by posts created by that user.
When the checkbox is clicked, you can toggle the css with javascript and also update the database with an ajax call all without leaving the page.
That's the logic. How to implement it, that you'll have to try to figure out first and we can help you when you're stuck.
how would I do this?
What's your view look like?
Hey @native tide!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @native tide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Just show me the view for the one template, not all of them.
This is a web or mobile app?
web app
What framework?
django
Ok, so your view controls what you see on the page, yea?
yeah
So show me the view that controls the page with the posts you want to change.
Where you query your database for the events.
here you go:
def event(request, event_id=None):
instance = Event()
if event_id:
instance = get_object_or_404(Event, pk=event_id)
else:
instance = Event()
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('calendarApp:calendar'))
return render(request, 'cal/event.html', {'form': form})
This doesn't display events on your page.
This gets one event and displays the details it looks like - and submits them.
Is your problem that you are displaying events for all users on a page, and you want only to show events that the user created?
yeah
give me one second to locate it, I forgot where I put it
@dense slate would it be in the views.py of the calendar app itself? or would it be in another file
Do you know how views work generally?
You go to a page of your app website, and then the request is sent to your Django backend to figure out what data to show on the template. This is called your view.
So the view asks the DB for data based on what you want, and then you return it to the template, right?
So this should be in your views.py.
this is my first time working with django in 5 years so I've forgotten essentially everything sorry
It's ok, I'm just trying to teach you a bit along the way.
So you understand how it works. 🙂
I actually think this was present in my utils.py
from datetime import datetime, timedelta
from calendar import HTMLCalendar
from .models import Event
class Calendar(HTMLCalendar):
def __init__(self, year=None, month=None):
self.year = year
self.month = month
super(Calendar, self).__init__()
# formats a day as a td
# filter events by day
def formatday(self, day, events):
events_per_day = events.filter(start_time__day=day)
d = ''
for event in events_per_day:
d += f'<li> {event.get_html_url} </li>'
if day != 0:
return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
return '<td></td>'
# formats a week as a tr
def formatweek(self, theweek, events):
week = ''
for d, weekday in theweek:
week += self.formatday(d, events)
return f'<tr> {week} </tr>'
# formats a month as a table
# filter events by year and month
def formatmonth(self, withyear=True):
events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month)
cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n'
cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
cal += f'{self.formatweekheader()}\n'
for week in self.monthdays2calendar(self.year, self.month):
cal += f'{self.formatweek(week, events)}\n'
return cal
so in the events_per_day we should be filtering by user as well
but what exact command would do this
I tried this and got the error: Calendar has no attribute request
So what is that you wanna make?
I want to make a assignment organizer, part of the assignment organizer includes a calendar feature and google authentication. In the calendar feature I want then to create and display events, but then even if I am logged into a different account, it shows events created by other users
ok
@random sand as you see in the utils.py above, when I add events to the calendar, I only filter by day, how do I filter by event
not by event sorry, I mean by user
I'm assuming that self here is a calendar instance?
So it won't have a request attribute. Request is a parameter passed from the webpage/template to the view.
You have to somehow list the events where request.user = event.user
like events.objects.filter(event.user=request.user)
from django.db import models
from django.urls import reverse
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
start_time = models.DateTimeField()
end_time = models.DateTimeField()
@property
def get_html_url(self):
url = reverse('calendarApp:event_edit', args=(self.id,))
return f'<a href="{url}"> {self.title} </a>'
this is the event model, do I have to add a user field
and how would I automatically initialize it to the current signed in user
Yea, events should have an author/user field that is a ForeignKey field that points to the user row.
What do you mean by automatically initialize?
never mind about that, I think I was wrong all along
it's like when you hit submit to add the event to the calendar, we initialize an event object and we set the author field =user.uid
That's really vague. It depends how you use it.
request.user will work in your views.
def myview(request):
etc...
def event(request, event_id=None):
instance = Event()
if event_id:
instance = get_object_or_404(Event, pk=event_id)
else:
instance = Event()
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('calendarApp:calendar'))
return render(request, 'cal/event.html', {'form': form})
so now we just set form.author=request.user
right after we declare form
Hi there, how would I be able to send my javascript variable in HTML through to to python to be used? Thank you
what would the type of the foreign key be as well?
I don't think you can send it through HTML, you would have to use JSON
fr i would rather upate the db in python not js
Using Javascript?
@dense slate for the foreign key, we would have to access the social accounts model, how would we do this?
yeah
I'm not sure I can picture how it relates all together off the top of my head. When you hit the social auth api, it should come back to your endpoint, which is where you do whatever you need to with the information.
The ajax call is what calls your view and does whatever you want to your DB.
It's an async call from your front-end so that you can do something without refreshing the page.
If you update without it, you will have to do a page refresh.
What do you mean here?
I mean I don't know how to access the information, we have a social accounts model which was automatically generated for us, I don't know how to access this
sorry don't worry about this
Yea I don't know man, you're asking some big questions without me seeing any code so I can only speak in theory at this point.
When you ask a social auth api for a login, it sends you information back. Like a refresh token, etc.
You have to do stuff with that on your end to make it work with your app.
ok so for example we have to do this to retreive a social account
user.social_auth.get(provider='facebook')
in our case, it's google
but where would I call this
If you press "login from google" on your website, I think it has to go directly to a social auth link that you get from the API. That API should be setup to then send a return response to your backend endpoint.
Either that, or the button activates a view on your backend, where you call whatever function that is you wrote.
The library you're using as your social auth should have documentation on how to set this up.
ok I think I Just got it working thanks!
Sweet. 🙂
I was trying to do an inference of a PyTorch model using django rest API. I am new to django rest api. can anyone share some resources are suggest me how to do it if anyone worked before on the same problem. Previouly i used django api and did inference by keeping all the pytorch code in views.py but now i saw the same thing done on models.py while using rest framework and using axios.js and corsheaders I am pretty confused.
Will anyone test my flask code
pytest will gladly test your flask code
https://flask.palletsprojects.com/en/2.0.x/testing/
https://realpython.com/pytest-python-testing/
Ok
@inland oak but my code is genuine and working as html
And no problem with flask at all it is running but doesn't get desired output
@inland oak
read about all types of testing, and cover the code.
otherwise it is just a ... guessing where it went wrong
for frontend things, u can test in python at least with selenium.
Ok
Apps Script (JS)
how the fuck do I find a cell by date
.textFinder() doesn't work
tried finding by unix, also doesn't work
spent few hours yesterday I'm hopeless at this point
googling "javascript find in array by date" and opening links
https://stackoverflow.com/questions/27450867/how-to-correctly-use-javascript-indexof-in-a-date-array
For more help with googling, provide bigger code example
lmao
@inland oak I done testing and the code is genuine I think there is a problem with blocks can you check it
which blocks? I see no blocks.
TypeError
TypeError: 'method' object is not subscriptable getting this error when running flask need help
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
if request.method=='POST':
solute = request.form["solute"]
solvent = request.form["solvent"]
else:
solute = request.args.get["solute"]
solvent = request.args.get["solvent"]
results = predictions(solute, solvent)
response["predictions"] = results
return flask.jsonify(response)
http://127.0.0.1:3000/predict?solute='CC(C)(C)Br'?solvent = 'CC(C)(C)O' using this url to see the prediction in json format
please help i have tried but i am unable to figure out where i am doing wrong for long time
Use '()' instead of []
on request.args.get["solute"]
(and solvent ofc)
Now I am getting this error.
Is this the correct way to give input in url
my inputs are # solute='CC(C)(C)Br'
solvent = 'CC(C)(C)O'
I've never used boost python
but if you want to pass multiple args in the get, you use &
like this
@sacred crane
Your response probably isn't something serializable, like a dict
can you print me your response?
or try something like this:
return flask.jsonify({'result': response})
But I think you have to convert Tensor data to a serializable form probably
Are you using Tensorflow?
Thank you I am using pytorch
response["predictions"] = str(results) adding str() here resolved the problem
yeah that's why str won't work
I am planning to use this result to show in a react website
You have to find a way to serialize your torch obj
do:
print(results)
print(type(results))
and show me the output
you can hook this piece before the response
serialized_results = {k: v.item() for k, v in results.items()}
return flask.jsonify({'predictions': serialized_results})
try this
@sacred crane
tensor([[-3.4333]], grad_fn=<AddmmBackward>)
<class 'torch.Tensor'>
@grizzled basin adding results.item() solved the problem i guess
tensor([[-3.4333]], grad_fn=<AddmmBackward>)
<class 'float'>
@sacred crane good!
Hey, I'm looking to build an e commerce site, using django. Just looking to get the general gist and what I need to learn before, I want to make it so it's easy to add products from a UI, meaning that a user can add pages of html/products without actually doing html or any of that. Anyone got recommendations to some info related to doing that? Not sure if this kind of thing got like a name
There are loads of of tutorials and examples online like https://github.com/justdjango/django-ecommerce and https://www.freecodecamp.org/news/how-to-build-an-e-commerce-website-with-django-and-python/
An e-commerce website built with Django. Contribute to justdjango/django-ecommerce development by creating an account on GitHub.
Learn how to build an e-commerce website with Django and Python in this full course from JustDjango You will learn all the steps for developing a complete e-commerce site, including: Setup and project configurationAdding items to a cartImproving the UICreating an order summaryThe checkout processHandling payments with StripeDiscount codesManagin...
NEED HELP - Each time someone send request to my application i have to check their token with a yaml file in server. So i have to load that ymal file each time someone send request. Can i do something where I don't have to read that yaml file each time. Insted maybe django can load it one time in starting and Store that token into a veriable. And keep updating that veriable every 10 to 15 min from yaml file. ?
@wise kite I can help if it is flask
It,s django. But solution should be kind of same bhai . Isn't it ?.
is it possible to change my maintenance page from an ip whitelist and htaccess to a login form
alot of people dont trust givign there ip addresses to get past it and i want the page to have a login form to bypass the page
I've never heard of someone implementing auth from a file. Why did you decide to do it that way?
Rather than keeping the token in the DB.
So i can change the token and some other details without needing to restart the server
What framework are you using?
Because you shouldn't have to restart the server just because you update the DB.
If you load the yaml file once at build time, and then need to change it, you'll have to restart the server to re-read it each time you change it.
Django. I might not. But my senior dev is Java dev he don't know anything about django. He said i have to do it that way . So i have to. It will be convenient for him i guess.
Wish I knew what to say in that case. I don't really do a lot with direct file accessing.
Maybe using something like SQLite?
I think that saves as text if I'm not mistaken.
I have a 25 lines of story displayed in a webpage. One user can select a word/number/symbol or anything in that page with their mouse select.
can I get:
- the word itself
- the line number
-index number
To my backend flask app?
Which approach should I take?
Thank you!😊
One can upload a story file, he/she can select a word or anything from what's displayed on the screen. To the backend, we should get index number, line number
@wise kite yes, you should better using Sqlite.
The point of Django of having easy database management with its ORM
if you aren't using it... u aren't using Django
Reinventing the wheel with going for YML stored self written database is just plainly horrible
it is fine to use YML for one time setting up settings from the code though
Anyone here know any website where we can get the Time complexities by entering the code?
xD coded first layout today. It is relaxing, and I succeded! yaaaay!
Going full Vue.js, loving its ecosystem
Thanks gods for the flex zombies game https://mastery.games/flexboxzombies
Like... everywhere just using flex boxes ;b they are fine to remove almost any positional problem ;b, since they allow nesting.
Interested to go through Service Worker mastery game too though 🤔
Because u know... it looks like cool stuff to have
That music.... when playing flex zombies. Makes u writing layout code as super easy. You remember how your life was depending on it!
I needed to write syntax fast enough to aim my crossbow and kill the zombies!
Awesome game
Interesting I've never seen that.
Epic level of quality game 😉
After this game u'll remember the syntax as your reflexes
Have you used React? Are there some drastic differences?
I had a colleague who used React. So I am partially (and only very briefly) familiar.
not having enough knowledge to compare. I can say that Vue has state management easily out of the box, which is simple to use.
Global state or just state?
for global state I mean
Thanku i will try to convince my senior dev about it
for local state, in one component everything is easy and simple
we have there static JS things, computed JS things and some custom things I think.
Vue gives easy reactivity to any data, and allows easily to setup reactivity in both directions between rendered and JS data
Component writing is easy, just create another file with Html, Script and Style section.
Vue is mostly not interfering into Html code too much
It has Django/Jinja like syntax for inserting data into Html, with exception to binding Properties and writing loops, which has more HTMLish looking syntax
{{ here we have full javascript language compatibility to insert data }}
I don't know react to tell you differencies, but Vue is nice and easy to use and learn 😉
Setting up I18N is easy too, going out of the box
out of the box, I can have everything, even examples how to write unit and e2e tests
btw, I love SASS. SASS is Awesome
I did not reach that section, but Vue is also bringing some of its own addition to have more features to CSS animation I think.
oh btw, like React, Vue has its own Nuxt.js, which allows Server Side Render and Static Site Building
I'm curious how you handle caching in the future. I've never used redis so I cache everything on the front-end with Next/Apollo for a big speed boost.
Yes I've seen that as well.
Hehe. Going to find out that soon.
I have 3 weeks to implement my project at least, purely for frontend
or more, considering requests to setup Payment system, and monitoring+logging requested things to monitor business stuff
during those weeks going to become intimately familiar with Vue
I'm wondering if using redis can actually get an even better speed boost in addition to FE caching.
I used redis only in backend framework
I can say that it is needed only for framework level logic to cache stuff from database for example
but I think it would be much faster to use...
Nginx/Traeffic as web accelerators, they will provide caching copy BEFORE request reaches the framework (when we set them up as reverse proxy to our backends)
I think that's faster ;b
no idea about how the same stuff is handled in frontend yet. Except for knowing about browser storage existence and cookies 🤷♂️
Fascinating. I am using JUST A FRACTION of flexbox powers!
with killing all flex zombies (https://mastery.games/flexboxzombies/), I feel like I'll have
help
heroku
did you try to look at the logs
does anyone have experience with streamlit?
for some reason everytime I click on a st.number_input to put in a number my app just goes blank
not showen
In django-channels is it possible to add jwt authentication?
I'm using django-rest-framework-simplejwt and is it possible to implement jwt authentication when a user is connecting to a consumer? won't sending the token in the query string have security issues?
Why would it have security issues?
Have you tried nuxt 3 yet?
I'm not sure if it's worth learning or just sticking with nuxt 2
Hey, I'm having trouble integrating a S3 storage on my django project (i'm using jschneier's django-storages ). I want to manipulate the Content Disposition metadata to ease my backups (I want to write them using a UUID as filename, but populate the contentdisposition filename so users can download it with a friendly name). I've opened a question with more details at #help-rice
@inland oak Sounds like redis will be good to cache server-side even if you use client side caching when you have a high number of users:
Client side caching improves the performance for the clients. But if the number of clients is high, you can experience high load on the server side resources which will eventually affect the client side performance too.
Makes sense.
if request.method == 'POST':
print(request)
return "success"```
ok so
uhhh
why does the request only look like this
<Request 'http://127.0.0.1:5000/dashboard/880574219560321104/api' [POST]>
how do i get the data
nvm, i got it
Below is the code used to fetch the rest API predictions in react app.
function App() {
const [state, setState] = useState([{}]);
useEffect(() => {
fetch("/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O")
.then((res) => res.json())
.then((data) => {
setState(data);
console.log(data);
});
}, []);
In fetch /predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O here solute=CC(C)(C)Br and solvent=CC(C)(C)O are the inputs for the flask rest API to give predictions.
But I want to give it from the frontend rather than mentioned in the URL. How to do it?
this is Javascript React
Hello!
I'm developing a Flask app, and I'm a beginner in this. So here is my script:
from flask import Flask,render_template,request
app = Flask('')
@app.route('/')
def home():
return "Hello World"
@app.route("/test",methods=["GET","POST"])
def test():
if request.method == "POST":
# getting input with name = fname in HTML form
inp = request.form.get("testinput")
# desc = request.form.get("desc")
# getting input with name = lname in HTML form
return "Test input: "+inp
return render_template("testing.html")
``` And my testing.html
```html
<!DOCTYPE html>
<html>
<head>
<title>Testing</title></head>
<body>
<h1>Hello there</h1>
<form action="{{url_for('test')}}" method="POST" id="tst"
<label for="testinput">Input: </label>
<input type="text" name="testinput"> <br>
<button name="gennew">New input</button>
<button type="submit">Submit</button>
</form>
</body>
</html>
``` But I want when I click gennew button, it will create a new entry right down this button. How can I do that?
Where do you wish new entry being stored?
In server database?
temporally in user browser?
Temporally in user browser
Um, I just want when I click the button and then an input being inserted right after it in the browser, and later I can access it too 😄
They I would say that u use wrong tool for that ;b
Flask is not meant for this. React / Vue.js will work much better.
You can still do it in Flask it though, but u will need working with Vanilla JS. At least if you wish the data being shown without page re render;
We can simplify things a lot your syntax writing in Flask for this purpose, at the cost of sacrificing time to update the page 🤔
Mm... all right, so in order to do this simply in flask... We should probably use Cookies! They will allow you to use relatively easy client side storage while accessing easily as server
Lets write pseudo code how it will looks like...
Client side form
Pressing button => Invoking POST request with new value
Server receives piece from POST request data
Checks user cookies
Combined result rendered back, with attaching updated cookie to client
yeah, it would be simpliest way to do that if we have Flask (at the cost of having requests to server every time with re rendering page every time we press button)
more complicated (and a bit ancient) approach would be to use Vanilla JS in order to do that without additional requests to server, manipulating user DOM purely client side
more modern solution would be to use frontend framework
How do I run a piece of Python code when a button on my website is clicked? I'm using Flask.py and failed to find the answer elsewhere.
I don't think you should post this here. #game-development would be a better place. I'm not a moderator so feel free to do whatever you want.
google: flask set cookie, flask get cookie
https://stackoverflow.com/questions/46661083/how-to-set-cookie-in-python-flask
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('somecookiename', 'I am cookie')
return resp
# This way cookie will generate in your browser but you can get this cookie in next request.
@app.route('/get-cookie/')
def get_cookie():
username = request.cookies.get('somecookiename')
it is regular Javascript, that is used to manipulate browser DOM
https://www.youtube.com/watch?v=cuHDQhDhvPE
See for yourself difference in how to do the same with Vanilla JS or with frontend frameworks
I built a simple app with 10 different JavaScript frameworks... Learn the pros and cons of each JS framework before building your next app https://github.com/fireship-io/10-javascript-frameworks
#javascript #webdev #top10
🔗 Resources
Full Courses https://fireship.io/courses/
Performance Benchmarks https://github.com/krausest/js-framework-benc...
in 99% cases they are still enabled anyway. almost no users disable cookies fully, because it will break all web sites
they just decline interactive agreement at some specific web site, it is purely your logic, not theirs
some users erase their cookies after browser is closed though, but it will not prevent you from making your functionality
@trail veldt actually the video shows exactly what you wished to make 😉 adding entries with button and input
See for yourself how it is done in Vanila JS and other frontend frameworks
Oh yeah I see, because I see many sites have something like
This site uses cookies to improve your experience...
it is a juridical issue, that araises from EU laws at least
according to their rules web site should ask and explain why they track user with cookies
you see, cookies can be used for evil... for tracking you for advertisements and etc
2021-11-11T08:27:10.802264+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="xxx
" host=xxxx-xxxx request_id=c0aee3b4-67f2-410c-af70-c00d747257d5 fwd="156.211.170.33" dyno=web.1 connect=0ms service=30204ms status=503 bytes=0 protocol=https```
**this is a heroku logs whin i upload a file .zip or . rar it says like this in the image**
help plz
☝️ minecraftclub1.herokuapp.com, I like it.
?
what would you do?
deploy a website?
no i deployed the website but i have a field file field i but a file in it it gives me this err
so how to fix it
Yo these worked! Thanks
U a welcome 😁
There is btw even more old school solution btw..
..instead of using cookies, you could have been using query params to accumulate the data (basically in user url)
url/?data=stuff&anotherdata=stuff
it could have been used for your case in the same way. A bit awkward way tbh, but who judges.
but cookies I guess should be more comfortable.
I saw a stackoverflow post explaining the issue in passing the token in the query string
You create forms, link their values to a state object and send them as query params to your backend. The basic stuff..
Is it possible to create a website using markdown with style formatting (hosted on github pages) ?
it should be completely possible. I do the same in gitlab pages.
how?
oh wait. I tell wrongly, I just commit directly to repostiroy my markdown pages, github/gitlab pages aren't even needed.
just writing markdown, and having relative links, they work fine in gitlab
im talking abt creating a website
what u assume being a website
How do I run a piece of Python code when a button on my website is clicked? I'm using Flask.py and failed to find the answer elsewhere.
You can create a view, connect it to a URL and add this URL to your HTML form.
If you write more info on what you want to do, I can make a more detailed response.
Hi guys, Is there any channel I can post my latest work on?
Since Python has APIs unlike JavaScript (not Node.js), I want to use Flask.py to make a button. When the button is clicked, a Python function should be called.```py
This is my current code.
import flask
app = flask . Flask (
name
)
@ app . route (
'/run-python-code'
)
def run_python_code () :
return 'Trying to run Python code...<br><button>Run Python code!>/button>'```
??
what u understand being a website
🤷♂️ all right. So anything hosted in github pages, even text file will be website for you
I'm starting JavaScript. I'm confused thinking a better way to run it. My friends suggest to use Nodejs since I'm familiar with cmdline.
Other one said that I can run js in browser, by creating snippest inside chrome dev console. Although I don't understand what he meant, I think I really want to know this
Can we actually run Js inside a browser? Just like writing inside an interpreter
Vanilla js without html
Or nodejs would be better?
how would i format it 😕
like the background colour, font styles etc
afaik only html&css can do that
is it possible just to have an external.css and markdown for the content?
Browsers can execute javascript, if you don't need to do browser-specific things, e.g. DOM manipulation you can run it via nodejs
I'm trying to get started with Django and i'm a little confused about the overall structure of the project. I know that I should create an app for a blog for instance, or a forum, but should I create an app for my home page? Or do I just use the files that were created when I used startproject?
@umbral rock If you have some individual parts of your project that are not highly coupled you could split them into different applications
My plan is to first off create a homepage, then start to expand out by making a planner app, a blog app etc. I'm just a bit confused as to whether I create my homepage in my project folder or whether I should create an app for my homepage
It depends on what you mean by homepage in this case, if it's some sort of static landing page i'd make it separate app
Yeah, it's going to be static. Thanks 🙂
does anyone know some reference material for Django rest and taking in parameters? I can do it with regex and taking the full endpoint but I was wondering if there is a better method?
There are lots of markdown to html converters if that's what you want. Pandoc, for example.
Yes, you can link to css to handle the extra style stuff.
I personally like org mode in emacs, similar to markdown and emacs makes it easy to re-export and update your web content with a few keystrokes.
does anyone know how to use BeautifulSoup4 to parse html strings?
ping me if you've got the answer or you can point me in the right direction, thanks! 😄
oh thanks!
How to rectify cors error
I have my FE (next) and BE (Django) in separate directories on the same server. I'm trying to upload a file via GraphQL via the BE and have that file be saved in the public directory of my FE but I'm getting:
Detected path traversal attempt
There a way around this? I can only upload without an error if I upload to my media_root directory within the Django project. If I try to go above that level, I get this error.
Well, besides markdown, there is really similar ReStructurizedText syntax.
You could use Python tool Sphinx
Which allows to write in this syntax...
...as for styles, you can choose at least a dozen of premade stylings which are available in the tool.
Perhaps more little adjustments to elements is possible.
But that's it.
And... actually you know.. if u don't want to deal with HTML and CSS
but u a wishing to have still relatively customizable thing capable to change background / fonts and e.t.c.... You are probably looking for WordPress.
does a symlinked directory work?
Can we get a domain for free
I'll look into it, but the lack of Google answers really makes me think I'm either approaching this the wrong way, or it's supposed to be possible and I'm just doing something wrong.
oh, how do i use sphinx or 'jekyll'
is 'jekyll' md?
jekyll is smth similar alternative, but I never used it.
I have an example of how to use Sphinx in Github in the simpliest and dumbest way
https://github.com/dd84ai/darkbot
Just copy folder sphinx from here (and requirements.txt with scripts.py file and scripts folder)
in project settings enable github pages from docs folder
install dependencies for sphinx (and click library) from requirements.txt
use python scripts.py sphinx build command in order to build your website to from source to docs folder
(or manually delete previous docs, create folder docs, make empty file .nojekyll in docs, and write command sphinx-build -b html sphinx/source docs)
change sphinx folder files to match your desired RST documents
this setup is silliest and dumbiest, because you need to commit your docs folder to repostiroy in order for this way github pages to work 😉
it can be made smarter with pipeline and artifacts, but whatever.
xD I even commited my database to this repository. I was really lazy this for pet project.
well, it has its benefits. it is really easy to migrate and maintain at least.
but what idk is make.bat, config.py, makefile etc
don't touch make.bat and makefile, they were auto generated by sphinx initialization, they aren't needed.
tbh they should be deleted probably, if it will not break anything
hmmmmmmmmmm
whats 'jekyll' again
no idea, I have just .nojekyll file, that disables it from my github pages, that's it.
some sort of alternative to sphinx it is
probably another way to format documentation easily
...well, I mentioned command for building above
using python scripts or manually writing sphinx-build
make.bat and makefile do the same basically, but without dependencies to click library which i have
doubtfully.
sphinx requires installed dependencies
replit is highly likely aren't having them
what are those?
packages?
pip packages.
oh yeah repl has them
what is the best wed-site development maker?
huh
@lethal void did you just test a forum you filled out that could have an attachment (cv, resume), but you didn't attach a file, and the code assumes you have
oh let me check on it
what do you mean?
thanks for the help, now it's running , so yeah I just attach ah cv file inside the admin panel and now it's ok thank you
Good to hear
at which level, backend framework, frontend framework or CMS
Hi All, a beginner's question from my end. In web development, why would you choose JS over Python for backend, or vice versa?
so whats the best way to create a site for personal use, easily?
it should only need basic html and css coding
and categories+search bar
and thats it. no fancy url or other features
That's my hosted made with Sphinx
the one to which i gave source code
it has automated menu and submenu handled by sphinx
https://dd84ai.github.io/darkbot/info/begining.html#help
search bar is there
there are different themes to choose, I liked this one
idk how to use sphinx :/
and ill have to learn it
it is quite simple to learn
whats the diff between mkdocs and sphinx?
which ones better, which one should i use
I have no idea what mkdocs is
oh
its just like sphinx
used to create doc sites
all i want to do is
create something that can easily display my markdown files
so that its easy for the user to view them
with some decent navigation
looks like i should just create a gist 
response = {}
@app.route('/predict', methods=["POST", "GET"])
def predict():
if request.method=='POST':
solute = request.form["solute"]
solvent = request.form["solvent"]
else:
solute = request.args.get("solute")
solvent = request.args.get("solvent")
results = predictions(solute, solvent)
print(results)
print(type(results.item()))
response["predictions"] = results.item()
return flask.jsonify({'result': response})
``` I have build a rest api using flask. when i give `/predict?solute=${form.one}&solvent=${form.two}`; then i get output. but rather than changing the query in url i just want to change url like `/predict` and want to get the output. Because i want to access this in a react frontend
Hey guys, does anyone here knows how to make swagger generate documentation for APIView in DRF? It generates docs for generics like ListAPIView but for APIView I need to write schema manually, what does generics have that base view doesn't and makes swagger/redoc/coreapi work? I just get empty method without parameters
@thick sinew You need to manually specify request body and responses using swagger_auto_schema in case of drf_yasg
class SomethingAPIView(APIView):
@swagger_auto_schema(
request_body=serializer.SomethingCreateSerializer(),
responses={
status.HTTP_201_CREATED: seralizers.SomethingSerializer(),
}
)
def post(self, request):
serializer_in = serializers.SomethingCreateSerializer(data=request.data)
serializer_in.is_valid(raise_exception=True)
data = serializer_in.validated_data
...
that helped, thanks a lot!
Anyone can help me with android devp? Trying to bring data from firebase and put in recycle view in app and having a problem there
Help, i'm trying to do a folder with the environment files of my project, but the proyet don't read the files. Im using django-environ 0.4.5
error:
django.core.exceptions.ImproperlyConfigured: Set the PROGRES_DB enviroment variable
my code:
ROOT_DIR = environ.Path(__file__) - 3
env = environ.Env()
environ.Env.read_env(os.path.join(ROOT_DIR, ".envs/.local/.postgres", ".envs/.local/.django"))
.postgres file:
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=cride
POSTGRES_USER=postgres
POSTGRES_PASSWORD=my_password
i'm trying to import the 2 envs files, .postgres and .django, but i don't know how
Hello guys
I need your help in Django
How to make like api endpoint that returns json of all users from database?
{"result":{"predictions":-3.5411367416381836}}
```How can i access the floating value using javascript
Hello guys
I need your help in Django
I had to make like api endpoint that returns everything from the database in json format
I wrote code like this and it kinda workedpy def identity_json(request, *args, **kwargs): data = list(identity.objects.values()) return JsonResponse(data, safe=False)
It looks like this
but i also have many to many field that doesn't show up there in json
Is python a reasonable tool and what in that case what packages? Goal: generate a one-page html with headings, some paragraphs of text and some images.
django
...
what do you mean?
you probably have a while true of a for loop continuosly running
i dont understnad what you are trying to do
so you send a request and it sends json format back?
i get everything except characteristic adn characteristic is many to many field
If it's not dynamic, ie doesn't use a data or create content dynamically, just use html/css
when i go to http://127.0.0.1:8000/json it shows me json
so whats wrong w it
?
If you need a database/business logic/etc then python and django is a good choice
It doesnt show up characteristic in json
Try looking at select_related() . It sounds like you want related objects in your json. You might also have to write more logic than you have to make that happen in the way you want.
i got a question
:0
{% extends 'main/base.html' %}
{% block body %}
{%for car in all %}
<div class = "container">
<div class = "table">
<div class="row">
<div class="col-md-3">
{{car}}
</div>
</div>
</div>
</div>
{% endfor %}
{%endblock %}```
```{'BMW M3 E30': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Dodge Charger': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Polestar 1': {'price': '$', 'description': '', 'seats': '', 'url': ''}}```
cant find the bloody
price
i guess its javascript
💀
it seems quite .. big, for such a small task, but perhaps not
{{all[car]["price"]}} no?
the basic example has a lot of python files https://docs.djangoproject.com/en/3.2/intro/tutorial01/
its html
not inside {{ }} it's not
it's python
well yes
but im making a for loop
Did you look at the docs for selected_related
Also Im no interested in running python on the webserver, I just want a plain html generated and host that
cool
🏅
Then just write html/css and host it. Or use a static site generator. Pelican (if it still exists) is Python based. Others exist for Ruby.
I would prefer to no write html, but maybe I just should. It's just, kinda boring 😐
ok thanks
right, you're looping through your dictionary
{'BMW M3 E30': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Dodge Charger': {'price': '$', 'description': '', 'seats': '', 'url': ''}, 'Polestar 1': {'price': '$', 'description': '', 'seats': '', 'url': ''}}```
i just dont understand how to read inside the BMW M3 E30 area
if you want to show price, I showed you how
no u didnt
there ya go
bossman
try {{car["price"]}}
tried it
same thing
[""] doesnt work in html
lmfao
well I use actual objects instead of dictionaries so I don't have this problem. good luck
maybe try {% for car in all.values() %}
and then past with {{car["price"]}}
Hi all, having some trouble with using whitenoise to locally serve my static files for my django website. As soon as I turn Debug to False, I can no longer access my static files. I've installed whitenoise and i've added it to the MIDDLEWARE list in settings.py, but it's still not working. Am I missing something?
The static files load fine whenever I have debugging set to True, so I think my STATIC_URL and STATIC_ROOT etc are all okay. This is my first time setting up a django website though so could be wrong.
How to install flask in pycharm
i don't know in PyCharm but you must install it from PIP in virtualenv
!code
https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html#packages-tool-window this can help if you mean install flask package
how do i get a clock to frontend, updating on every page reload???
prod_add_date = forms.DateField(label='Date', initial=datetime.now().strftime("%d/%m/%Y - %I:%M"), disabled=True,
widget = forms.DateInput(attrs={'class':'form-control'})
)
How do you handle uploading files to your backend but saving them in the front-end project folder? I'm getting a Detected path traversal attempt error.
Basically anything I try to upload outside of the BE project folder gives me this error. I assume that's to prevent uploading files that are like "../../../whatever.jpg" but then how do I actually get it there?
a little more specific?
after page reaload, catch current time
that will update automatically?
exactly
Javascript is able to give u the current time
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();```
Pulled from CodeGrepper
then just set the time variable into the element that is displaying the current time
hey everyone, looking for some assistance with my flask app and background celery tasks, tasks are executing but not going to queues i believe to be defining in the celery app conf
https://github.com/apsamuel/workshop-ctrl-system/blob/main/pylibs/sidecars/metrics/app.py
I'm defining scheduled tasks like this:
metrics_exchange = Exchange('metrics_exchange', type='direct')
celery.conf.task_queues = (
Queue(name='vmem', routing_key='vmem'),
Queue(name='swap', routing_key='swap'),
Queue(name='cputime', routing_key='cputime'),
Queue(name='metrics', routing_key='metrics.*'),
)
celery.conf.default_queue = 'metrics'
celery.conf.task_default_queue = 'metrics'
#celery.conf.task_default_exchange = 'metrics_exchange'
celery.conf.task_default_routing_key = 'metrics'
celery.conf.beat_schedule = {
'publish-vmem-60s': {
'task': 'pylibs.sidecars.metrics.app.publish_vmem',
'schedule': 60.0,
'options': {
'queue': 'vmem',
'routing_key': 'vmem',
#'exchange': 'metrics_exchange',
},
},
'publish-swap-60s': {
'task': 'pylibs.sidecars.metrics.app.publish_swap',
'schedule': 60.0,
'options': {
'queue': 'swap',
'routing_key': 'swap',
# 'exchange': 'metrics_exchange',
},
},
'publish-cputime-60s': {
'task': 'pylibs.sidecars.metrics.app.publish_cputime',
'schedule': 60.0,
'options': {
'queue': 'metrics',
'routing_key': 'metrics.cputime',
},
},
}
however those tasks are being sent to an auto-generated queue
[2021-11-12 19:09:43,990: INFO/MainProcess] Task pylibs.sidecars.metrics.app.publish_cpustats[969172b3-f99d-4512-8005-4aed0e49ef0a] received
[2021-11-12 19:09:43,992: DEBUG/MainProcess] TaskPool: Apply <function fast_trace_task at 0xb5542030> (args:('pylibs.sidecars.metrics.app.publish_cpustats', '969172b3-f99d-4512-8005-4aed0e49ef0a', {'lang': 'py', 'task': 'pylibs.sidecars.metrics.app.publish_cpustats', 'id': '969172b3-f99d-4512-8005-4aed0e49ef0a', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '969172b3-f99d-4512-8005-4aed0e49ef0a', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen18174@raspberrypi', 'ignore_result': False, 'reply_to': '870d7a81-21e5-3e32-a7db-fe8c3cb61c33', 'correlation_id': '969172b3-f99d-4512-8005-4aed0e49ef0a', 'hostname': 'celery@raspberrypi', 'delivery_info': {'exchange': '', 'routing_key': 'metrics', 'priority': None, 'redelivered': False}, 'args': [], 'kwargs': {}}, '[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]', 'application/json', 'utf-8') kwargs:{})
which i'm not controlling the name of
pi@raspberrypi:~/restart/headunit $ ./dev/rabbitmqadmin list queues
+-----------------------------------------------+----------+
| name | messages |
+-----------------------------------------------+----------+
...
| 870d7a81-21e5-3e32-a7db-fe8c3cb61c33 | 108
..
hello, im trying to make a website like https://nedbot.org/ but i dont know where to start.
you'll want to start by picking a stack.
pick a backend, a frontend, and if needed, a database, event broker, worker, etc
you should pick one with a nice acronym.
for example. MEAN:
MongoDB
Express.js
AngularJS
Node.js
What’s a good stack to use Django with? Is there a preference front end to connect to Django? Or not really?
function submitFormData() {
console.log('Payment button clicked')
var userFormData = {
'name':null,
'email':null,
'total':total,
}
var shippingInfo = {
'address':null,
'city':null,
'state':null,
'zipcode':null,
}
if(shipping!='False') {
shippingInfo.address = form.address.value
shippingInfo.city = form.city.value
shippingInfo.state = form.state.value
shippingInfo.zipcode = form.zipcode.value
}
if(user=='AnonymousUser') {
userFormData.name = form.name.value
userFormData.email = form.email.value
}
var url = '/process_order/'
fetch(url, {
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo})
})
.then((response)=>response.json())
.then((data) => {
console.log('Success:', data);
alert('Transaction Completed');
window.location.href = "{% url 'store' %}"
})
}
why are the properties in userFormData and shippingInfo in single quote? are those JS objects or JSON? thanks
Hi all, I posted asking for some help with using whitenoise in a Django project yesterday. Any help would be appreciated: #web-development message
likewise on some flask/celery/rabbitmq related issues i've been facing #web-development message
those are js objects
which fundamentally get serialized to JSON on this line
body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo})
Hello, in the django ORM is there a possibility to add a auto incrementing IntegerField and it increments by one per ForeignKey of another model,
for an example ```py
class Channel(Model):
""""A channel of a ChatGroup"""
chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
description = models.TextField(max_length=255, null=True, blank=True)
position = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
@property
def group_name(self):
return f"ChatChannel-{self.id}"
class Meta:
constraints = [
models.UniqueConstraint(
fields=("chat_group", "position"),
name="Unique channel position"
)
]``` the `position` field will increment by one per `ForeignKey` to the `ChatGroup` model, Thanks 😃
will try again later, celery gave me a splitting headache
you can create your own field that implements your logic, it's not a standard use case
How can I do that?
Within Django, If I create a templates folder within an app, do I not need to update my settings.py TEMPLATES DIRS? Or do you only need to do that if you're using a templates folder outside of your app?
Fairly certain my setup is working correctly but I don't want to run into issues further down the road when I add more apps.
I generally use postgresql and vue.js
I made a path that takes post requests, but how can i access the binary file if I want images to be sent through it?
I think I got it, except how can I save it to a folder?
@app.route("/add", methods=["POST"])
def add():
file = request.files['file']
if file:
filename = secure_filename(file.filename)
# Save to directory
fascinating. reading one book and discovered alternative way to get location of the user.
Apperently all web devices are having automatically available API... for location of the user
Making the right call, it automatically makes browser/device asking for permission to use the user location
which in turns gets precise location shown based on user IP / GPS / wifi / triangulation to cell towers
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Where am I?</title>
<script src="myLoc.js"></script>
</head>
<body>
<div id="location">
Your location will be here!
</div>
</body>
</html>
console.log("launching js boot!");
window.onload=getMyLocation;
function getMyLocation() {
console.log("launching geol on boot");
if (navigator.geolocation){
console.log("acquiring geolocation");
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("ops, no geolocation support");
console.log("alert, no geol");
}
console.log("finished getmylocation");
}
function displayLocation(position) {
console.log("starting display function");
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at latitude:" + latitude + ", longitude:" + longitude;
}
That's all that it takes
result:
accuracy: 3713.4307272065403
altitude: null
altitudeAccuracy: null
heading: null
latitude: 51.539466
timestamp: 1636814290068
all is left having a database of country/towns coordinates, to match those Earth coordinates in order to get country/town of the user.
Although, asking for user ip address requires no user permission 🤔 So it has its own advantage in comparison to geolocation API
but surely geolocation API should be bringing more precise results ;b
not really remembering seeing it actively asking permission at any PC web site though, probably it is more used only for mobile apps, i wonder if they request it in the same way or differently
So long as you add your app to INSTALLED_APPS, you’re good with just creating template directories within your apps along with the <app_name> subdirectory
That’s the setup I’ve been thinking about using
Thanks 😊
@dense slate cool graphics, neat music, nice plot.
https://mastery.games/serviceworkies
I am going to learn Service Workers usage ;b Interesting thing to learn for frontenders
Hello, I am working on a Session Security Project along with a company.
We're trying to show the impact of not sanitizing user input (Blind XSS > gets rendered on the admin dashboard via the DB > Cookie Stealing depending on the Cookie flags set.)
This works because there is an admin authenticated when the attacker sends the payload however if there is no administrator authenticated this won't work as there's no cookie to grab so is there any way in PHP to predefine variables so when they send that payload there is already a cookie or for a bot to login to the administrator session and stay authenticated?
Thanks. 🙂
I can make a bot in Python to do this but I want a second option and more better option.
I am making a WYSIWYG editor using the contenteditable attribute in divs
I have implemented font changing
I would like to know what font is the cursor on
anyone can help with celery issues sending to queues and not the default autogenerated queue please?
problem description: #web-development message
Hey, I have a simple fast api thingy that works on my local machine, but when I try to use it on a VPS it doesn't work, I mean the code runs I just don't manage to connect to it. I launch it using 'uvicorn api:app --host 0.0.0.0 8001' Do I need to change the host to the VPS public IP?
https://gist.github.com/apsamuel/04cbb2538f64a287f72e18e00ba76450 i updated the issue with more details on this gist
who can help me with allauth django?
raise exc.NoReferencedColumnError(
sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'Products.product_id' on table 'order_product': table 'Products' has no column named 'product_id'
order_product = db.Table('order_product',
db.Column('order_id', db.String(length=36), db.ForeignKey('Orders.order_id')),
db.Column('product_id', db.String(length=36), db.ForeignKey('Products.product_id'))
)
class Order(db.Model):
__tablename__ = 'Orders'
order_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
total_price = db.Column(db.Integer(), default=1)
order_date = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
shipping_address = db.Column(db.String(length=255), nullable=False)
delivered = db.Column(db.Boolean(), default=True)
user_id = db.Column(db.String(length=36), db.ForeignKey('Users.user_id'))
products = db.relationship('Product', secondary=order_product, backref=db.backref('orders', lazy='dynamic'))
def get_id(self):
return self.order_id
def __repr__(self):
return f"Order('{self.order_id}, {self.total_price}, {self.order_date}')"
class Product(db.Model):
__tablename__ = 'Products'
product_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
product_name = db.Column(db.String(length=255), nullable=False)
category = db.Column(db.String(length=255), nullable=False)
color = db.Column(db.String(length=255), nullable=False)
price = db.Column(db.Integer() , default=1)
quantity = db.Column(db.Integer(), default=1)
status = db.Column(db.Boolean(), default=True)
discount = db.Column(db.Integer(), default=0)
image = db.Column(db.LargeBinary())
store_id = db.Column(db.String(length=36), db.ForeignKey('Stores.store_id'))
def get_id(self):
return self.product_id
def __repr__(self):
return f"Product('{self.product_id}, {self.product_name}, {self.category}, {self.color}, {self.price}, {self.discount}')"
```
Have you ensured that access to port 8001 is open?
any resources for learning html/css? im fine with reading books or watching YT vids
Best book to get started, really friendly ;b
I really like w3schools.com for reference. You won’t get the whole picture, but it’s more than enough to just start doing, and you can take any html you write in a plain text file and open it with your browser to see what’s there. VSCode also has a Live Server extension that’s really helpful.
https://www.w3schools.com/w3css/defaulT.asp
They also have a CSS… suite? Called W3.CSS which makes it very easy to create a sleek web page. Also look at https://www.w3schools.com/html/html_responsive.asp
It's been 4 hours I stuck on geoserver sld issue if anybody help i will save my sss for tomorrow presentaion
<StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.1.0" xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:se="http://www.opengis.net/se">
<NamedLayer>
<se:Name>DBT_MASTER_LIST</se:Name>
<UserStyle>
<se:Name>DBT_MASTER_LIST</se:Name>
<se:FeatureTypeStyle>
<se:Rule>
<se:Name>Apiculture</se:Name>
<se:Description>
<se:Title>Apiculture</se:Title>
</se:Description>
<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
<ogc:PropertyIsEqualTo>
<ogc:PropertyName>activity_group_name</ogc:PropertyName>
<ogc:Literal>Apiculture</ogc:Literal>
</ogc:PropertyIsEqualTo>
</ogc:Filter>
<se:PointSymbolizer>
<se:Graphic>
<se:Mark>
<se:WellKnownName>ttf://ESRI Business#U+0042</se:WellKnownName>
<se:Fill>
<se:SvgParameter name="fill">#000000</se:SvgParameter>
</se:Fill>
</se:Mark>
<se:Size>25</se:Size>
<se:Displacement>
<se:DisplacementX>0</se:DisplacementX>
<se:DisplacementY>-1</se:DisplacementY>
</se:Displacement>
</se:Graphic>
</se:PointSymbolizer>
</se:Rule>
</se:FeatureTypeStyle>
</UserStyle>
</NamedLayer>
</StyledLayerDescriptor>```
on my local system its working fine, but on remote server it showing
Failed to build legend preview. Check to see if the style is valid.
when i validated its showing no error
Can anyone point me in the right direction to figure out how to populate a SelectField in FlaskForm from a database query? I am trying to make selections available to a user depending on the results of a db query. For example, if a user is a member of the "admin" group, the SelectField should show all options from 1 query, but if they are a member of the "regularuser" group, they should get a completely different set of options in the SelectField.
Using sqlalchemy with mariadb btw
https://www.npmjs.com/package/jsme-react this package is working perfectly fine in reactjs . But not working in nextjs project. can anyone one tell me the reason
what happen to our community, nobody is answering
Any help from here would be highly appreciated,
https://stackoverflow.com/questions/69964270/expressjs-how-to-cache-on-demand
when im doing flask in vscode, why doesnt suggestions popup for flask?
You mean type hints?
Probably because request isn't properly annotated as flask.Request. it's just a proxy object.
Anyone got any experience with sqlalchemy ?
@frank shoal are you familiar with jinja syntax?
Yes
is there a way to make something that after you logged in , it says your name instead of saying login?
i think theres an if statement in jinja syntax
hahah im working on this right now
i pass the name via python return render_template("index.html",name=current_user.name ,tasks=tasks)
then in the html : <h1>Hello there {{ name }}</h1>
Building a HR system
I believe current_user is a global variable in jinja
unsure its part of "flask-login"
ah.
but substitute it for whatever framework you use
then you can assign it as one.
my coding experience is so low kinda sad to see
The wish to have cache invalidated for one route, after having request to another route, makes it a bit difficult 
Essentially caching exists at levels: Framework level (redis) / Web server server side (nginx) / Client side (nginx) / Client side configurable (service workers)
Considering that you need programmable invalidation, web server server side should not work, because I don't know ways to invalidate their cache in a way that suits your case, client side caching...same problem with cache validation, I think will not work too. and I don't know enough about service workers yet.
Framework level (redis or any other alternative) should be definitely working for your case, simple algorithm
Backend:
GET request:
if cache exists, get it (for example from redis)
Otherwise make your SQL request and set cache to redis
POST request:
Delete cache (from redis)
Perform stuff
Well, actually I have another idea. U could be definitely having cache invlidation at client side level too with localstorages. example:
frontend client side
if cache in windows.localstorage exists
get cache from it, otherwise make GET request.
if u make POST request, delete cache from localstorage
then perform your POST request
if you just use flask-session, request.session.user.name
Neat, Wait do i need to use flask-session if multiple people will use the system at the same time?
maybe
hmmm, something to think about.
flask session assigns a cookie containing a session id pointing to a local file (or database record)
btw do you know much about sql-alchemy? struggling with writing a query atm
Sure, what code do you have right now?
class database(db.Model): id = db.Column(db.Integer, primary_key=True) user = db.Column(db.String(200), nullable=False) startdate = db.Column(db.String(10), nullable=False) enddate = db.Column(db.String(10), nullable=False) duration = db.Column(db.Integer, nullable=False)
My Db structure
How would i write a query to only get the results when user="ben"
I use this to get all data but i want to filter to just "ben"
tasks = database.query.order_by(database.startdate).all()
.filter_by(user="ben")
or .filter(database.user=="ben")
the Column type implements all the operators for ease of use in filter statements
so : tasks = database.query..filter(database.user=="ben") ?
hmm i get this " 'BaseQuery' object is not callable"
maybe db.query(database).filter(...)
you can use multiple models to resolve relationships.
.join() will also work
Ah wait
my bad
Working!
forgot the .all()
btw, @frank shoal Would love to see the wikipedia project your working on, Maybe DM me sometime, Happy to show what I'm working on also
my bad haha got confused with the other user
Umm I have two questions, if possible can you provide with something to begin with, in redis and
In the example, how would I know to delete cache before every cycle, because I have an mechanism that updates players, every 30 seconds (the cycle)...
I worked with redis only with python, will it work for you? Although I learn javascript at the moment, but did not try redis there yet 🤔
where is located the mechanism that updates players every 30 seconds?
no problem, I think I can figure out the javascript part...
requirements.txt
create venv / pip install -r requirements.txt
redis==3.5.3
if u wish easily raised redis, instal docker-compose and run docker compose up -d in folder with file docker-compose.yml with content below
version: '3'
services:
redis:
image: "redis:alpine"
command: redis-server --requirepass your_password
ports:
- "6379:6379"
# volumes:
# - ./redis-data:/var/lib/redis # uncomment for redis perssistance
# - ./redis.conf:/usr/local/etc/redis/redis.conf # if u wish your own config set
restart: always
import redis
REDIS_PASS = "your_password"
REDIS_HOST = "localhost"
redis_conn = redis.Redis(host=REDIS_HOST, password=REDIS_PASS, port=6379, db=0)
redis_conn.set("key", "abc")
print(redis_conn.get("key"))
P.S. redis also gives a thing for pipeline transfer of a lot of values in one request. If needed to speed up transfer of a lot of values sent in one run.
In some file:
/**
* Periodically update the `model` table, over an interval `ms`,
* with the data generated from `factory`, and call the `callback`
* after iteratively updating the whole table.
*
* @param {number} ms
* @param {promise} factory
* @param {Model} model
* @param {function} callback
* @param {string[]} attributes An array of strings to pass as `options.attribute` to `model.findAll(options)`
* @returns Interval from `setInterval`
*/
function periodicUpdate (ms, factory, model, callback, attributes) {
return setInterval(() => {
model.findAll({ attributes: ['id', ...attributes] })
.then((instances) => {
factory(instances)
.then((data) => {
Promise.allSettled(instances.map((instance, index) => {
return new Promise((resolve, reject) => {
instance
.update(data[index])
.then(resolve, reject)
})
}))
.then((results) => {
const [updatedInstances, failedReasons] = results.reduce((previous, current) => {
if (current.status === 'fulfilled') {
return [previous[0].concat(current.value), previous[1]]
}
return [previous[0], previous[1].concat(current.reason)]
}, [[], []])
if (failedReasons.length > 0) {
console.log('Unable to update certain instances:', failedReasons)
}
callback(updatedInstances)
})
})
.catch(error => console.log(`Unable to get data from ${factory.name}:`, error))
})
.catch(error => console.log(`Unable to fetch ${attributes} from DB:`, error))
}, ms)
}
module.exports = { periodicUpdate }
and then in the main entrypoint file:
// UPDATE_MARKET_INTERVAL = 30 * 1000
// stocksDataFactory -> generates new data, when called
periodicUpdate(
UPDATE_MARKET_INTERVAL, stocksDataFactory, sequelize.models.Stock,
(instances) => {
const data = instances.map((instance) => instance.toJSON())
console.log(JSON.stringify(data.map(({ code }) => code)))
io.emit('market', data)
console.log(data.length, 'Stocks updated')
},
['name', 'code']
)
God, save the queen. My eyes from this nesting hell!
no offence, but I think u should refactor it
thank you, I guess, I have to do some research on it
lol
yeah I definitely need to do it, smh
Why not use async/await? 🤔
idk, umm maybe because I need a synchronous function, so that the callback (an argument of the function) gets executed in each cycle after updating
You totally can use async/await syntax here instead of then and catch 🙂
and maybe to avoid try catch pyramids, 😂
aah yeah I guess so, I need to work on it
Not sure how you can create any try-catch pyramids here 🙃
So should I just shove it all in one try catch and can handle different errors differently?
Why not catch different errors in their respective try-catch blocks?
aah yeah I guess so, although I think it'll lead to try catch pyramids or maybe not, I need to give it a try to figure it out 😂
Just don't do operations that can throw multiple errors in single try-catch block?
try:
42 / 0
my_list[42]
except IndexError, ZeroDivisionError:
...
try:
42 / 0
except ZeroDivisionError:
...
try:
my_list[42]
except IndexError:
...
Yep, tysm !! 
I have stored pdfs in my database, does anyone know how I can display just the first page of it as a picture in html
I have a pdf model which has a file field
how do i update my github respitory by using cmd?
just cd into the repository and you can pull, commit, push, as you need
by that I mean cd into your local where you've made the changes
If you decide to move a directory where you have been uploading files originally (FileField), is there a way to update just the path of all your images without reuploading then one by one?
Hello im not sure if i should post that here but i decided so since its web-dev maybe you are familiar with requests. So im trying to pass an PHPSESSID cookie in a url with python requests but it doesn't seem to work and i dont know why, i have made this script ```py
cookies = {
'PHPSESSID' : 'myPHPSESSID'
}
def get_data(logger_key):
r = requests.get(url, cookies=cookies)
for cookie in r.cookies:
print(cookie.name, cookie.value)
soup = BeautifulSoup(r.text, 'html.parser')
return soup```
to output the cookies in use. When i dont use cookies in request.get() the output is something like that, "auth_code NO_AUTH
eid blablabla
PHPSESSID myPHPSESSID
" but when i do use cookies in my request (hoping i pass the PHPSESSID) i get the same result without the PHPSESSID
my form is not being read as a post request even when it is recorded as such
<form method='POST' action="" enctype='multipart/form-data'>
{% csrf_token %}
<div class="form-group m-3">
<label>Upload pdf</label>
<input name="pdf" type="file" class="form-control-file">
</div>
<div class="form-group m-3">
<label>Description</label>
<input name="description" type="text" placeholder="Enter a description" class="form-control">
</div>
<div class="form-group m-3">
<label>Select Folder</label>
<select name="folder" class="form-control">
<option value='none'>Select a folder...</option>
{%for folder in folders %}
<option value='{{folder.id}}'>{{folder.name}}</option>
{% endfor %}
</select>>
</div>
<div class="form-group m-3">
<label>Create a new Folder</label>
<input name="folder_new" type="text" placeholder="Create a new Folder" class="form-control">
</div>
<button type='submit' class="btn btn-primary m-3">Submit</button>
</form>
it's still being read is as a get request even though the form says that it is post
is there any way to get the UID that is registered after google login
What IDE do you all like using?
hello, i created this but the code was really messy
was there any better way than having to write out each letter of "down" individually?
using css you would be able to lose the <strong> tags
hello can someone assist here?
Hello guys im developing a flask api and then i encountered a problem with swagger that it raise an error
validation error: {'operation': 10, 'operationTarget': [{'_id': 'e7e66327-3ab7-4213-db2d-57fzc1314dg9', 'attribute': {'birthdate': '1990-06-21', 'gender': 'male', 'phone_number': '1234-5678'}, 'user_name': 'john'}]} is not valid under any of the given schemas
So, what's the most efficient way in you guys' opinion to traverse through a django codebase?
come to discord
const [solutestate, setSoluteState] = useState();
const [valueInFirst, setValueInFirst] = useState(false);
<input
className="mr-2 leading-tight"
type="checkbox"
onChange={(event)=>{setValueInFirst(event.target.checked)}}
/>
<form
noValidate
onSubmit={handleSubmit(onSubmit)}
className="space-x-4"
>
<input
className="shadow"
{...register("solute")}
placeholder="SOLUTE"
onChange={(e) => valueInFirst && setSoluteState(e.target.value)}
value={valueInFirst && solutestate}
/>
<input
className="shadow"
{...register("solvent")}
placeholder="SOLVENT"
onChange={(e) => !valueInFirst &&setSoluteState(e.target.value)}
value={!valueInFirst && solutestate}
/>
```I am getting false for another input field and when ever I uncheck, the state value is swapping and the other is false. I have attached the image for your reference in the question. How should i rectify
So I want to append input(thoughts) in json file, but it appends null to it.
thoughts = flask.request.form.get("thoughts")
filename = 'posts.json'
entry = thoughts
# 1. Read file contents
with open(filename, "r") as file:
data = json.load(file)
data.append(entry)
# 3. Write json file
with open(filename, "w") as file:
json.dump(data, file)
how do I route back to 8000/ with no extra tags in HTML
Hello everyone. I'm not new to python but I'm complete new to Django. We have a SaaS product that collects data from web with python and shows it to the user with insights, dashboards etc.
Currently we're using Angular, Flask and Mongo for this. Is Django a good alternative for Angular + Flask part? Can it be done with it? Do you think it could have benefits?
it would involve javascript then.
the way to write depends on u using which js: Javascript Vanilla, JQuery or any specific frontend framework (React / Vue.js and e.t.c.)
the amount of javascript makes no sense to use for this purpose tbh, it is simpler just to use HTML <a href="/"></a>
does anyone know how to make an image animation reset smoothly? my animation starts then ends abruptly and just resets
Anyone able to take a look at this ? Has me stumped all morning : https://stackoverflow.com/questions/69976720/heroku-flask-mail-timout-issue
yeah I just wanted html, this solved it thanks
Like a GIF?
Or CSS
Nope just a hover over image animation, i have it spin like 180 degrees, then after my mouse is not on it, it just resets abruptly
i think its css
Not entirely sure, but my instinct would be to look into mouseover vs. hoverover
maybe nullify the mouseleave event
do you know about flask?
hehe, u a welcome. your question sounded like u wish to acomplish it without HTML 😉
How best can I create a search field in Django that supports searching a field in model and also filtering by a date range? I have implemented the search functionality via DRF but ideally I'd like to create a little UI that does both - how best do I accomplish this?
<!DOCTYPE html>
<head>
<style>
.box {
transition: transform 2s;
width: 200px;
height: 200px;
background-color: blue;
}
.box:hover {
transform: rotate(180deg);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
this one looks smoothly. when removing mouse, it returns back to normal smoothly
the rotation is not in the loop though. if you wished a loop
i pretty new to css so why do we need two? like .box and .box:hover? cant we just cram it into one like
width: 200px;
height: 200px;
background-color: blue;
transform: rotate(180deg);
}```
?
@inland oak
i think i had it like that before i changed it to one and so it lost the smoothly returning animation
.box for the... llooking like in any state.
.box:hover is a chained selector, that selects .box first, then specificies, that applies styles only when its in state of mouse hovering abouve it.
ah i see, what does transition do?
basically box has hidden child :hover
I did not reach this CSS chapter yet too ;b
I can say that transition here sets type of animation: transform, with duration 2 seconds
necessary parent thing for our rotate thing in child
ah i see now, hey atleast you're fater than me at learning lol
are books generally better than videos for you?
yeah. I am really fast and vivid reader
and I hate videos for learning in general. too unefficient for me. too much water. too difficult navigation, too much waste of time.
books can be read fast, going through material you know faster, through difficult material as slow as you need
all the material is condensed for usefulness, and if not, you can change the speed easily ;b
plus with reading thousands of books, my reading speed is just fast
i think the difference between me and you is that i dont really read books when i was younger (and now), so reading docs just makes me super bored, which kinda sucks cause i know docs/books are way better
i think its a mix of both...they play different roles.
the only exception when i make to video learning, when it requires learning graphical interface, or disassembling some real life thing. in this case, video is always more useful IMO.
never really needed to learn graphical interface though. But I heard Figma designers are having option to learn it only from videos.
I'm trying to make an assignment organizer web app which allows a user to add classes and see who all is in each class
how would I structure my models for this
class Classes(models.Model):
name = models.CharField(max_length=255)
numberOfStudents = ArrayField(Profile)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Profile(models.Model):
user=models.ForeignKey(User,null=True)
numClasses=ArrayField(Classes)
this is how I structured my models so far but I think it's incorrect
lets think about their relationship
one class can have many students
and one student can have many classes
can one students have a lot of classes? well, he can too.
basically, many to many relationship then.
yes, so is it proper to have array of classes, and array of students for profile and classes respectively
class Class(models.Model):
name = models.CharField(max_length=255)
class Student(models.Model):
name = models.CharField(max_length=255)
class ClassesAndStudents(models.Model):
student = models.ForeignKey(Student,null=True)
Class = models.ForeignKey(Class,null=True)
probably this one then.
but then how would we display all the classes for a given student
SELECT class.name FROM ClassesAndStudents
WHERE student == your desired student.
not remembering how exactly it looks like in ORM, pseudocode will work yeah?
I see, so we need to pass in classesandstudents context which can be filtered by student being the user who made the request
I remember that it is possible to query it from student. I remember seeing the way how to do it in Djando Rest Framework https://www.django-rest-framework.org/api-guide/relations/
Django, API, REST, Serializer relations
ok
wait but when would a classes and students object be created, when a user adds a class?
also one more thing, when we are trying to display all the students in a class, how would we do that using the classesandstudents
because there's only one student and one class in that model
in almost same way:
SELECT student.name FROM ClassesAndStudents
WHERE class == your desired class
warning: i write in pseudo raw SQL language, because I don't remember ORM very well
uh, could be probably finding how it is in ORM
don't worry about it, you've helped me so much
it make sense
so when we are trying to display all the classes for a user, we filter by user
when we are trying to find all users for a class, we filter by class
yup 😉
that makes way more sense
thank you
what happens if a student wants to leave a class? how would we remove it from the database
results = ClassesAndStudents.objects.all().filter(student__name="Alex")
or ClassesAndStudents.objects.filter(student__name="Alex"), perhaps all() is not necessary.
will return the classes. with some not know how modification, it would return class names immediately.
with python we could request class_names as [result.class.name for result in results]
I mean then we can just take the classes object from that
well. good question.
there is some additional syntax to request class names directly from one query, i just don't know how
if to be simple, you just delete record from ClassesAndStudents
if to be more advanced, you have... somewhere record about it.
you could just make state of the link as left
class ClassesAndStudents(models.Model):
student = models.ForeignKey(Student,null=True)
Class = models.ForeignKey(Class,null=True)
state= "student_left at date"
or you could be having separate table for leaving records, which sounds a bit better.
class StudentLeftClassAtDate(models.Model):
student = models.ForeignKey(Student,null=True)
Class = models.ForeignKey(Class,null=True)
date = models for date thing
don't delete Class objects ;b
to one class a lot of students were connected
oh yeah I know
if you have Foreign Key relation ship with DELETE on cascade
you will delete all links
for all students) which attend the same class
yeah
oh wait
don't we just have to delete the classesandstudents object
not the actual class
can we delete on cascade for the student and the class in the classesandstudents object
class ClassesAndStudents(models.Model):
student = models.ForeignKey(User,null=True, on_delete=models.CASCADE)
Class = models.ForeignKey(Class,null=True, on_delete=models.CASCADE)
like this
uh. it sounds like a bad thing to do 😉
I would advice against doing it
why would u wish deleting Class or Student?
so just use no action
I mean...
when you setup it like
class ClassesAndStudents(models.Model):
student = models.ForeignKey(User,null=True, on_delete=models.CASCADE)
Class = models.ForeignKey(Class,null=True, on_delete=models.CASCADE)
if you delete ClassesAndStudents, you delete just one ClassesAndStudents obj
yeah
if you delete related student or class, you delete related ClassesAndStudents objects too
oh so then we need to just do no action
delete on cascade is perfect default relationship
yup. you don't neeed to do anything to clear any mess) the mess would be gone automatically
BUT!
usually people never delete objects from classes or students, objects from table full of... dunno how to say that, first layer unique objects?
because they would have lost all the related those records
they just turn those Students or Classes with additional attribute as "deleted" state or "deprecated"
don't delete them 😉 keep them, in case u need to make analytics from the records of the left students too
class Class(models.Model):
name = models.CharField(max_length=255)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class ClassesAndStudents(models.Model):
student = models.ForeignKey(User,null=True, on_delete=models.DO_NOTHING)
Class = models.ForeignKey(Class,null=True, on_delete=models.DO_NOTHING)