#web-development
2 messages · Page 234 of 1
why ?
I
amhave just finished my Computer Science (Year 2 Sem 1) and waiting for my result.
Thanks! I'll change it later!
In case my clients type "website.com/profile/12" instead of "website.com/Profile/12" I don't want them to get redirected to a 404 page, I want them to see the correct page regardless of the case. Do you know a solution to this problem? This should be a pretty common problem, I'd assume?
Where do you guys host your projects?
We have landed on Digital Ocean for a couple of SaaS that are entering into expanded testing. Over the past 2 months, Digital Ocean are really looking solid.
And the focus is scalable production. For personal projects Heroku for super free, Linode for deeper work. Digital Ocean does start cheap at $12/month for the app platform. Django + Docker FTW!
Hey guys, any idea why this code:
import pandas as pd, ast
from flask import Flask
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
class Players(Resource):
def get(self):
data = pd.read_csv('data.csv')
data = data.to_dict()
return {'data': data}, 200
api.add_resource(Players, '/players')
if __name__ == '__main__':
app.run()
At URL http://127.0.0.1:5000/players is returning {"message": "The browser (or proxy) sent a request that this server could not understand."}?
<button type="submit" class="btn mt-5 rounded-pill btn-lg btn-custom btn-block text-uppercase" id="sign-in">Sign-in</button>
<a href="sign-up.html"><p class="mt-3 font-weight-normal">Don't have an account?<strong>Sign-in</strong></p></a>
</form>
</div>
<script type="text/javascript">
document.getElementById("sign-in") = function () {
window.location.href = "kart.html"
};
</script>
why doesn't the sign in button redirect?
please help
please
How do i update an object value without using form? I just want it to be a one liner in the code.
which sign in? the top or the bottom?
top one
you need to add the redirect url in the view file.
if form.is_valid():
form.save()
return redirect("url")```
where do i put this
in script?
and this is python
lol
are you using django?
oh, well though luck. lmao
can't you give code in js
i know nothing about js. im sorry
why using js on forms to submit? i think you can use the form element
let me try myself first, if it doesn't work sorry.
oka
<html>
<body>
<form action="/kart.html">
<button type="submit" class="btn mt-5 rounded-pill btn-lg btn-custom btn-block text-uppercase" id="sign-in">Sign-in</button>
<a href="sign-up.html"><p class="mt-3 font-weight-normal">Don't have an account?<strong>Sign-in</strong></p></a>
</form>
</body>
</html>``` maybe this should work?
okk
the inputted password or username maybe will be placed as a query on the redirected page after pressing sign in
that worked tysm
np
btw how do i check if the form's valid
wym
like user hasn't kept it empty and stuff
whats the full form thingy?
<form action="/kart.html">
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Username" required>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com" required>
<input type="password" class="form-control" id="exampleFormControlInput1" placeholder="your password" required>
<button type="submit" class="btn mt-5 rounded-pill btn-lg btn-custom btn-block text-uppercase" id="sign-in">Sign-in</button>
<a href="sign-up.html"><p class="mt-3 font-weight-normal">Don't have an account?<strong>Sign-in</strong></p></a>
</form>``` add a required after maybe placeholder or the thing
ok
class for block radio buttons
||print('hi')||
there's no such class i guess
but you can add the css to it
Hello,
How do you prevent SQL injections in a html form, using Flask?
thanks
any way I can change ``http://0.0.0.0:8000/` to point to frontend for the password reset confirm email?
app_1 | app_1 | You're receiving this e-mail because you or someone else has requested a password for your user account. app_1 | It can be safely ignored if you did not request a password reset. Click the link below to reset your password. app_1 | app_1 | http://0.0.0.0:8000/api/user/password-reset-confirm/3/b85upt-4566c2d0e6832b36510d3cc04e40d00a/
I didn't fully understand?
hey guys!
can anyone tell me how to make a toggle button with bootstrap 3.4.1
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitches">
<label class="custom-control-label" for="customSwitches">Toggle this switch element</label>
</div>
i have this code
doesn't work
just creates a checkbox
You want to change http://0.0.0.0:8000/ to something else like this http://1.3.9.7:8000/?
Sorry, i'm not interested in bootstrap
bruh
🙂
Try google it
no fucking answer that helps me
stackoverflow is toxic
its a garbage website no one should use it
Bro the whole world use it, even Steve Jobs use it 🙂
First, this is a volunteer community. Patience is your friend here. Second, Stack Overflow certainly isn't known for being forgiving. However, it has been a most useful tool for me on my journey of developing in Django. A lot of good people have shared the benefit of their experience to help those less experienced in learning how to solve development problems.
As for a toggle button you could start with the raw html/css code: https://www.w3schools.com/howto/howto_css_switch.asp
From there you can work out how to add the Bootstrap flavour to it. Remember that Bootstrap is a css framework. It's built on css but designed to make it easier to use. In my experience, when I've encountered things that Bootstrap doesn't do I return to the css basics and work up a solution from there.
hi,
i am first time working on app
i wanted to ask if flask is only for web development??
Yes, APIs mostly
dj-rest-auth sends an email with that ip I need to change that so it points to my front-end application
Question: What's the preferred way to automatically create a profile for a user after they sign up for your website using the built-in user?
Are signals the only way to achieve this or can I somehow use the save() method?
Follow-up question:
I have different Profile and User(built-in version) models. Is it possible to create a form that creates a Profile as well as the User?
In the previous question I asked if we could create the User first, and then automatically create a Profile. Now I'm wondering if I can create a Profile and automatically create Users off of it.
I want to do this because the Profile model has a country, and I'd like each new user to be assigned a country instantly. When I create a User and connect it to Profile using signals, there is nothing in the usercreationform that would alter the "country" field in the Profile, so the Profile that is created has no country on it. And I don't want that, I want users to have a country as soon as they sign up.
What is the best way to create a simple API with Python and publish it?
I already have the "base" for it
The base being this code: https://github.com/gtkacz/nba-headshot-api/blob/main/source_code/crawler.py, that will crawl the NBA.com website for every player in the league and store their ID, and therefore can generate an URL for the official headshot for every player using their ID
FastAPI
How do I actually create it tho?
Look up a tutorial, there are plenty. Come back here if you have specific questions
@golden bone what about this?
Not sure, but you're in the right track. Must be something silly like this: https://stackoverflow.com/questions/48780324/flask-bad-request-the-browser-or-proxy-sent-a-request-that-this-server-could if that doesn't solve try a help channel
Hello, is it possible to run this in my python script?
socket.on('scoreUpdate', (data)=>{
console.log(data)
})
it is javascript.
how to say that... technically no, but actually yes
You python could be exposing socket to connect
to which you could attach your javascript code
and web sockets are meant to be used in this way with python, because we have no options to use javascript at client side
when i see javascript, this video will forever get on my mind now https://youtu.be/Uo3cL4nrGOk
Javascript programming language
Interview with a Javascript developer in 2022 with Jack Borrough - aired on © 2022 The Javascript.
https://imgur.com/a/PnaZq1F
Find more Javascript opinions under:
https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f
Programmer humor
Javascript humor
Programming jokes
Programming memes
Ja...
flask
a problem with a file upload...
folder = "static\images\dynamic\images"
extensions = {"jpg", "png", "svg", "txt"}
def fileallowed(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in extensions
@app.route("/admin", methods=["GET", "POST"])
@login_required
def admin():
return render_template("admin.html")
@app.route("/admin", methods=["GET", "POST"])
@login_required
def upload_file_logo1():
if request.method == 'POST':
if 'NewTeamLogo1' not in request.files:
return redirect(request.url)
file = request.files['NewTeamLogo1']
if file.filename == '':
return redirect(request.url)
if file and fileallowed(file.filename):
filename = "frz1-logo.png"
file.save(os.path.join("folder", filename))
return redirect(url_for('admin', name=filename))
return render_template("admin.html")
<!-- page where you uplaod the file -->
<form method=post enctype="multipart/form-data">
<li class="AdminLi">
<p class="AdminLiP" style="margin-right: .85em;">Change Team Logo1</p>
<input class="AdminLiInput" type="file" name=NewTeamLogo1 id="NewTeamLogo1">
<input type=submit value=Upload class="AdminLiButton">
</li>
</form>
<!-- page where the image is shown -->
<div class="FRZ1Logo">
<img class="TeamLogo" src="{{ url_for('static', filename='/images/dynamic/images/frz1-logo.png') }}" alt="">
</div>
It stays with the old image, no errors
Hello,
Im using Django for Backend and I have a QuerySet which i want to mutate with other records. This works fine but when I use .filter() again on the queryset mutated the values are not mutated anymore
# get the records where the gültig von is smaller equal than the given date
records_all = self.__class__.objects.filter(gueltig_von__lte=date).order_by("object_bezugs_id", "bezugs_id",
"erstellt_am",
) | self.__class__.objects.filter(
gueltig_von__isnull=True).order_by("object_bezugs_id", "bezugs_id", "erstellt_am")
records_create = records_all.filter(event="create")
for create_record in records_create:
for record in records_all:
if record.object_bezugs_id == create_record.object_bezugs_id and record.event != "create":
for column in self._meta.fields:
if column.name not in ["id", "bezugs_id", "object_id", "object_bezugs_id", "erstellt_am",
"event"]:
if getattr(record, column.name) is not None and getattr(record, column.name) != "":
setattr(create_record, column.name,
getattr(record, column.name))
print(f"create records: {records_create}")
records_create = records_create.filter(aktiv=aktiv)
print(f"filtered records: {records_create}")
return records_create
I use event sourcing so i want to add up corrections and updates to the create record so its the latest version. then i want to filter but after filtering the updates / latest version isnt their anymore
depends on the project, just watch a comparison on youtube
Oh k
Another question is python good with Web development or learning Another language like js is better?
if you feel comfortable with python, just use it ^^
I mean does it have the abilities to develop a good website?
Sorry for my noob questions
yeah, you probably can do all the important backend things like in js. for a good professional website you probably will need still need js for the frontend tho
no worries, we all have been at this point
Concerning Selenium in python:
How do I wait for an element to be clickable (EC.element_to_be_clickable)? I'm using that one, but it bombs out "because another element <.....> obscures it." How do I handle this situation? Thanks
el_submit = driver.find_element(By.CSS_SELECTOR, '#submitButton').click() # Submit button click: success
We must wait here, as the results window goes modal while waiting for data and some element "obscures" the "next_page" button I wish to click.
WebDriverWait(driver, 45).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#nextPage')) # dies here rather than waiting
driver.find_element((By.CSS_SELECTOR, '#nextPage')).click()
Also, the "next_page" button does exist even before the submit click, so I must wait until it "activates"
PermissionError: [Errno 13] Permission denied: 'quizdb.json' anyone know how to fix this error?
im using windows 11
Without more context, could be anything. If you're trying to delete a file that's in use by another program, that's one reason you could get that error
never mind, i had to run the terminal with administration permissions
hi i had a doubt in the use of with statements inside code blocks of an html file
why do we always issue end after using a statement
like for if with??
How often/how many minutes/hours before an access token expires is it appropriate to refresh it using the refresh token? Is there a standard to it? I'm working with an access token that is valid for 12 hrs... JWT
and that, that didn't work
can i host multiple web applications with one linode?
Or, you haven't worked it out yet. Bootstrap is based on css. It would appear that you have an opportunity to work out how to use css to obtain the result you're looking for.
I wasn't giving you a solution, I was suggesting a direction. As such, what I wrote was not an answer on a silver platter for you. It was a clue, based on experience that has worked for me, that was intended to help you.
Software engineering is about solving problems...taking big problems, refining the big problem into lots of little problems, bite sized pieces, that can be solved.
So, no, the suggested direction for research was never going to work without you going down a suggested path and solving the problem yourself. What it was intended to do was to support you in your learning experience. If I take the time to research your problem to develop a solution I've robbed you developing for yourself one of the most important skills in software engineering...that of solving problems.
Good luck. Trust me when I say I've been where you are...in that place where you discover just how hard software engineering is. It's not for everyone. Persevering with a problem over hours, or days, and overcoming any frustration that comes with banging your head on a logic nut is really what separates those who want to be a developer from those who become a developer.
Without load balancing, with the most simple of implementations, I believe that each Linode can be considered a container that through gunicorn/apache/etc can serve up one web app per Linode. At least, that's how I was using Linode. Disclaimer: I am no expert, and my breadth of deployments have been fairly narrow. I've not gotten into Kubernetes (yet) or load balancing.
banging your head
it gets better. If to write clean architectured code, and learning how to do it
the travel to this code architecture is a bit of a long journey though
testing makes life better with minimal learning curve much earlier. Testing synergies and becomes more efficient with good architecture and factorization skills though.
efficient way to develop / and efficiently developed code speed up continued development speed by yet another magnitude 🤔
Code Complete by McConnel is a nice book to get started with most of generic basic stuff
can anyone fork this and add mobile nav bar?, when user clicks on hamburger icon it will show home, signup links with some cool animation? https://codepen.io/abhisheksurela79/pen/jOzqbbd
I would be surprised if anyone takes you up on the offer of forking the repo and solving this for you.
The reaction you're more likely to experience in this Discord will run along the lines of pointing you in a helpful direction. For example, a css framework (such as Bootstrap and Tailwinds) are built to be mobile first, and come with pre-built css classes to accomplish your stated objective.
And so, I could solve this problem for you. But then I'd be robbing you of your learning opportunity in this. I am called to suggest that I've accomplished your stated objective with Bootstrap v4 and v5. As for cool animation, I've found that cool is very subjective.
In short, Bootstrap will provide ability to allow for responsive websites, where when the viewport is changed (browser resolution) a hamburger will automatically appear. You can see how I've implemented this in the two projects linked in my profile.
Right now i'm learning django, but sucked on this front-end part.. It seems like I am going nowhere because all I want to focus on back-end but I want my website will look beautiful too, so that I can add this in my project list.
If you're not looking to do frontend, then nobody cares what your frontend looks like. Learn frontend or live without it.
Hello!, I've done a website and i'd like to hear some comments about it, here's the link, i'm usinkg flask
Hey there, I'm trying to build a Fastapi + Nuxt/Vue js app and getting a 422 error unprocessable entity error only in my post request whereas the get, put & delete work well. On /docs the post request is working well im not sure why my form isnt working for post, this is my config for method in vue and route on fastapi. Anychance someone has a clue why this is occuring i would really appreciate the advice
What's the detail of the 422?
I think you made the item_id in post as a form parameter instead of a path parameter
just says failed to load resource at createError from console log
use /{item_id} as the path
ok and then change that on vue as well?
no, you're using that url in vue
wait...
Why are you passing the item_id to post?
post will create the item id, so it shouldn't have an id yet
i thought it would be necessary if i want to be able to let the user create a custom id
so you reckon i can just remove item_id from the post as a whole?
yes
ok thank you very much for the help im giving it a go now
hah it works, love you thank you very much
What does a micro framework mean?
I'm trying to create a user profile along with a user account with one form.
What am I doing wrong?
Here is the code for forms.py, views.py, models.py, and the register.html page: https://pastebin.com/Hk4QgNmS
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
When I click submit on the register page, it creates the User but doesn't create the Profile to go along with it.
The error I get says
IntegrityError at /register/
NOT NULL constraint failed: User_profile.user_id
a framework for a microservice, which does only one thing.
Hey guys, I'm building a CRUD with PHP and JS for a fantasy NBA game I run with a few friends, and I want a ticking timer for every player we're biding
I succesfully implemented it, but it only appears in the first "bid"
Here's the code:
How can I make it work with every loop?
I've written this code but it doesn't work. Any tips on how to fix it?
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=True, null=True)
bio = models.TextField(max_length=200)
friends = models.ManyToManyField("Profile", blank=True)
def save(self, *args, **kwargs):
created = not self
super(Profile, self).save(*args, **kwargs)
if created:
UserBalance.objects.create(user=self, country=self.country)
class UserBalance(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)
currency = models.OneToOneField(Currency, blank=True, on_delete=models.CASCADE)
Balance = models.DecimalField(max_digits=10, decimal_places=2)
What I'm trying to do is automatically create a UserBalance object every time a Profile is created.
django signals are the way to go here
also i think UserBalance.currency should be a foreign key
I know about signals, thank you for reminding me of those. So there's no way to do it with the save() method like I'm trying to do here?
technically this should work. are you getting an error?
Not an error, it just doesn't create the new UserBalance object
then the if created is wrong
i havent used django for a long time but i dont think that is the way to determine if the object is being inserted or updated
I want to trigger a special action in the save() method of a Django model object when I'm saving a new record (not updating an existing record.)
Is the check for (self.id != None) necessary and
should I use py if self: instead of py if created:
neither, see the link above ^
I changed the save() to
def save(self, *args, **kwargs):
created = self._state.adding
super(Profile, self).save(*args, **kwargs)
if created:
UserBalance.objects.create(user=self, country=self.country)
and now I'm getting this error:
ValueError at /register/
Cannot assign "<Profile: Testuser100>": "UserBalance.user" must be a "User" instance.
Ok, I changed the last line to
UserBalance.objects.create(user=self.user
``` and now I don't get that error but instead I get
```py
UserBalance() got an unexpected keyword argument 'country'
which is correct since UserBalance model doesn't have a country field
It has a currency field instead, which is connected to a country field. I shared the code of UserBalance above. Any ideas how to connect it to the country via the currency?
you can always make a query there to fetch the details
but other than that i have no idea
i dont really remember how relations in django works
Hey Can someone tell me how can I create send_emai functionality using javascript smtp library as google has permanently turned off access to less secure apps?
you can use less secure apps
search on youtube
I have watched so many videos and in all of them google have provided a button using which one can turn it on and off but in my case I am not getting any such option. Look at this screenshot -
I guess they have permanently turned it off and was wondering if there's an alternative way to send emails?
You have to enable 2FA in order to use less secure app access
Oh k
You mean 2 step verification? or what?
yes
it will provide you a different password of which you can use that password in your back-end
I just started backend developer, i learn database design but i only use ORM not native SQL. Do you think it is the suitable choice ?
You can do almost everything using a good ORM, it's the best choice for most applications
So I recently started working on a small team with 2 senior developers. The app is built in Django. Up until now in my career, I've been putting all JS into external files and importing them into my Django template. My new coworkers like to out jQuery and vanilla JS right into the template, stating that that's the norm for Django. Is this correct? It feels so wrong but I'm not sure how to argue against it, or is this indeed the common place practice in Django?
Anyone familiar with html and bootstrap rows/grid system? I made a really simple example using 3 sentences inside of a <p> tag: https://md37i6.csb.app/ My goal is to put each sentence on a new row (newline).
I'd rather not use html tags like <br> as I know there is a way to do this using the bootstrap grid system, but I'm not knowledgable enough in it.
draw a simple pictur ewhat you wish to get, and provide element syou wish to place, i will be able to help
draw a small picture in paint (in whatever ugly way), what you wish to get
Anyone know how to center contents inside of a div tag?
How can I achieve this using bootstrap? obviously using html's <br> is bad practice as it contains text, buttons, etc
you'd be surprise how many br tags I've used lol
I think <br> is fine if it was just text, each line will contain more than text it has buttons and bunch of other stuff this is just example
not a norm but a flavor. Few years ago I would've said that separation of concern was related to languages but React kinda changed that. If your team is organized by following this approach I'd say that it is not a problem. The only issue I see is that you need to deploy django every time you want to change JS code but if that's not a problem then it's fine
Firstly. There is no need to apply bootstrap, as it is a job of a regular CSS
You are thinking correctly of course, although even in case of a text it is not really acceptable
as for text we split text with <p> </p>
I am still not seeing what you wish to receive as an end result
i see code, but I don't see what you wish to get as a final state
external files you mean outside of the Django project and on your harddrive? From when I use to work with Django I just created a folder for my JS and CSS files within the project. Not sure what is standard
Each text+button should be on a different line inside of the <p></p> tag
It's easily achieved using bootstrap but im just reading docs for 1+ hour at this point
Urgh. Can't you just use a paint
to show what you wish as end result
Draw a SIMPLE picture what you wish to get
with lines and boxes xD
how to change the binding to disable the server? django
Look, here is final result lol each text+button is on its own line
u wish the text just to start each time from new line, and button being at the end of a text?
Yeah I mean I do exactly what you do. JS into separate folder, CSS into another. Seeing 200 lines of jQuery in a homepage.html seems goofy too me, but hey to each his own I guess?
the first thought is actually kind of wrong. Because you are supposed to mark your text with divs or alternative tags. Html is main purpose... to mark the elements for placement.
It is still possible to have your layout without divs though 🤔
a moment
It's not uncommon, but if that's their convention then you should follow it. Every place you work they will want you to follow a standard. Even if it sucks or is bad thats just the way it goes sometimes
So... is it what you want to get?
how buttons are supposed to be aligned to text?
and draw the desired result
actually wait, no
as it is meant literally only for this xD
Yeah, but it has to be done with bootstrap lol I have everything wrapped inside <p class="form-control-plaintext col-sm-9 p-0" id="demo">1..2..3</p>
Why?
Why with bootstrap?
it should be done with regular CSS! SCSS!
LOL
Why to limit yourself into bootstrap limitations?
It's an assignment, it cannot be that hard with bootstrap it seems like very simple task
well, it explains it better
do you have in your assigment crealy written
what you need to get as end result?
I just need text and buttons on their own line, look here button1 and button2 are on the same line:
this is how you are supposed to do within your current version
you are supposed to use divs
this is the correct way to mark stuff for placement
just use multiple rows, instead of columns from example
Yeah that's what i've been reading cannot figure it out, because divs will just break out of the <p></p> lol
your saying to just use divs anyways
you are not supposed to use <p> as external wrapping
why you have it
replace it with another div
Ok
nested bootstrap div container code works perfectly fine
it would be still better be done in regular CSS ;b
bootstrap is an easy way with limitations
regular HTML+SCSS is usually a way to implement any desires 🤔
quite comprehensive and easy to write syntax
a bit messy without frontend frameworks though
its wrapped inside <div class="form-group row m-0"> </div>
as in class"row"
you wish to have them placed one after each other
below the previous ones
Row is a row
horizonal thing
Column is a vertical thing
correct
you wrote Col, = columns
you wish to have them from left to right
you need to use "row" in order to have from top to bottom
My bad
I would like to POST Username and Password using python code, how would I go about and do that?
I tried requests.get(url, auth=("username", "password"))
but get 401 response
And when entering correct information I never get any POST method in "network" tab in developer tools... shouldn't there be a POST method?
@inland oak Thanks, I guess all we had to do was turn the <p></p> wrapper into <div></div>, the text+buttons can be <p></p> as it naturally starts on a newline.
within the <div> wrapper
yup. <p></p> is meant for text only
to split the text into... what is the word for that>
<p>
bla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla bla
</p>
<p>
bla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla blabla bla bla bla
</p>
only for this and for nothing more
regular object placing should be done with divs, which should be preferably specified more clearly by using key words article /menu and dozens of other words exist there as alternative for div (their main purpose to make your markdown just more readable + allowing to external tools(including search engines) to parse your web site easier. Kind of SEO depends on which tags you use 🤔 )
in lazy way we just use divs though
not clear enough description what u wish to get. Provide an example step by step
Hey guys I'm trying to create a file uploader thing where the page is literally just a drag and drop. then when things are dragged dropped each file gets assigned a table
I'm not sure where to start
i saw the form plugin thing but other than that not sure
This is in wordpress btw!
i can imagine how to do it with regular html/css/js. It should be just a matter of at least listening to javacript browser events
there are javascript events for drag and drop stuff
Ya dats one thing
then putting it all into frontend framework, and voila. It will work
Can u use js in wordpress
no idea. as far as I know wordpress is a set of premade solutions
you either have it there or not
if not, then it should involve a bloody dirty magic/ PHP and etc, and considering that it is wordpress, it should be all quite painfull xD
I saw u can code in php but thats about it
Hey,Can someone recommend the best way to learn pyhton?
surely people make plugins for wordpress
but making wordpress... i just have no idea how
Ya they do
and you would have to know javascrip for that too
because such stuff is impossible without it
The thing is most of them are demos
and do I remember correctly that Wordpress is Jquery? 🤔
imaging coding in JQuery
it will be such a pain in the ass xD
I have no clue i cant lie to you
A lot of the plugins are useful only if u pay
highly likely details of javascript reliaization are optional how to be made
so it can be vanilla, Jquery or even statically linked frontend framework
but you know what? Doing it just in frontend framework is surely easier than inventing wordpress plugin I think xD
having it easier in wordpress is easier only if there is already premade solution for that
the point of wordpress to provide with already ready solutions. Then it all works
for custom solutions, you are supposed to go into web frameworks
WordPress is php/mysql focused. I wouldn't be surprised to learn jquery is a big part of the front-end.
I've dabbled with WordPress, for three different projects. However, the more comfortable I became with web-work, and the more I started realizing the potential within web 2.0, I found Django and have never looked back.
How do I get current domain name within settings.py?
any idea how to force selenium to focus on the a pop up drag and drop window that comes up when a button is pressed to upload files?
Can you provide example markup of the pop up in question?
Is that really what you need to do? The normal solution seems to be to just send the path of the file you're trying to upload.
I will send you a screenshot of thr actual webelements
Sure
In Django, how can I overide save method and .save() other fields and avoid recursion?
when you override the save method you eventually call super().save(*args, **kwargs) to call the parent save method. There's no recursion
Thanks 🙂
Can you show me the input field for the file?
@viscid valley
class NationalPolicies(models.Model):
country = models.OneToOneField(Country, on_delete=models.CASCADE)
enemies = models.ManyToManyField(Country, symmetrical=True, related_name='enemies')
allies = models.ManyToManyField(Country, symmetrical=True, related_name='allies')
This code isn't working. How can I get a countries' allies and enemies(which are also countries) in this model?
maybe it makes more sense to put enemies and allies directly on the Country model?
otherwise I don't think you can use Symmetrical=True like this
yeah
^ I changed the symmetrical=True to False and it works now.
But what if I want countries to declare other countries as enemy/ally immediately when the other countries declare them as enemy/ally? symmetrical=False doesn't help with that
Are there any additional steps to enabling HTTPS on Flask other than providing the cert and key file to app.run()? app.run(debug=True, ssl_context=context) Any steps on client side, or is that handled by the browser?
if you don't want to put enemies/allies directly on the Country model (which I think you might want), you could also create your own custom through table
class Country(models.Model):
...
class Ally(models.Model):
country_1 = models.ForeignKey(Country, on_delete=models.CASCADE)
country_2 = models.ForeignKey(Country, on_delete=models.CASCADE)
class Enemy(models.Model):
country_1 = models.ForeignKey(Country, on_delete=models.CASCADE)
country_2 = models.ForeignKey(Country, on_delete=models.CASCADE)
you'd also want some constraints for ensuring you don't add two rows with the same countries
Ok, I've been looking up through tables because I didn't know about them so thanks for telling me about those. Their functionality seems pretty nice, I can even add extra fields to this. Will probably end up using htis.
what do you mean? how would that happen?
nvm, I figured it out. I'll put unique constraints in the meta class.
ManyToMany Fields create a through table for you
but you can do it manually of course
yeah, that's what I'm doing
Can you find the exact file input field? That drag div is part of a file form, unless it uses javascript to somehow pass to backend, in that case can you provide a list of on click events?
I was getting errors with manytomanyfields so I just decided to create new models for enemies and allies. I guess it should suffice.
seems good! A gotcha is to create constraints that ensure you can't do something like
Ally(country_1=a, country_2=b)
andAlly(country_1=b, country_2=a)
then alsoAlly(country_1=a, country_2=a)
since 1 and 2 are essentially the same
That's exactly the issues which are arising atm, I just did those tests on the admin panel. Any ideas what constraints would be helpful here?
this is my code atm:
class Ally(models.Model):
country_1 = models.ForeignKey(Country, on_delete=models.CASCADE)
country_2 = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allied_country')
declaration_date = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = [['country_1', 'country_2']]
I think you can do it with checkconstraints in django, these create constraints in the database
class Ally(models.Model):
country_1 = models.ForeignKey(Country, on_delete=models.CASCADE)
country_2 = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allied_country')
declaration_date = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['country_1', 'country_2'], name='unique allies')
]
Any ideas what's off in my code here? It disallows repeating the same object twice, but it doesn't work with the issues you mentioned here
from django.db.models.functions import Greatest, Least
class Ally(models.Model):
country_1 = models.ForeignKey(Country, on_delete=models.CASCADE)
country_2 = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allied_country')
declaration_date = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [
models.UniqueConstraint(Greatest('country_1', 'country_2'), Least('country_1', 'country_2'), name='unique_allies')
]
I think this works
The order of country_1, country_2 need to match to violate the uniqueness constraint we want
It didn't work :/
It didn't work for country_1 = a, country_2 = a
It works for country_1=b, country_2=a though
I'll try to google, but it's tough to formulate what exactly I'm looking for on google
I guess I could instead just add constraints on the front end so that people don't make countries allies that are already allies, and leave the database with just an Ally model without the other constraints
you can just add one more check constraint
something like this but check that country_1 != country_2
CheckConstraint(check=~models.Q(country_1=F('country_2'), name='countries_not_equal')
Ok, I'll try that out. Thanks a bunch for your help
Btw... How to using session id for selenium? Is can be use? Like you just do one time login but.... In second time u don't need to input you name or password.... Jus in home page :(
i think its not possible since the drivers used launch in incognito modes
We can use path to open chrome normally not in incognito modes
The chromedriver itself is an incognito sandbox. It doesn't store session related details across application restarts.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
main.py: https://paste.pythondiscord.com/evamujigux
app.py: https://paste.pythondiscord.com/uhecoziyax
index.html: https://paste.pythondiscord.com/ganiyuhulo
I want to change the image in the card dynamically whenever someone opens the page with a meme from which is fetched from main.py.
Any help would be appreciated!
You can try is
return render_template("index.html", dict(Post=Post))
haven't try it though
Or you can do is run the getpost function then have it in the render_template 2nd argument
And also when I try to fetch the API, it returns a CORS error
hello, I am trying to send autogenerated pdf certificates in outlook, I used pdfrw to edit my fillable pdf and then mailed it, in outlook's preview the filled data is not showing, but if I download the attachment I could see the field data.
outlook preview is not detecting the fillable fields in pdf. how to resolve
can someone pls help
How can I access that
In Python, is selenium-wire decent for capturing HAR file data? Better, worse, or just different to BrowserMobProxy? I'm leary of yet another set of proxies sitting before the TOR(Firefox) instance.
I'm trying to make a bot dashboard using Flask, though I'm really struggling with displaying the servers a user is in. This requires it to be adaptable and generate a nice little icon to click which should pop up the dashboard. Is this something worth using Flask for? What sort of tooling would I use? Could I use Vue here?
When you create a web app with django for example is that web app and API? I heard peo0le tell me that but i dont know why it is an api
yo
dunno if i should be asking it here
i want to create a google site,actually an small ecommerce shop selling game items and google site is free so im gonna use that
but i need like a legit payment method like they show in website,checkout with visa etc
i tried stripe but they asked for bank
while i only have visa card
anyone here can guide me on how to setup a payment gateaway which accept visa as payout.
i'm stuck on the simplest thing and it's driving me crazy
<img src="images/logo.jpg"/>```
tried every possible path, put the image on every level, changed the image format
still wont show
is images in the same folder as your html?
it's in the images folder which is with the html
but like i've said, i've tried putting it in the same folder
i've tried putting it on every level
are you viewing it as a file or via http?
no, my html is in templates and then theres a folder in templates called images
you need to put non-templates in a static folder.
i.e. ```
static/
images/
logo.jpg
templates/
index.html
app.py
this image is for the base template though, it's the logo image
then use ```html
<img src="static/images/logo.jpg" />
if you want, you can set the static_path in the Flask constructor to an empty string to remove the static/ prefix
I'm trying to pass a form in my view, but I'm receiving an error.
Is there something blatantly wrong here?
Code of views.py, forms.py, and html template: https://pastebin.com/jUVEdqS5
This is the error I get whenever I create a new post(submit form) at my homepage:
TypeError at /
'SocialPosts' object is not iterable
The post does get created, so the form is working, but it returns this error and I have to reload the homepage to get out of the error screen.
how can i download django in a simpler way?
bc every single time i watch a tutorial, its confusing
nothing is better than official tutorial
https://docs.djangoproject.com/en/4.0/topics/install/#installing-official-release
Just install python.
Ensure activated venv
Ensure installed pip
python -m pip install Django
djang-admin startproject your_project_name
Please tell me 10 most important projects on web develpment
I am really confused
how to start
its still confusing
man why is this hard
i can't give you less confusing instructions due to not knowing your operational system
and that I forgot how to use any other operational system besides linux
Pet projects are born out of enthusiasm. Currently doing discord bot for one gaming community, that provides some data and features based on data scavenged from REst APIs and web scrapping
I hope I will have the strength to make MVP
ik, im overreacting atm but i'll try to manage
https://github.com/darklab8/darklab_backend_roadmap
https://raw.githubusercontent.com/darklab8/darklab_backend_roadmap/master/swe_backend.drawio.svg
I am kind of drawing roadmap for that, with mentioning which books to read
my map is different because it has generic SWE skills mentioned which you are obligated to know too
I just want to say words of appreciation to FastAPI
reading its docs, and it is freaking amazing (i already saw Flask and Django before)
unbelieable but they counted everything to auto generate documentation on the fly. Path params, Query params, Data body params. And everything looks so Pythonic
So uniform simple in syntax for everything... my level of happiness increases with each page of documentation
A love from first sight (Speaking from the point of REST API development)
The only thing that's lacking is the openapi client generation
the documentation is good. It's the process that is lacking.
e.g. the typescript interfaces all ignore any inheritance defined in the models
I don't know if that's a openapi limitation or what
according to docs it is supposed to work
https://fastapi.tiangolo.com/advanced/dataclasses/#dataclasses-in-nested-data-structures
from fastapi import FastAPI
from pydantic.dataclasses import dataclass
from typing import List
app = FastAPI()
@dataclass
class Item:
name: str
@app.post("/")
async def root(response_model=List[Item]):
return []
trying to document list of responses. But it is not working.
FastAPI framework, high performance, easy to learn, fast to code, ready for production
File "pydantic/schema.py", line 251, in pydantic.schema.field_schema
File "pydantic/schema.py", line 219, in pydantic.schema.get_field_info_schema
File "pydantic/schema.py", line 996, in pydantic.schema.encode_default
File "pydantic/json.py", line 97, in pydantic.json.pydantic_encoder
TypeError: Object of type '_GenericAlias' is not JSON serializable
Slightly confused why
when I try to update/request any documentation page
wait a second, found a way quickly to find the source of error
Found!
I was inserting response_model keyword to a wrong place xD
it should be in decorator, not in function params
Hello! i need help with HTML and iFrames
im finding an element through a python module which uses HTML
but i cannot find the element because of what i assume is an iframe
Are you using beautiful soup?
Google says that iframes have their own urls. You could scrape that url then go to that website.
im using selenium
and in a page in instagram I cannot find any elements anywhere
like not the home button, or any text of images or anything
And I am going to miss Django Admin feature
it is always nice to have it under the hand generated
well. and i have to figure out how to configure a lot of stuff from zero now 🤔 including having autowiped db during tests
Hey guys, so, I'm trying to get my first job as a Django dev, I've been studying Django for quite sometime now, I'm more of a backend guy, and I was able to create my first website, that is a blog (of course haha), so I was wandering, what is the best thing that I can do now to get a job, and I don't think that my blog project would be enough, I didn't deploy this blog yet, but It has a [comment section for each post, tags, a navigation with links to all posts, home, and read later saved posts], I think it's probably what every starter website would have, but I really wanted advices, in what project should I do that would make getting a job a lot easier, or if this website would be good enough to start applying(I'm gonna leave some photos below) What would be the best thing possible for me to do right now? I really want to get a job within 1 month, I have exactly 1 month of free time, Thanks alot! Also the content is in Portuguese because I live in Portugal 🙂
https://github.com/chechasa/django_blog
hahah
can you make a rest api and a website with flask in the same python program?
Sure. Nothing prevents you from that
it is just not a good way
because for a front, by default you are having only html/css/vanilla js in flask. Which ugly as hell combination for frontend.
it will be really dirty code xD
without options to scale in any way for client side actions
or having comfortable layout coding at all if you are without scss
I have made a website that can predict an output value based on some inputs using machine learning in python. This data is sent with a post request. If I were to make a mobile app in Swift/Java/Kotlin/Flutter etc. how would i use the website service to replicate the same functionality of the website, in the app?
literally in same way
mobile app would be making post request
and getting output in json from your REST API part of flask
how do you send data in a post request, if i were to write the code in python right now?
you have options to send parameters in url address
in query params
fully fledged JSON dictionary of data in post request (your preferably main way for complex data)
plus you can even send files in request
in python it is usually a request written with requests library
import requests
requests.post(url, json) # or was is it `data` param and json/applicattion format?
exact syntax i don't remember
is there a way to make a post request whilst being signed in as a specific user?
yes. multiple ways
i would recommend JWT in a cookie way
so i have an app that has logs certain data and different parts of the app,now i have another app that i want to basically function like a log viewer.how would i achieve this?
hi guys
if anyone is free can we have little chit-chat about django secret key and csrf token
i have the following django database queries:
seeders = self.peers.filter(peer_bytes_left__exact=0).count()
leechers = self.peers.filter(peer_bytes_left__gt=0).count()
is there any way to optimise this down to a single query?
logically, the leechers line is the same as:
self.peers.count() - self.peers.filter(peer_bytes_left__exact=0).count()
since either query is simply the inversion of the other
i assume that the database (internally) knows the answer to the complementary query when it performs either one, since it knows the number of rows it has to iterate over and also the number of rows that satisfied the condition, so it's a simple subtraction to find the inverse
but i don't know if there's a way to get django to wrestle that information out of the database
well, and Alembic looks like downgrade after Django orm migrating system tbh 😁
but at the same time Alembic looks cool to use for situation when we don't have ORM at all
My solution was to not do anything that requires a database migration
and just setting up everything by own hand is a bit of a pain in the ass. I would definitely not recommend it as first framework.
I think better to get used to Django ecosystem first, and then jumping to FastAPI.
as you would already know a lot of things how can be done in a good way
at least fastapi makes no assumptions on your knowledge of type annotations, which it employs heavy usage of
Well. FastAPI has some of its own features where it could flare better than Django.
Django ORM is still sync for example xD
better to question what it is not supporting. Django ecosystem has answer for every little question.
I will do my pet projects fully in FastAPI nevertheless. Because it is too often asked in jobs.
Idk but I have written this before :
Use union()
1-is used to combine the result sets of two or more selecet statments in SQL
2-it removes any duplicate rows between the various select statments
3-should only have the same fieldsa and data type(objects,tuple,lists,etc...) when performing the union method ex.(e.objects.all().values_list("first_name").union(e2.objects.all().values_list("this should equal the first pramter it would be (first_name)")))
i don't think that's what i'm after
a union of the two queries would just be equivalent to Peers.objects.all()
which doesn't help me get a .count() for the objects that do meet my criterion
I don't think so. I think i wrote it just for instance
If you want to combine querysets union is what you looking for
that's not what i'm looking to do
Anyone here try django-unicorn? Any way to target something in another template.
Question: I'm trying to create a registrationform where users can select the country and region for their profiles.
But I want them to only be able to select their region depending on what country they selected, I don't want them to be able to select a region which is not in the country they've entered, and I want this in one form.
This is what I tried:
class UserProfileForm(forms.ModelForm):
country = forms.ModelChoiceField(queryset=Country.objects.all())
region = forms.ModelChoiceField(queryset=Region.objects.filter(country=country))
class Meta:
model = Profile
fields = ('country', 'region', 'bio')
but it doesn't work, it simply shows all the regions in my database regardless of what country the user has chosen. How can I let users make the choice dependent on the country they've selected?
Hi guys anyone know how to fix DRF
How long have you been learning Django for?
Hi can anyone help with DRF 'Request' object has no attribute 'driver'
https://learngitbranching.js.org/?locale=en_US how about with starting to learn how to use git
tryi to sink into you about the way git is supposed to be used https://deepsource.io/blog/git-best-practices/
And after that learning about the ways to unit test your code?
and oh well, i made a roadmap for backend development, which tells directions where to go
https://github.com/darklab8/darklab_backend_roadmap
https://raw.githubusercontent.com/darklab8/darklab_backend_roadmap/master/swe_backend.drawio.svg
the thing is you need to learn not just Purple (Python) and Yellow (Backend), but also a lot of Green (Generic Software Engineering) stuff
Hello,
is there a way to give each App in a Django Project different allowed hosts?
Sure. Nothing really prevents you from writing your own middleware plugged into Django
in FastAPI this process is quite simple. I don't think in Django it would be that different
ok thx
https://docs.djangoproject.com/en/4.0/topics/http/middleware/ here is an example how to do it
there is only slight question how to extract necessary data from app.config of a current app
or you would have to go through decorator way
slight research is required to find out which way is easier to implement
i think it should be middleware, because it will automatically support all Class based views
decorator would be not easily supporting it. Though class based decorators are possible too as far as I know. 🤔
im using fastapi and im sending processed data to another endpoint but it gets stuck in a endless loop
def post_to_ipfs(
auth: str,
file: bytes,
):
"""
Post a file to IPFS.
"""
headers = {"Authorization": auth}
data = {"file": file}
response = requests.post(
"http://localhost:8000/storage/upload",
headers={
"Content-Type": "video/mp4",
"Authorization": f"Bearer {auth}",
},
)
return response
@storage_service.post("/compress/video")
async def compress_task(
file: bytes | None = File(default=None),
rate: str = "lossless",
ipfs_flag: bool | None = True,
identity_token: str = Depends(get_current_user),
):
if identity_token is None:
return {"message": "Unauthorised user"}, status.HTTP_401_UNAUTHORIZED
if not file:
return {"error": "No file uploaded"}
try:
temp_dir = save_to_temp(file)
except Exception as e:
return {"error": str(e)}, status.HTTP_400_BAD_REQUEST
if temp_dir is None:
return {
"error": "Could not save file to temporary location"
}, status.HTTP_400_BAD_REQUEST
else:
try:
compressing_video = CompressVideo(rate, temp_dir)
compressed_video = compressing_video.produce_compression()
if ipfs_flag:
try:
post_to_ipfs(
identity_token,
compressed_video,
)
except Exception as e:
return {
"error": "Could not upload video to IPFS",
}, status.HTTP_400_BAD_REQUEST
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
return {"message": compressing_video}
can somone tell me how to fix this issue?
writing unit tests for each piece of your logic in order to verify each piece of logic is working and localizing the source of error
no point, fastapi has a good testing ui
Also it would be really nice to move logic out of view layer
wdym move logic out of view
This book is the answer to your question directly
as for this question.. Hmm probably to start with Code Complete by McConnel? But technically it is described in Clean Architecture by Robert Martin
Although i am quite tempted to read Head First Design Patterns as first book. Ergh. long question to answer.
The point is you are having a lot of your logic in a code where it should be only accepting input and rendering back answer
the code for your action should be in a class that process your action. Which you can test independently part by part
and then reuse at any necessary view end points
you could have saved your time by reading my code and understanding that your recommendation is respectfully irrelevant
i will not try to persuade you for anything, except starting to read from this book first I think
it would bring you the most value in a short time
alot of "logic" has been abstracted to external functions which process information. my endpoint, simply assembles information to dispatch to another endpoint
also ive not read any programming books, i dont find value in them.
Apartment Angels — Today at 2:51 PM
also ive not read any programming books, i dont find value in them.
https://youtu.be/aiPEGBOvu1Y
Daisy: What?
Roseluck: Oh, the horror! The horror!
its pretty much self-explaining.
moment from My Little Pony: Friendship is Magic. season 5, episode 9, slice of life.
literally no piece of literature contains information that isnt accessible through a quick google search.
but this is really irrelevant. I appreciate your response, but I'd like to hear other's view on the situation
Books provide structurized information about a subject. Once you found a good one, you don't need to seek next clues to learn next piece of a material from same field
Books guide you to teach you, and mention all resources what to learn next
You can't google something, if you don't know what to google.
wrong guy to give this advice to but again, i appreciate the response.
And the more stuff you learn, then more you are exposed to guess what you don't know yet
btw, as a short first step to fix introduce Timeout to your request
https://linuxpip.org/python-requests-timeout/
to fall out of the endless waiting, if it is stuck more than N seconds
(and adding a message to your logging system about it)
no it was a cors issue. i didnt include the cors header.
In my Flask website, when I am logged into an account on my www domain, it does not automatically login to the account on the non www domain. What is the reason for this, and is there a way to fix this?
DNS CNAME record add to your DNS settings
It would redirect from WWW to @
You will have redirection at once when u visit any page
can this be done without any sort of redirecting, where both www and non www have the same login?
DNS setting will ensure u a logging in users only in one version
Can u login a user between different domains? Yes. I think it is configured at the level of cookie. To which domains it would be sent
This solution is more meant for microservices architecture though
DNS solution will fix your problem better
Anyone has modern resources for multitenancy options in Django?
I am currently working on a monolith in a Docker container with PostgreSQL.
can a user override a redirect?
no 🤔 I mean yes he actually can as it is stuff technically happening at client side (though I can't imagine how to hack DNS xD), but you will not care about it due to your ability to lock your CORS headers freely only to one domain (which is still doing nothing), but you can also restrict access at your reverse proxy servers for listening only for requests from certain domains, then user will not be able to request alternative domained resources for sure
so i should just remove the www/non www from my nginx conf?
sure. Leave just one version of domain in all your settings
and have DNS settings redirecting from other versions to the chosen one
it is DNS job after all
previously i asked in this channel whether it is possible for one vps to have multiple websites hosted but i got the reply that it is not possible.
however, i have searched the web and it seems possible
i will tell you they were wrong
i already did it for 5+ web sites
ok thanks that would save money
the principle is simple for that
just having DNS settings from different domains pointing to same IP address of the VPS
Nginx should be listening to specific domains and redirecting to the right web site based on incoming domain
it can be done at regular linux VPS and nginx as reverse proxy (or apache for that matter)
when i run the code, should it be run on different ports for different websites?
I did it in a more complicated matter with k8s though, and Ingress-nginx
what?
ah, yes. I get it. yeah
ok
host them all on different ports
and let Nginx regulate from which incoming domain to which localhost+port to direct request
does nginx always listen on port 80, and then direct traffic to 127.0.0.1:xxxx ?
nginx can listen at any port you wish and write in your settings
usually people often use port 80 for http and 443 for https
and 80 http port is usually just redirected to 443, which has SSL certificates attached for encrypted connection
it can redirect traffic at any of your choice
this way is using Nginx is called reverse proxy and it is only one out of SEVERAL ways to use nginx
the other popular way is to host static files with nginx
we in python always host our static files with nginx (css, js files) usually. if we need to do that
because all alternatives are worse
well, usually people host with static files fully scaled frontend in react/vue/js/angular though
Nginx can be also used in a limited fashion as a Load Balancer
which means redirecting traffic not to one resource, but distributing traffic between serveral of them, but it is preffered to use Haproxy for that
it is popular to use Nginx as Reverse proxy, with attaching server/client caching capabilities into it also, to speed up your resource
quite multipurpose tool in conclusion
read free O'reilly book with recipes how to use it.
Could you tell more info
For now, the error says that you try to get access to field that doesn't exists in the request data
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I'm trying to get user info for my mobile
Any python dev here?
Try print request.user and show me the result
Is it secure to use flask sessions as a way to authenticate? The user signs in, and I add their email to session and use that to gather info on them from the database
I'm trying to create a 'reset password' functionality in my django application, everything seems working fine, the email-sent confirmation page shows but the email is not sent (I use gmail). I activated IMAP. Any ideas? I have also configured everything in my settings app ```EMAIL_BACKEND = 'django.core.mail.backends.email.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = 'True'
EMAIL_HOST_USER = 'myemail@gmail.com'
EMAIL_HOST_PASSWORD = 'mypass'
As of June I'm pretty sure Gmail doesn't allow that anymore. I believe you need a 3rd party tool or don't use Gmail
I'll check, thanks for the information
firstly you need to allow insecure access to your account in settings
secondly, it will have a lot of limitations anyway, you should better use serverices like Sendgrid, which are APIs meant to send emails
What's a good method to implement token-based httpOnly cookie authentication for my drf API for a javascript frontend I looked into django-rest-knox for token-based authentication but its built-in LoginView required the user to be logged in already. Why is that?. I want a good method to authenticate the user from the javascript frontend
I have made a Flask website. One of the pages involves inputting some numbers into a form and by a post request an output is generated. How can I let users perform this request using a python script/bot only if they have a specific api key?
using jwt, you can give them a "script" scope and check for that
What's the difference between is_authenticated and @steel edge_required decorator? When to use which one?
my backend is django, while frontend react native and when i try my login function i get this error = > undefined is not an object (evaluating 'json.token') my code => ```class Occupier(AbstractBaseUser,PermissionsMixin):
#occupiers can join several cliques
#all posts must go to a specific clique
email = models.EmailField(verbose_name='email',max_length=59, unique=True)
username = models.CharField(max_length=30,unique=True)
occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
dob = models.DateField(blank=True, null=True,unique=False)
password = models.CharField(unique=True, max_length=200)
first_name = models.CharField(max_length=200,null=True)
last_name = models.CharField(max_length=200,null=True)
objects = OccupierManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','occupations','password','dob']
@property
def token(self):
token = jwt.encode({'username':self.username,'email':self.email,'exp':datetime.utcnow() + timedelta(hours=24)},
settings.SECRET_KEY,
algorithm='HS256' )
return token``` , ```class LoginSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=128, min_length=6, write_only=True)
class Meta:
model = Occupier
fields = ('email','username','password','token')
read_only_fields = ['token']```
im using replit and im tryn keep my discord bot alive
i was using this code + uptime robot to do so
then i got errors saying i need to use wsgi
so ive got this, but, i dont get a web page output like i did with the first code, with which id use the url on uptimerobot to keep the bot alive
so idk how to complete the rest
Does anyone know of any free hotel or flight Api's to get prices?
hey guys, can someone explain in simple terms what this render function does? I understand it return the request, and stores the data in the dictionary, but how does it actually work in terms of making a website
return render(request, 'update.html', {'form':form, 'todo': todo})
is there a way to create a collapsible that pops out to the side besides directly under it?
!d django.shortcuts.render
render(request, template_name, context=None, content_type=None, status=None, using=None)```
Combines a given template with a given context dictionary and returns an [`HttpResponse`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpResponse "django.http.HttpResponse") object with that rendered text.
Django does not provide a shortcut function which returns a [`TemplateResponse`](https://docs.djangoproject.com/en/stable/ref/template-response/#django.template.response.TemplateResponse "django.template.response.TemplateResponse") because the constructor of [`TemplateResponse`](https://docs.djangoproject.com/en/stable/ref/template-response/#django.template.response.TemplateResponse "django.template.response.TemplateResponse") offers the same level of convenience as [`render()`](https://docs.djangoproject.com/en/stable/topics/http/shortcuts/#django.shortcuts.render "django.shortcuts.render").
Its just a shortcut to a HttpResponse function and passing it to a template
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
https://pastebin.com/tJNkDPuB
my serializer
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
For full stack projects how what advice would you give on planning your project? Should I start with frontend or backend first?
https://www.amazon.com/Systems-Analysis-Design-Alan-Dennis/dp/1119496489
With system analysis and design first
Try this request.data.driver instead of request.user.driver
Anybody else getting cors error with heroku atm ?
I have a deployed webapp that was fine until about 15 minutes ago
Are there any differences between using is_authenticated() or @steel edge_required decorator to check if users are logged in?
Anyone can help me with Django? I'm confused at this moment.. so I want to store user phone number during registration and for that I'm extending User model with OneToOneField, but later how do I will verify which phone number belongs to which user?
I did it
is_authenticated is used in the template as a tag. @login_required is used as a decorator in the view. The big difference for me is that on pages where I can have both those logged and those not, the tag allows me to conditionally build the template (which can be very useful for a navbar in base.html). The decorator is a simple but effective security measure.
Remember that there are three layers. The data model (models.py) is where you organize how data is stored. The application layer (views.py) you will use to build the templates. And the front-end layer will include forms.py. You can verify phone number for a user by checking for existing data when the template (application) queries the database. You can verify the format for the phone number, or require it to be entered, through forms.py (the front end).
If you have a solid mental grasp of your vision for the data and application layer design, and can see how you want data presentation, data entry, etc to look, then you can flesh out the design language for the front-end, and then re-use through the app. I tend to set the front-end UX down as I'm building the first app, build out the remaining apps etc., keeping the UX fairly consistent once I've set key aspects. Having those decisions made will help you quickly configure template pages as you are building out the app.
That said, if you plan on different presentation styles within the project that would be different.
That sounds like dynamic behaviour in the web page. I'd look into js frameworks such as React etc.
What other recommendations do you have?
Makes sense, thanks
Appericate your time will test out later
I asked this question, and got this response. However, even after searching the web as to what this means, I still do not understand it. Could someone please explain this concept further, and briefly outline its implementation in a flask webapp?
JWT is basically a base64 string
that is under the hood is Python Dictionary json dumped, with added at the end validatation string
the point is, when you authorize user, you can stick to them sticky cookie
which would be having inside dictionary whatever information you wish to have about this user
for example a setting which is endpoint user is allowed to request
when you receive sticky cookie back at your endpoint, you verify with your secret_key, that it is a valid one, and read permissions
I think that I will better understand this with an example.
Let's say that I build a desktop app and send a post request from it to an api, and it returns the relevant output.
Without the concept of authorisation of users, if the rule was that requests can only be sent from this desktop app and not from any other service, how would it work?
How can I tell the API to only accept requests if it has a special key that is only sent from the desktop app?
i found a good video explaining jwt in brief, u can give it a look.
JSON Web Tokens (JWT) are talked about all the time, but what exactly are they and how do they work. In this video I will explain in depth exactly what JWT is, how it works, why it is secure, and when you should use it. We will go through multiple visual demonstrations of exactly how and why JWT works. We will also compare JWT to the more common...
Hello friends .
I have a problem.
After writing the codes of my site with Django framework, I write runserver in cmd, but nothing happens and it doesn't even give an error.
Is it a problem with the Python or Django version or is it a system problem?
Because I was able to activate it with this command very unexpectedly.
I have models A and B and B have fk field to A. I have a sidebar which is visible on every page. I have a homepage, seperate homepage for every instance of A, and page that lists B that have fk to specified A.
the urls could be -
/ # home
/<A's pk>/home/ # separate home for every instance of A
/<A's pk>/B_list/ # B instance list for specified A
The sidebar is a template that is included in base.html. I need a link to B list in the sidebar for current A (current A is the A of current homepage). How do i achieve this? if any doubt feel free to ask
django 👆
ping when you reply
Hi guys, do you know any nice repos with production-level code for a data intensive REST api? Need some inspiration
Implemented in fastAPI and using as pytest as test runner would be a great bonus!
Cheers
still same
AttributeError: 'dict' object has no attribute 'driver'
Bro you try to access attribute that doesn't exists in the request data
Your request dosent has driver
Started actually doing a pet project to learn this tech stack and just made setup
For fastAPI, pytest, SQLalchemy, alembic migrations and celery beat
Postgresql database
And pytest fixture creating temporal test database empty inside for each test
https://github.com/darklab8/darklab_darkbot
Sub project scrappy inside
Probably should add scripts for database migration for doc clarity 
I ll add it just a bit later
Cool, looks good, thanks! 🙂 Where is your test code btw?
do you want see my serializer
How can I send information to the backend of a website? The details of the question are in #help-grapes so please help me if you can
Sure
when i do print it able to detect my username but that all
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
{"driver": {"avatar": "", "car_model": "", "plate_number": ""}}
I managed to capture this
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is what i do
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Try print this request.user['driver']
print(request.driver) ?
'Request' object has no attribute 'driver'
Ah...
Last thing bro
Try this request.user[0]
Your problem is so easy
You got the data
But you don't know how to extract it
'User' object is not subscriptable
driver = OrderDriverSerializer( driver = request.user[0] ).data
if i don't use this part i'm able to detect but not my infomation
What did you type to get this?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
src/scrappy/players/tests.py
And fixtures in src/scrappy/contest.py
driver = request.user.driver
this one leave the zone
Bro do me a favore and print this block of code request.data
Dears how python is compared to other web backends like PHP nodejs or even c#
Are you doing it as a hobby or career
hey guys, I am building an app, and, I am able to create an account successfully, but signing in or logging in, nothing happens, I click the button and inside my terminal nothing happens, see anything wrong with the code?:
As career doing in c# as that’s what is accepted in the place I work and as hobby long time back used to do in PHP more than 10 then for long time didn’t have time for hobby at all now exploring nodejs and python
More than 10** years ago
Anyone familiar with django messages ?
#I am sending a list of messages in django template like this..
messages.error(request, list(verify_user.values()))
#this is my html file, and I'm expecting iterate each list items and show as error message in my html page
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}
#but the problem with this, I am getting error messages like this in my html page
['username is not available', 'password should be 8 to 16 characters long']
#I even tried to do
{{ message[0] }}
but I get an error
Could not parse the remainder: '[0]' from 'message[0]'
where should i write them
Delivery Loh
request.data
solved?
I think you have to do one message at a time.
for message in verify_user.values():
messages.error(request, message)
The frontend makes a request to the login endpoint and the backend is supposed to sent a csrftoken cookie and a sessionid cookie. But for some reason no cookies are being set ```
Set-Cookie: csrftoken=QCISyaq08PkCwgADj8j7HvRe94ouETW5WkI1xSmqW6sDzbpgqWgjf0tKfxOoLl8Y; expires=Tue, 11 Jul 2023 18:26:21 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Set-Cookie: sessionid=98k1sack6fauqylu2awd4jhktpw37tum; expires=Tue, 26 Jul 2022 18:26:21 GMT; Max-Age=1209600; Path=/; SameSite=Lax```
do you mean how to reload your application with new changes?
yeah. like i code on my computer, but somehow i need to transfer the changes to my server
there are too many ways to do this and depends on a lot of variables. What's your app tech stack?
A lot of people use sftp or rsync
rsync has a feature to transfer a folder, deleting any old files
This works best for static sites, not flask
i have a flask app, pretty basic one
i basically want something similar to git.
i want to sync changes, but want to add exclusions. for things like venv or __pycache__
?
ahh did not see the previous text
those files and directories are usually excluded via gitignore file, so cloning a repo usually skips them - have you checked this? - https://flask.palletsprojects.com/en/2.1.x/tutorial/deploy/
no, thank you for showing me this resource.
while your at it you should also look at docker
so when i deploy my app, you recommend to run it in a docker container?
and not directly on my VPS?
your vps runs the docker, that runs your container
so on any machine which has a docker u can run your app on it
If you want something similar to git where you can push to deploy, I suggest heroku
it depends on several variables. I can suggest kubernetes for someone who uses only containers. And then I can suggest serverless to someone who uses kubernetes
but it mostly depends on your app needs, your skills, time, budget, etc
with heroku, it can either build a container to run or setup the environment automatically if you have a requirements.txt, setup.py, or pyproject.toml files.
then you git push heroku main -f
ohh, so its like a git addon?
I can suggest cloudflare workers too 😂
cloudflare or heroku?
heroku
pushing directly to production ooof living on the edge nice
better try using DigitalOcean 😉
it has technically same capabilities
with app deployment.
or more exactly go for Docker image deployment in app deployment xD
or just go for VPS deployment that uses docker 🤔 i think it will be greatest learning option
I tried recently (DO apps). Not 100% convinced but I'm pretty sure it will get better
If you need a database, DO charges extra for that
VPS it is then 😉
heroku gives you a free (limited) database, but you can unlock more rows for $8/mo
cheapest DO has is $16
DO db are a bit expensive, yes
it's $0.0000185 per second after 90000 seconds
btw I don´t know why private repositories are so expensive in DO and in Github
I bet the support is excellent
If you have a reason to hide the database, you're probably willing to pay for it.
oh DO is magic. I had a kubernetes issue, I couldn´t renew my certificate and a dude solve my problem in less than 24h. Pure magic
can i just use git to sync my files with my VPS?
short, yes
but docker hub is so cheap
would i create a seperate github account for my server?
i think thats reasonable
your app would just be a separate git server.
it's like pushing your code to github, gitlab, and bitbucket
you got any resource i can read?
if you use DO App Platform, you won't really get "admin" access.
So you're using a VPS.
yes.
That just means you'll have to do a few things manually.
I assume your distro is using systemd?
are you using a load-balancer?
there is only a single server
this app wont need any scaling
how do i check that?
just check if you can get to port 80
Should also be shown in the windows server admin center
yes, i can access my app via the public IP of the VPS
windows server admin center
whats that?
It's the place where you can manage everything about the server (and the whole fleet)
so its outside of the VPS?
what windows version are you running?
its windows 10 i assume
it's probably not windows 10
It's probably windows server 2016 or 2022
Does this window show up when you start up?
If you don't know how to manage a server, I suggest switching over to the app platform
or getting someone else to deploy it
Here's a tutorial btw
https://medium.com/@dpralay07/deploy-a-python-flask-application-in-iis-server-and-run-on-machine-ip-address-ddb81df8edf3
yes, i taught that program was from the hoster
thx
That program is from microsoft.
its not in my power to decide that
i have to work with that vps
In that case, google is your friend.
and maybe youtube tutorials
btw, if you want something you can git push to deploy, you'll need to use a CI/CD solution like github-actions, gitlab-runner, or jenkins
that will need to either connect to your VPS or mount the volume hosting your app, update it, then restart the service.
Something like this.
https://www.devopsroles.com/gitlab-ci-cd-deploy-the-website-to-vps/
except you're on windows
I used windows server once for flask but DB was a M$ sql server because a proprietary software only supported that engine...
It was a hassle to configure
does it run on linux too?
I configured it once to connect to some database with credentials that were given to me only to later learn that I didn't have access to the network that could connect to it.
Yes, it runs on linux
as a separate apt package. You need that package to use it in python
I can´t recall, it was probably apache on windows vs. odbc on linux decision
apache has a database?
no but having flask on windows implied (at the time) having apache on windows
I do recall windows as server 😂
I guess if you weren't using windows server, you weren't using IIS
apache web serve I meant
or IIS wasn't around yet?
yes, it was around but we used apache
why would i use this webserver from windows over nginx?
if you want to use nginx, use nginx
my plan was to use some WSGI server which i connect to nginx
does that sound foolish?
waitress?
It's easier to link them on linux because of sockets
so its recommended to use FastCGI?
cgi != wsgi
but IIS + wfastcgi do essentially the same thing as for eg nginx + waitress?
fastcgi will work actually.
https://flask.palletsprojects.com/en/2.0.x/deploying/fastcgi/
I deploy Django apps through the Digital Ocean App platform, with apps connected to github repos. The Digital Ocean App platform is fantastic. The app has a dockerfile. I push a change to the repo, and any DO apps sharing the same repo automatically rebuild the docker container. I've been using DO for a couple of months now. Super impressed.
More recently, I've shifted to using the DO Spaces (their S3 solution) to store static files. This has allowed me to shift away from even storing static files on the app. There may be different schools of thought on that, but I'm finding this experiment to be working very well so far.
hi i am having to do integrations and i need to change a form into a flask wtf form
i am an ML engineer so this is not my area of expertise
here is the input ```html
<input id="checkbox_major{{ loop.index }}" type="checkbox" class="custom-checkbox" value="" />
Hey which python framework is more widely used at companies, Django or Fastapi? I’m new to all this, so any help would be appreciated.
depends, fastapi is pretty popular for most things done in python tho ( as typically in the realm of ds )
regarding my problem:
I have a list of say 200 items for these checkboxes, list type str and that needs to be displayed and whatever checkbox is selected the str needs to be passed back to the server on submit
Yes I finally solved the issue! It came down to a database model typo….of course haha
and DO Spaces can have easily attached CDN, to speed up access by manitude
(Technically I think it is just Cloudflare under the hood though)
CDN makes sure content is delivered to user from closest server to the country in Content Delivery Network of caching servers
Yes. 100%. It was VERY easy to setup, even including the cert baked in. Very cheap, seamless setup and is serving up static content LIKE A CHAMP.
It's actually cheaper, as I'd need another container (for nginx) for x2 the cost, while a Space is crazy cheap - and I'm sharing one space for multiple apps. So the cost saving is 50% for each app on the same code base. This literally halves the app hosting cost regardless of the number of apps, AND reduces the complexity of setup for additional apps on the same repo.
DO estimates the CDN option is 70% faster, plus availability and redundancy! All you need for the CDN is your own domain, and you go for a url such as cdn.yoururl.com
DO is literally THE host of choice for us right now!
I feel like u became Digital Ocean advertisement agent xD
Now I know how I look like from a side when talking about Serbia
Totally unsponsored. But I AM a fan boi of Digital Ocean. Their app platform offering has been astonishingly solid. The time DO saves me, and the upside potential for what we are about to do! We just got our 5th testing client on board today for Whurthy. If Beta goes as hoped, we're going to be ramping up fast.
Ergh. I use digital Ocean now as main provider just because it is a single quality provider offering to pay in advance
Unstable payment systems situation at the moment
I can only imagine.
Yes, the advance payment option is very solid
I am having fun too. Keeping learning new stuff. I have a hope to make clearing learning queue within half of a year
What is a "clearing learning queue"
I mean I hope to clear a gathered learning queue
Two open source projects
And dozen of programming books to process or something
...that makes more sense 😄
Going to shift to a new stack in a company after that time too
Slightly thinking how drastic I wish to have a shift though
To fast API and Kafka
Or going bravely to golang
There is even a possible option to change a role to DevOps
Ergh. Too many yummi choices. Too little of human life time and career
Amazing stuff! May you make the most amazing choice!
For me, Django continues to astonish me. Every line of code is more experience.
I started pet projects to explore fast API already. It has its own benefits for sure.
Too much of django at work already
I've been in a 12-14 hour daily coding crush for over a month now.
When Whurthy takes off, then we'll hire the talent to take the code base and devops to next lvl. Figure 100 and then 500 clients are the key next two phase triggers
Entrepreneuring at full scale. Way to go. Woohoo.
We? Do u have already some team?
Business partner and I. Plus a couple of people stepping forward into sales.
Fun
I'm going to automate our operational workflows and build a virtual business...global virtual business with no physical business costs!
That will save a huge operational overhead.
And I'm already coding workflows with Django...what I really need to get worked out is celery or something like it. Waiting for someone to do that right. I'm also curious about DO's "Functions" platform though...thinking there may be some scheduling bots I could use for workflow
DO functions is so called serverless infrastructure. It is serverless alternative to celery, and the point of it, that no need to scale it hardware resources. It is synonym to AWS lambda
Is it possible for a django backend to set a cookie when a POST request is sent by a react frontend?
The set cookie header is there but the browser is not setting it
I assume it is because samesite is set to lax?
I can set samesite to none but thatll require an ssl connection
the cookies are being set when I send a post request using postman and when using the interface rest framework provides, it just doesnt work when using react
sounds like a time for CORS problems
these are the cors settings py CORS_ALLOWED_ORIGINS = ['https://localhost:3000', 'https://localtest.me:3000'] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ['https://localhost:3000']
check your browser networking settings
they should show your errors
debug it client side
while checking server side log in debug mode
these are the response headers
with an exclamation mark
uh there are no errors?
Maybe these headers are causing the issue? @inland oak Cross-Origin-Opener-Policy: same-origin Date: Wed, 13 Jul 2022 07:31:29 GMT Referrer-Policy: same-origin
hmm setting up a next.js proxy to my api worked
How do you check the expiry date of a Let's encrypt SSL certificate using certbot on ubuntu 22?
Can you do app development in it?
firstly they send notifications to email
secondly... it is auto updated anyway, if you set everything right
You can, but unless it's fairly simple Django may be better. Also you'll probably want a JS framework for the frontend unless the interface can be very crude
Hello, I am using fastapi and I have a post endpoint for user signup and login. I've used pydantic base class for typing the arguments. class has username and password fields only. May I know how do I test this endpoint through postman API? Like where do I add these parameters in postman API?
I think you just map out the key and value of the request in the body of Postman
I have three simple questions related to Django.
1:
Could my website security be compromised because of me not following Django's best practices and focus completely on speed? (but still doing all safety measures)
2:
When doing choice fields why should I write the short version an then the long one when creating a choice? What is the difference between them? Would it be bad if I just wrote the same word on both?
3:
I have two really big choice fields where in each one all countries are listed, does that slow my code as much as other stuff would? (like loops and ifs/elses)
.com domains aren't free
the price is something like 5$ per year
there is free option, a moment
https://desec.io/ 16 subdomains here, for free.
already told you > .com domains aren't free
desec.io gives *.dedyn.io as free I think
or something similar
hello... i'm a little confused with where django passes things around... i have a view function that's throwing a missing positional argument. it's there, i'm just not sure at which part i'm supposed to pass it to the function. isn't it the user going to the url that calls the view function associated with that url path?
this involves a form to be filled out btw
so you can get to the url, and the form will be there, but when you hit submit, that's when the missing argument is thrown. i'm not sure if it has to do with how it's modelled because this is supposed to be a foreign key to create a relationship in the database.
I am able to create the base entity, but now i want to create the associations to other tables. for context, it's supposed to be a basic auto shop app, so that i have a customer and then they can have vehicles and repair orders, etc... the tests are passing, so i think my schema is correct, i just need to know how to make the relations stick.
apologies if i'm misusing terminology.
i also used django.forms.ModelForm
It will be much easier to help if you share some code and the exact error message
Thanks. I had help come in and apparently the problem has to do with my request method. I'll try to work on that for now, but I'll make sure to add more information next time.
it gives some "type error" something like not a dict
I'm currently struggling to understand react.
I have a django site I'm toying with and wanted to add a dropdown box that's disabled and has its options change based on the previous dropdown selection(and enables it)
I'm not so much looking for help with existing code as I'm wondering if their is a recommended resource for beginners in the combo of django and react. Every tutorial I'm finding that doesn't make knowledge assumptions begins by telling me to create a new react application which I will probably toy with soon, but for now I'm just wanting to add a small amount of react to my existing app.
glad you got it fixed
You cant "add a small amount of React" just like you can't "add a small amount of Django". It's a framework.
This looks pretty good: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react
But if you just want to add some menu dynamics, React might be overkill
Fair about the small amount of react, poor word choice 😂 I'm just a hobbyist and was just interested is all, react is definitely overkill for what I'm trying to do. Thank you for the tutorial, I'll check it out right now 😃
ill post a snippet of my code
Not sure if this is enough, please let me know if you need to see more code
Set editable to true
i've tried both
could it just be a django issue? hard coded to be non editable
yea what part would u like to see like the whole class or no
Send the class ye
if you'd like a pic lemme know
If React is overkill, look into HTMX or vanilla JS
Is there any default value for editable
i do not see one
venv_scrappy/lib/python3.10/site-packages/sqlalchemy/util/deprecations.py:309: in warned
return fn(*args, **kwargs)
venv_scrappy/lib/python3.10/site-packages/sqlalchemy/sql/schema.py:593: in __new__
raise exc.InvalidRequestError(
E sqlalchemy.exc.InvalidRequestError: Table 'players' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
====================================================== short test summary info ======================================================
ERROR scrappy/players/tests.py - sqlalchemy.exc.InvalidRequestError: Table 'players' is already defined for this MetaData instance...
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
========================================================= 1 error in 0.14s ==========================================================
how to fix this error in SQLAlchemy?
After folder structure restructuzation it started to appear
The created on works?
yes
but i want to sort by published and not created on
Thats weird its literally the same
so been making changes to do published on
right
just a diff variable name lol
wait
nvm
?
changed created_on to published_on lol same error
Huh.
So created kn doesnt work
!you said something for modifying the published on
What modifications exactly
well no created on does work, but published on doesnt
so right now posts are sorted by created on rather than published on
and ive been just doing ctrl+f and replacing created_on to published_on
and made this change in models.py
and thats when it broke
yea posted it on stack
Np
I've only just recently started working with the frontend so its a surprise to me the vanilla JS is considered overkill. What would a web developer even use on a simple website?
vanilla JS is not overkill. It is just Dirtiest thing to use
that's why people just use regular html/css if they aren't fully in frontend
and if they are in frontend, then they go for frontend frameworks. I can recommend Vue.js as being quite simple and nice experience
and regular CSS kind of sucks too. SCSS for the win.
