#web-development
2 messages · Page 165 of 1
woah, Thank you, is there also a tutorial that teaches about rest api using flask?
pretty sure there is hold on
ah man that was for django
Im using django
so in your form submission view
when you save the form
you can do this
instead of form.save()
you can use instance_of_form = form.save(commit=False)
now instance_of_form is a model
that corresponds to the model in the modelform
then you can insert whatever you want
so like
instance_of_form.date = django.utils.timezone.now()
oke, if you find a good tutorial Flask for api please tag me, thanks a lot
Hello Dear Friends,I wanna say that I have spring boot ecommerce backend + advanced design + clean code + unit tests if you are interested in my app please contact me!
!rule 9
And how can i compare dates?
for example: if 5 days passed after my purchase
im pretty sure you can access the models and subtract them
other than that im not really sure
oh, thanks for the info
Is there a value set for the checkbox input? If so it will be truthy since None is falsey.
if request.form.get('input_from_checkbox'):
do_something_when_true()
else:
do_something_when_false()
here's the html part
yes
its a check box so no submit button
<div class="form-check form-switch">
<form method="post" action="">
<label class="form-check-label" for="addToDb">add to your collection</label>
<input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" name="toAdd", value ="True">
</form>
How are you submitting data then? Do you have some JS that's submitting on the checkbox click?
no this is it, do i need a submit button too?
Should I first learn HTML, CSS and JS or should i learn html and css and use flask as backend?
I barely know about HTML, and I want to design a webpage for my project, nothing complex just the website showing features and dowload buttons, guess that's a static website right?
You should definitely learn HTML/CSS. JS would be a good thing to learn, but I don't think it would be necessary.
it gives me parse error, can someone tell why?
I see some " marked in red there
Probably you have to fix the strings
Alright
I now the reason lol, but it doesnt get fixed in any way
Alright my bad
No worries, it's pretty interesting situation
I have certain texts on site (flask) that may be edited from time to time (like description of site in /about). Because manually rewriting jinja templates just for these parts may be a bit far from optimal - I thought if there is some recommended way to insert markdown texts into these?
I've found flask-markdown package on pip, but its from 2010 and never updated since then
it just feels like such trivial and popular idea (everyone love blogs, right?) - I refuse to believe there is no package to solve it
store the info in a database, render it to html, when you want to edit basically edit the info in the database
simple as that
Anyone know how to get the sec- headers to send from a browser? Ive checked on other sites and it does work but what ive read says it should just magically send.
answering myself: used https://pypi.org/project/Flask-Misaka/
Normally I'd go for any (edit) AWS service any day (cost-wise).
I've been happy with EC2
cuz money
just checkout wether scalability is an issue for you or not
All of the options they listed are different services in AWS
They were asking which AWS service to use
Sorry not what I intended @calm plume
Okay that is why I am too
thanks for pointing that out
I've used light sail, not elastic bean stalk
An ec2 instance gives many hurdles in automating
I have not used light sail, or at least don't remember using it
And with the database, have used RDS small scale, never aurora or Redshift, this time it'll be a huge DB so needed some help figuring with scaling
I'm having some issues of my own
with Heroku that too
literally NEVER had an issue with Heroku before
Why does django not work well with mssql
I wish it did
Or at least as easily as it does with oracle
It works great with heroku
goddamn my flask app is such a clusterfuck
*postgres
lol just spent two hours trying to get my basic heroku app running cuz I messed up my requirements.txt file
yep
except for the fact that all my static files are giving up on me
so that's just…so great
it's 4:22 AM here
http://whitenoise.evans.io/en/stable/flask.html might do the trick. haven't tried with heroku though
Thanks so much!! Thought I already found out what the issue was ... Another typo
(phone acc)
😭😭
GCP mini and dedicated reservations are the cheapest on the market rn
IBM is much easier though that AWS or GCP, though GCP is all automated bots and no boys though
Hi
Im trying to get data from my db
but the .objetcs.filter() function return me <QuerySet []>
these are my models
class Purchase(models.Model):
total = models.IntegerField()
date = models.DateTimeField(auto_now=True)
user_phone = models.CharField(max_length=50)
id_user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
class Purchase_detail(models.Model):
id_product = models.ForeignKey(Product, on_delete=models.CASCADE)
id_purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE)
quantity= models.IntegerField()
price = models.IntegerField()
and this is how can i use the function
def see_purchase_detail(request, id):
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
purchase_detail = json.loads(serializers.serialize(
'json',
Purchase_detail.objects.filter(id_purchase=id)
))
print(purchase_detail, Purchase_detail.objects.filter(id_purchase=id))
return JsonResponse({'details': purchase_detail}, safe=False)
else:
return JsonResponse({None}, safe=False)
Im using django
hey how do I make a python script to detect if there is a new GET from a page?
i have return render(request, 'Pages/home.html', context) in my views function but it gives a 404 error that home.html does not exist, but i think i gave it the correct path
If you are using an app
nvm i hadnt added my app to settings.py
put it in the INSTALLED_APPS list on the settings.py
ya that fixed it 😅
where should one store the js file in a flask app?
is it possible to use a template from another app? i wanna make a navbar but i want them all to use the same layout
/static/js
A js folder inside static
thanks!!!
hey how do I make a python script to detect if there is a new GET from a page?
Make a route to accept request (Which leads to some method)
The answer is different for different frameworks
Can't say more precisely without knowing which one
May be it is just empty db
print(Purchase_detail.objects.all())
will print everything you ve got there
I don't know. I'm not using a framework
Start using one then
why
I think I don't know enough about your situation then
Are you web scrapper?
The web site is not belonging to you?
? I'm nothing, just a guy who wants to know when my browser do a GET method
Oh that is what you are doing...
I have just a bit of experience with python
...well.. the easiest would be making something like chrome extension, attaching javascript to internal browser APIs
With python it would be harder, but you can look for sniffig, how to make sniffing to intercept browser requests with python
my friend said the same, but there is too much just to know if my browser do a new GET method, maybe with the shark thing it will be easier?
wireshark
Oh yes, it can help a lot
It will give answer, what you will be able to do in python
Since you would see in comfortable GUI what can be done for sniffing at all
actually I will use pyshark not wireshark itself 
Is not empty maybe the problem is due to that column are a Foriegh Key
But i am searching in the docs
oh sorry and thanks
i have added 'DIRS': [os.path.join(BASE_DIR, 'layout')],# Add this line to my settings.py file to have layouts accessible to all apps, how do i set my {%extends "layout/layout.html"%} so that it points to the folder
In don't find anything
Yeah, think about making browser extension.
It will simplify your task ten times
Other option is refactor the data from Purchase_detail.objects.all() with javascript
But is meh
actually I just want to make it for all browsers and just with python
Oh forgot to mention
Just... use....
Purchase_detail.objects.filter(id_purchase__pk=id)
You can specify after __ any parameter of sub obj attached to foreign key
including user id, phone and etc
Or actually...
You could make a search for purchase, before trying to search purchase detail
It don't work :C
I tried with Purchase_detail.objects.filter(id_purchase__id=id)
But also don't works
purchase = Purchase.objects.filter(pk=id).first()
Purchase_detail.objects.filter(id_purchase=purchase)
Perhaps this one then
i will try
Request all your purchase objects, and check their pk
The Puschase.objects.filter(pk=id) works
A return the Purchase
But the second line no
how do i get the records from another table based on the id of a table and display them on the admin panel, for eg i want to get the name of a countries based on a 'continent' id
id_purchase=id or id_purchase=purchase are returning a QuerySet with no lenght like always
Request all your purchase_detail objects, and check their pk
should i use python for back-end web development?
Python is a wonderful language for backend web dev, so yes imo
would it be good to use for bigger websites when i get to that point?
Instagram are using django
According to stackshare.io/django
Yup, Instagram uses Django with a fork of CPython called Cinder
thanks
I'm so dum
a check my db
what would be the limits of the working with Django ORM + Postgresql
I mean... there are certain technics like sharding for databases
what would be the limit of scalability without it
and how well technics like that could be applied to Django ORM applications?
No idea, I haven't gotten in to it that much
But Postgres scales very well
So it should be able to go pretty far
btw, I got advised by devops guys to read a cool book regarding it
Martin Kleppmann - Designing Data-Intensive Applications (O'Reilly 2017)
"The big ideas behind reliable, scalable and maintainable systems"
I've never heard of it, but O'Reilly is pretty reputable, and it seems like it's quite interesting
Looks like it'd be worth a read for me
.bm
Why Postgres and not mysql?
I haven't used MySQL, so I have no idea how it scales
But more people use Postgres including the heroku
Here's a good article detailing the difference: https://www.xplenty.com/blog/postgresql-vs-mysql-which-one-is-better-for-your-use-case/
Oh yea... Definitely
I am currently working on a website project, would anybody like to collaborate with me on it?
It's to generate PDFs or PNGs from LaTeX.
just finished learning python. anybody knows some good udemy courses so that i could start on web dev?...
I normally wouldn't recommend udemy at all
I'll ask you a question or two, and I'll give you a tutorial series
do you want to start out by building a simple blog site, or a webapp?
ned help
which is best
flask + bootstrap or flask + react
and
why css not working
how do I use CSS to centre a circle (like smack bang in the middle of a webpage)
and I want resize compatibility, so like if the user resizes the window, it should still stay in the centre
nvm got it
but still its difficult
to understand
Hi! How do I build a desktop application with python? Which IDE should i use?

oh if i use vs code, can i like code and launch a desktop application? sry... im rly new to programming
surely
python is not requiring actually anything to run it
except having installed python
(and installed dependency into your virtualvenv)
you can launch project literally from console
the only small specific about desktop applications
that they are at a later stage, minimized with something like pyinstaller
to be not dependended on python,
making some .exe file
oh okay. thank you!
Is there a way to create custom types for a Django model like with SQLAlchemy?
Thanks. I think I know how SQLAlchemy's column types work but not Django ORM's
I think I am having an opposite of the problem
yes
you need to define a custom model field class
with the methods to serialise and deserialise etc.
but why do you want to do that?
I'm planning to use Django as my backend that will read the data from the DB
Meanwhile there's another portion of code that creates data, that uses SQLAlchemy
!? why
It's a complicated architecture
I think I'm stuck in a bottom pit
any idea or way of rewrite those lines?
i usually dont go for udemy but i have a coupon to which i can get one course for free (t and c applied) thats why im asking so that i can be more familiar with web dev
they do have a lot of courses
ikr and i cant choose which one to go cause of my zero experience in web dev
I'll help out
i was thinking about this one https://www.udemy.com/course/the-complete-web-developer-zero-to-mastery/
hmm
right off the bat, there's just too much to learn at once
If you're comfortable with javascript, then learn react only
or node js only
😩 that's hurt
im only comfortable with python at a moment
don't learn two heavy frameworks at once
then I wouldn't recommend you take this course
get familiar with javascript first
ohhh
What do you wanna build with web-dev
is javascript the best language for web dev?
it's the most widely used
career opportunities
frontend web dev*
javascript it is
Though I'm a django lover it's the harsh reality
and even for frontend devs, javascript is augmented with typescript
imma get my hands on javascript then
it is but not a lot of companies are using django
frontend = about making visual part of the web site
backend = about making server side functionality, which is fetched to be shown on frontend
i cant learn too many things at a moment i have my school studies as of now too
ohhh
alright, let's start small
shrugs.
laravel and php is still quite popular
as far as I know
django is good too ;b
but php is probably more wider used
first, focus on getting familiar with javascript. Then, pick up node js
imma be a dev at microsoft and will LeAk wiNdOwS 18
If you want you can DM me if you want a learning path
ughhhh
yeah, node.js can work too
you can be completely full stack web dev
while knowing only javascript
yep
my brother's best friend just got an internship at google, he a web developer (idk front or back though) as an internship they paying a hella amount of money
You say not a lot of companies are using Django but I've never been out of work for even a few days in the last 5 years or so
pretty anecdotal I suppose and I don't know how the market is where you live
hehe, i can vote for this too
I am not having a shortage of work in Django too
loving this framework.
Blazingly fast development
It's also worth noting it's not too bad to be in a niche. Sure, it might be easier to find a job with Node, but you probably can't demand as high of a salary, either, because there is just so much competition.
I really like Django for prototyping
maintainability can get problematix
but at @ small scale it’s just SO EZ to get something up and running quickly
you do freelance dev?
I don't have much problem with bigger projects personally, Instagram is still running on Django last I checked. I dunno, I think it's a problem in any framework that things get a bit hard to find as the codebase gets bigger
I do contract work for a single company full time at the moment, but I have freelanced in the past.
is it absolutely necessary to set max length validators in wtforms?
class ContactForm(Form):
name = StringField('name', render_kw={"placeholder": "Name"}, validators=[DataRequired("Provide your name.")])
or is it enough to just set a field?
Or what i am acutally trying to ask: If I do not set max length, could people cause overflow errors or something like that and would this make my app unsafe and prone to hackers?
so is setting max length mandatory?
Depends where it's going after your form handles it
The server will have some maximum request body size anyway so if it's truly large it's unlikely to get through to your form in the first place.
Yeah there is not really a reason not to, here.
Python webservers dont even limit the amount they read because idk
10MB is still enough to cause issues depending on your setup
if it's a small enough server it's running on then 1000 connections all sending 10MB will cause issues
that doesn’t mean there aren’t aspects of a framework written in a dynamically typed language that aren’t objectively harder/impossible to test
“less maintainable” doesn’t mean “unmaintainable”
I'm sure there are some cases where that's true but whenever I looked into the research into this it didn't seem like statically typed languages have any overwhelming advantages in reducing bugs. Admittedly the research into this has not been super robust, or it wasn't when I last bothered to read about it, anywhere. In therms of "maintainability" I'm not so sure because it seems like quite a subjective term by it's nature. I would be interested in reading if there are objective measures though.
Hello, I am currently migrating my strapi api (Very basic) to FastAPI, but i want to "secure" it so no other app than my own app / Frontend is allowed to get the REST API data. How would i do that, i already using JWT for user authentification via Login, BUT i dont want to authentificate a USER, i want to allow my frontend to communicate with the API, how would i do that?
I am thinking about API-Keys like other API's are using it, BUT i am not sure how someone would implement it any suggetions?
it depends on the language
Python’s type hinting can more or less replace something like Java
but FP languages have more powerful type systems, IME, that really help
People using your frontend are going to be able to access the API keys and thus use your API anyway, I'm not sure it's worth the effort.
Btw I was wondering if it was possible for Django to read a database and "analyze" its contents to generate an object model. I know SQLAlchemy can do it with MetaData but I heard Django ORM wasn't as evolved.
At worst i'll just copypaste the fields
Its pretty much impossible to make it so only the front end can use the API sort of server side rendering everything and just not exposing the API to the outside world at all
If the api is exposed, and is used by the fronted like React, Vue etc... Its easy enough to get around anything you can do to try and mask it
Well, I think that's also very subjective, because when most people I know look at a functional language they are extremely confused :) My answer isn't very satisfying I suppose, but I think there's a barrier of accessibility for FP in general, hopefully it can be resolved somehow.
there are invariants you can statically verify, such as the existence of fields in the case of complex join queries, that are more or less inexpressible in Python (for example)’s type system
oh, I defo agree
and that’s 100% something you need to take into account as a tech lead when choosing the stack
Currently the only people I know who like/understand FP are math nerds, and that for sure ain't me and probably ain't most programmers either.
whether your present/future team can actually work with the language
Can you elaborate a bit more?
it’s a spectrum, right
don’t you use comprehensions?
@quick cargo@solar epoch Hmm ok i do understand, but how does other API's it? Where i need an API Key for my app to even use it? For example openweather api or Firebase? Hmm, i usually would not care but was wondering.
I've heard Python is probably not the best for webdevelopment but I never really understood why. Same ppl would privilege C#, Rust or Go.
the Python ecosystem is VERY developed
if you want something there a package for it
Sure, I use comprehensions, sometimes I even use map() :)
I tried to write a webapp in Rust and it was HELL
comprehensions are MEGA FP
yeah I mean that's why I use Python, right, I can use the handy bits of FP and discard the stuff I can't read :P
I mean no api can realistically stop you from using an alternate setup for requesting data from the API, you can only add auth to control who can access the data. You can somewhat limit what websites can use it via CORS but that's purely for browsers
Suppose you have a polls table already created in a SQL DB, with a couple of rows inserted. Django must use this table to expose its results. Knowing that the schema is already prepared, is there a way to generate a Django model from it?
I’m not saying you have to use monad transformers and higher-rank polymorphism
(which I don’t really get tbh)
I dont believe so, and i think by the time you work out how to do that you might as well manually implement the model
but you DON’T need those super hardcore aspects
Indeed that's kinda my point, right? I can use functional bits of Python where it makes sense and is readable. But in say, Haskell, I'm kinda forced to understand monads and stuff, right?
I wouldn't say Rust is really that functional but I don't use it very often so I dunno
I don’t even know Haskell 🥴
Or Java
on the surface, not really?
but its type system
well Rust is imperative @ its core I’d say
but it also has a lot of compile time benefits which was more what I was going for
and it uses functional ideas like ADTs and pattern matching
yeah this is kinda why I hate language ideology, like why use a "pure" functional language when you can just use the best bits?
the borrow checker is basically affine typing
i have added
def __str__(self): return self.title
to my model but my dropdown for the admin panel is still the same and when i attempt to migrate it says no changes were detected
well, avoiding mutable state has its own benefits I guess
that’s not a model change
so it won’t appear in a migration
lemme try that
Hmm I think it does use __str__() but only if you don't set the fields yourself.
nope, the dropdown still displays the object
@quick cargo @solar epoch Well i guess i leave it then for now open accesable API :/ thx for the answers !
Google says
Showing the admin class might be useful
you should be able to configure it in the form
class SubjectsAdmin(admin.ModelAdmin): exclude = ('status','created_by','modified_by', 'branchid','pastpaper_visibility', 'visible_stat', 'uservisibility', 'solved_papers_visibility', 'untopical_visibilty', 'topical_visibilty', 'topical_books_visibility', 'qbyq_visibilty') list_filter = ('cat_id','title') list_display = ('id','code', 'title', 'cat_id',)
oh is this just for a regular dropdown, sorry, I misunderstood
wait
you put __str__() on the ExamCategory model, right?
it is?
yup
I thought you were using autocomplete_fields originally
nope im not
mm, __str__() on the right model should work
reload server / etc.? I'm not sure otherwise, would have to tinker with it
ive already done that and it does not work, im gonna continue to keep tinkering with it and see if i find something, thank you
If you can share the whole models file with your changes it'd be useful
`
class ExamSubjects(models.Model):
class Meta:
verbose_name_plural = 'ExamSubjects'
cat_id = ForeignKey('ExamCategories', default=None, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
code = models.CharField(max_length=255,default=None, null=True)
description = models.CharField(max_length=255, default=None, null=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
modified_at = models.DateTimeField(auto_now=True, null=True)
created_by = models.IntegerField(default=None, null=True)
modified_by = models.IntegerField(default=None, null=True)
def __str__(self):
return self.title
`
Wait, where is your exam category model?
That's where you need the str
omg that was it
i thought i had to put it in the model where i used the foreign key
thank you so much
I'm not sure that's something that can be explained with a few discord messages, you probably need a book or at least a few articles
another question i have is how do i set a custom name for my the name for my admin panel fields , for eg i have a field named body but i want it to be named description in the admin page
hmm you can set the verbose_name on the model field. I'm not sure if there's anything simple you can do in the admin itself... maybe with a custom form but it'd be a bit of work
so can anybody explain this in voice chat pls
well it wouldn't be that much work, but it's probably still annoying to write a custom form if you don't have to
i manually deleted a table from my db and when i try to migrate it says the table does not exist, how do i fix this 😅
Nuke the whole db and start over if there's nothing important in it
or you can manually create the table from sql
You can delete the migration to before you deleted the table
That sometimes works for me, but most of the time I also just nuke my database
i nuked it and everything is working now
I don't really understand some methods from Django Field values
how do i make it so that for a foreign key it shows a specific field and not the id
Aren't get_db_prep_value() and get_prep_value() redundant? I just want to pass an array as a BYTEA field
So far it looks like this:
class NumpyField(models.Field):
description = "A Numpy array from bytes"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def db_type(self, connection):
if (
connection.settings_dict["ENGINE"] == "django.db.backends.postgis"
or connection.settings_dict["ENGINE"] == "django.db.backends.postgresql"
):
return "bytea"
else:
return "varbinary"
def from_db_value(self, value: Any, expression, connection):
if not value:
return value
out = io.BytesIO(value)
out.seek(0)
return np.load(out)
def to_python(self, value: Any) -> Any:
if isinstance(value, np.ndarray):
return value
if value is None:
return np.ndarray
out = io.BytesIO(value)
out.seek(0)
return np.load(out)
I think you can do e.g. fields = ["category__name", ...]
it'll hit the datbase for each row though, so you might want o use select_related on the queryset
I want someone to help me Dm Me For help Pls
i did ```python
list_display = ('id','code', 'title', 'category__title',)
oh my bad, the docs have you covered though, you can make a function to get the related field: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
thanks, ill check it out!
How can I create subdomain for each user in django?
Let's say there are two user with username1 and username2 and my domain is domain.com , so I want there profile should be opened as username1.domain.com and user2.domain.com
Like as website opens in GitHub or wix and lot more
Have you looked at the sites framework or do you need more help than that?
Hey, so i have made a registration form and i would like to access the username that the user submitted as a variable. How would i do that?
This is my main.py: ```python
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm
app = Flask(name)
app.config['SECRET_KEY'] = 'fdc00fc2de7015cd9477a90b7de191a9'
@app.route('/home')
def home():
form = RegistrationForm()
return render_template('index.html')
@app.route('/about')
def about():
return "About"
@app.route('/register', methods=["GET", "POST"])
@app.route('/', methods=["GET", "POST"])
def register():
form = RegistrationForm()
if form.validate_on_submit():
flash(f"Account created for {form.username.data}!", "success")
return redirect(url_for("home"))
return render_template('register.html', title='Register', form=form)
if name == 'main':
app.run(debug=True)
my `register.html`: ```html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title>Flask Forms</title>
</head>
<body class="bg-dark text-white">
{% block content %}
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }} text-center">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>
</html>```
and my `index.html`: ```html
{% extends 'layout.html' %}
{% block content %}
{{ form.hidden_tag()}}
{% endblock %}
We can access the input data on form with request.form.get("<name of input tag to get>")
You have to import request class from Flask module
To request data from the form
Hope this answer is correct........and fulfil your needs
Um, do you mean, like firefox's source code for example? Or something else?
I'm not sure what you're hoping to find from it :)
There's also https://source.chromium.org/chromium
which is basically unbranded google chrome
hey guys! I am planning to start web development and I do not have any experience (in web development not in coding) why should I use python instead of html and css?
Regardless if you use Python or not, you'll still be using HTML and CSS
so what is python for?
for dynamic content
so reading something from a database, doing calculations, deciding which pieces of html to show, ...
If you're new it's a good choice I think
why?
that's very subjective
react is just a js framework for making stuff reactive
if you're a beginner to web stuff you should maybe not worry about it too much
you can update text dynamically in javascript
must learn if you want to get into web dev
learning JS is probably necessary but you don't necessarily need to learn react
frontend frameworks are highly subjective in any case
you can create useful websites without needing any JS, it's mostly for making a nicer UX
then what I see here is I definitely should start with html and css, I need them anyways
yeah
the django girls tutorial is pretty good if you want to get something working in a short space of time without any background knowledge https://tutorial.djangogirls.org/en/
you don't even need to know a lot of CSS really, it's not a programming language, it's for declaring layout
and HTML is super simple, it's just markup
can anyone suggest a better logic for this?
https://paste.gg/p/anonymous/d975bbb939364370804677dd97cebfbc
That's probably how I would do it. There are a couple of other ways... You could shift the logic to the context process and in the template do {% if can_see_x_link %}...{% endif %} or you could make a context process to return a list of dicts with the stuff you need, then in the tempalte something like: {% for link in nav_links %}<a href="{{ link.url }}">{{ link.name }}</a> or something.
I wouldn't say any is really better than the other, depends what you prefer I guess ¯_(ツ)_/¯
Do the cs50 course its free
alright thanks. so by "That's probably how i would do it.", it isn't bad?
As long as you can read it and it doesn't turn into a mess at some point I think it's fine
It's all in one
Intro into programming then some web with python too
hi what do you recommend instead of spaced keys with commands/texts?
"great racing game": showText
js, objects
array with commands?
like tasks: ["great racing game", "second", "third"]
I'm making sth like this u type the text and result is given
currently I have like this:
const tasks = {
"great racing game": showText,
"show car": showCar,
"update os": updateOs,
"show popup": showPopup
}```
the keys are mapped to user input
how can i do web scraping? i want to take for example btc value
Bitcoin value? You could use API requests for that
But for webscraping, you have requestsand bs4(stands for BeautifulSoup)
For more advanced webscraping there’s Selenium (for JS) and Scrapy. But the most appropriate section I think is #data-science-and-ml
I think. I’m not sure bc webscraping is more for gathering data
import requests
response = requests.get(TICKER_API_URL+'btc')
response_json = response.json()
return float(response_json[0]['price_usd'])
Not sure but it may work
i just want to get some cryptocurrency values
Check if the status code is 200 for more safety
and dont know how to do it
import requests
TICKER_API_URL = 'https://api.coinmarketcap.com/v1/ticker/'
def get_latest_crypto_price(crypto):
response = requests.get(TICKER_API_URL+crypto)
response_json = response.json()
return float(response_json[0]['price_usd'])
get_latest_crypto_price('bitcoin')
These infos are available on APIs so you have to find one that you can use, then request an API token (to use the API). Once it’s done you can use the requestslibrary to extract the information you want
ty bro very helpful but that link he uses doesnt work anymore u know where can i get a good one?
There are many websites that moniter crypto. Just check any one.
So how can one bypass 403 response - Forbidden error. The server understood the request, but will not fulfill it.
I make the request to google that returns 200. But I am making request to another website that 403.
When I open the same url in incognito, that website still opens.
I have done the following, but neither worked
response = requests.get(url)
response = requests.get(url, auth=(username, password))
I suggest you ask the question then
my bad
body {
background-image: url("mai_sakurajima.jpg");
}
this is my css code
yep, looks ok
glad I could help :)
i had my styles.css in my css folder
but my picture was in the project folder but right outside of it
dang
ty
hey this isn't really a python question but hopefully someone has a quick answer: I have a web app running locally, on localhost:portnumber. I keep forgetting what the portnumber is. is there a way to make it so I can type localhost/my-app in my browser and have it go to that port instead
or my-app.localhost or something
just giving the port a name
im on ubuntu
Might just be easier to bookmark that URL in your browser if the port number isn't gonna change frequently
yeah bookmarking is probably simplest
Hello folks how do I add /health as an endpoint which responds to GET requests with status-code 200?
I have no clue
with which framework?
Does anyone have any good tips for a Django CMS when building a blog? Is the best way to post the blogs through the admin panel?
Or creating individual blog posts via static HTML files?
if you only want a blog, and one where you're the only author (or guest posts are rare) you should probably not use Django, but a static site generator in most cases. But if it's part of a bigger site, then... it depends. I would just use the admin panel. If people who are less technical are going to use it maybe you will need to provide a better editor.
Does anybody have a good ressource for DRF especially for FastAPI/Flask-RESTful users? I must admit putting classes everywhere confuses me a little bit
Ie, how would an @app.get would work with these ApiViews?
single backend endpoint that returns paginated data (needs to actually return paginated data) and a frontend to fetch that data (doesn't need to display response, just fetches the data)
May 20, 2021
403 means the page exists but you’re not allowed to see it. So either your credentials were incorrect or they don’t exist in the db
Could someone explain to me how I might get "oEmbed" working with Flask? I see there's a method using .json files, but that doesn't seem wise to do with Flask
I was trying to follow the information here: https://www.reddit.com/r/discordapp/comments/82p8i6/a_basic_tutorial_on_how_to_get_the_most_out_of/
I am using selenium to make a script it is also using a chrome driver
Now that script is running on my machine
Any way to host it on some server
To run
Because it closes as I close my PC
ok thanks, I'll give it a look.
When would this happen if requests.get and asyncio with aiohttp would take roughly about the same time?
If asyncio and aiohttp isnt set up properly?
Or could companies or developer who designed the api, limit the threshold/limit to how many requests can be made per second?
Made 55 requests, requests took 189 seconds
asyncio with aiohttp took 206 seconds
A blog is just a quarter of the website. Would much rather use django as I have the freedom to build. I just researched and found Wagtail! Looks super interesting and very scalable for other content writers
I haven't used it myself but I know some of the wagtail people so I think it's a good choice
Sure, you can run it in headless mode
Well... with django things are a bit different, it doesn't use decorator based routing. Typically there is a urls.py with your routes in, that point to a function. Though you mention you're using the class based views, in this case you use MyView.as_view() which returns a function that's run when you hit that route
Also, a serializer un DRF mostly transforms the queries in JSON data, right?
Meaning the intermediate stuff gets done there
and from JSON to the ORM, yes.
What is a headless mode ?
though they don't strictly serialize to json, you can render that data as a csv, say.
Hi there. Anyone free to do a hobby python project with me?
It's a way of running selenium without having a graphical display.
Because I’d like to handle authentication and authorisation based on user roles
Like who sees what
Ohhh can you provide some resources ?
does anyone know how get a variable from another file to my webpage ? or can you directly create variables in the web page itself (in Django)
What browser do you use? Each one has their own options but I believe headless is common for both Chrome and Firefox
I prefer using Selenium with Firefox bc Chrome is a pain to test with
Chrome
Edge
Both I use
Sure, you can do that, DRF has a permissions system that's reasonably easy to use.
The thing is: I have the data, I have an idea for an endpoint and who should see what, I just don’t know where to start lol.
For now the only endpoint is a list of prediction points you can see according to multiple filters
ok, you might want to look at APIListView and depending on how much filtering you need, you can do it manually, but probably better to use the django-filter package, it has a nice integration with DRF.
If what you want to list isn't as simple as a bunch of database rows from the same table, it might not work for you, but if it does, then it should work
for the permissions, you make a class and stick it in the view class as an attribute
probably the docs explain it better than me: https://www.django-rest-framework.org/api-guide/permissions/
Django, API, REST, Permissions
Guess I should look at the APIView then. No need to elaborate on the serializers?
if you're just listing stuff, the serializer is more or less just there to determine which fields you want to output
For the simplest case it's just:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ["id", "some_other_field"]
Oh yeah, it’s a nice way to put a DTO here
hello , i got a flask route that return this return jsonify({'webshellFiles' : webshellFiles, 'normalFiles' : normalFiles}) and those two are arrays , how can i them in response variable in fetch pls?
fetch you mean the fetch api in js?
async () => {
const response = await fetch(...);
const data = await response.json();
// now access them as you would a regular object
};
after you do the response .json() you can destructure
async () => {
const response = await fetch(...);
const data = await response.json();
const { webshellFiles, normalFiles } = data;
};
in FastAPI, if i create a cache singleton instance on startup, how to i access it from within a router?
is there a way i can make a dynamic dropdown menu based on a selection from another dropdown
for eg, when i select a continent, only countries from that continent will show in the country dropdown
you could use a frontend framework for this. let's say you have your continents and countries stored like this:
const data = {
"north-america": ["USA", "CANADA", "MEXICO"],
"europe": ["FRANCE", "SPAIN", "ITALY"],
}
then, you can use data binding to bind the country options based on the continent. here's a vuejs example
<select v-model="continent">
<option v-for="country in data[continent]" v-model="_country">{{ country }} </option>
</select>
thanks, ill look into it
im trying to make a custom field in the admin panel, i used the format the docs gave which is ```python
change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
but it still does not work
my path is ```python
change_form_template = 'admin/Papers/extras/Papers_change_form.html'
Error: https://paste.pythondiscord.com/yopumehayo.sql
Code, Descripion: #help-cake message
Flask help. Why doesn't adding /blog to the url work in the following snippet? what am I missing?
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/blog')
def blog():
return render_template('blog.html')
if __name__ == "__main__":
app.run(debug=True)```
^ is driving me bonkers!
/blog gives me a 404. The html file exists
In fact, if I reverse it and place it as the file for the / it works just fine
The index and blog file are in the same Templates dir
I've accomplished with other projects...and I can't see what I'm missing...
Are you sure you want quotes in that query?
And if you do, add one to the end
Are you querying an API? does the documentation list how it wants to receive that element?
While the YYYY-MM-DD is a string, typically, I use a dictionary to build the query and then tack it on to the end.
Well, that's good since you control the methods 🙂 Add a double quote to the end though
Be consistent. Quotes all around or none
As for using a dictionary....
Assuming requests imported...
parameters = {
"key1": VALUE,
"key2": VALUE2,
"formatted": 0
} # or whatever other key:value pairs you require for the method.
response = requests.get("https://api-endpoint-url.com", params=parameters) # and whatever method required obviously
response.raise_for_status()
working_var = response.json() # Now I have what I need in json format :)
I find loading a dict for parameters makes it INFINITELY easier to manage method calls
Python takes care of building the query for you
I'd start with the documentation. But scanning that I'd start with...
parameters = {
"date_from": date_from_var,
"date_to": date_to_var,
}```
once you load dictionaries for parameters in API calls you can never go back though 😉
Now, I don't have experience with Django yet and I'm only on day 56 of a Python boot camp...so don't take that as gospel
I'm just learning Flask. Django comes later 😉
Only day 56.
57 days ago I knew none of this...so noob
Well I'll be....turns out '/blog' must be reserved in Flask!
in Django request.POST returns a dictionary, but what dictionary though?
where can i host the django app with celery and redis except heroku. My problem with heroku is it asks billing information for Heroku Redis which I do not have.
any vps provider
hetzner is good
(requires knowing how to deploy in linux on your own)
they just provide server OS of your choice
there free tiers in some providers
you can visit my website in www.anirbanm.epizy.com
Anybody here who can help me out in html ,css who knows it well
I have a list of items which are put into a dropdown, how can I pass the selected value and filter the list accordingly? I am using starlette/fastpi
so u'll have to create an & query.....firstly you'll have to convert the date received from string to a date or datetime object depending on your model
then u can use in your query filters
model_name.objects.filter(created_at__gte=<range_start_point>) & model_name.objects.filter(created_at__lt=<range_end_point>)
How to retrieve data from onChange (storage listener) with js in Selenium?
This doesn't seem like much to do with web development
Ok I'm confronted to a difficulty with DRF. I have a Numpy array stored as Bytes in the DB. With my models I can retrieve it just fine. My question is how should I serialize it
not really web development, but whats the standard for applications that hold data offsite? Should every query on my client request the server, or should i request for changes?
Like, should I create an image through a function from that np array, then return the URL serialized?
As a sort of cache
I am not super familiar with numpy, but if you can dumb it down for me... is it like a list of numbers, more or less?
It's kind of an array structure mimicking MATLAB's matrices
numpy arrays can have multiple dimensions. What I'm trying to do is reconstruct an image when I make an API call
Decided to store the np array as a BYTEA column because it was small enough
hmm, well, it's possible to have n dimensions in a DRF ListField but I think you need to know the number of dimensions in advance
e.g. for a 2d array you can do ListFielf(child=ListField(child=FloatField())) or so
I'd like to know if it's possible to invoke a function that will take the np array, create an image then return the image's url
Like this:
NP ARRAY -> IMAGE URL
During serialization
I want to provide some sort of cache to avoid making too much
you can implement the cache however you like, with Django's cache framework or maybe something simpler.
(though django's cache framework is already quite simple)
are these np arrays supplied by client or stored?
yeah if they're stored you can just cache the url directly in the database
yep, and if they are supplied you can construct some sort of hash -> filename table
and maybe have something delete rows and files after X time not accessed?
Stored in the database as BYTEA then translated when the Django models calls them.
if they are fixed then you should probably create the images at insertion
I would just do that translation on save
and delete them at delete
Assuming it's read more often than written anyway
yeah, if they are fixed
Yeah i planned to keep the data stored in bytes just in case I could exploit heatmaps on a JS frontend
or any JS structures illustrating SVG-like imgs
mm, disregard all i posted, i think i misunderstood what you were talking about
Btw I encountered a session_error when I started the API. What happens exactly when you make migrations when the table already exists?
ProgrammingError at /api/
relation "django_session" does not exist
My Docker entrypoint script looks like this btw:
#!/bin/bash
# Run Django server with DB init
python manage.py makemigrations
# Migrate
python manage.py migrate
# Runs the server
python manage.py runserver 0.0.0.0:8000
you probably shouldn't run makemigrations or migrate from a Dockerfile
migrate is maybe ok but you should run makemigrations manually
sometimes it can prompt for input, for example
also if you're not usually a volume the migrations won't necessarily end up in your local filesystem
For this one I'm exceptionally using a local folder for the db
hm
why though?
it was small enough so I thought I should keep it that way + it can be reusable for a frontend framework
class User(AbstractUser):
""" User model """
username = None
first_name = None
last_name = None
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=False)
is_employer = models.BooleanField(default=False)
company_name = models.CharField(max_length=50, blank=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
def clean(self):
if (is_employer == True and company_name == ""):
raise ValidationError("Employer must fill out company name")
Why isn't the clean function do anything in my model when I try to add something trough the REST API?
DRF doesn't run the model's clean() method, you should add your validation to the serializer
<form method="post" action="{{url_for('delete',post_id=post.id)}}">
<label class="form-check-label" for="addToDb">Watched already?</label>
<input type="submit" value="Drop" class="btn btn-danger" name="dropIt">
</form> ```
i am getting an error that post_id is missing although i passed it in url_for
Ok cool, thanks
Found this nice extension for geospatial data
Hi ! I try to open my quart web server in my browser but it's not working... Here is my code :
app = quart.Quart(__name__)
ipc_client = ipc.Client(secret_key=TOKEN)
@app.route("/")
async def index():
member_count = await ipc_client.request(
"get_member_count", guild_id=840333999003533432
) # get the member count of server with ID 12345678
return str(member_count) # display member count
if __name__ == "__main__":
app.run(host="localhost", port=8000)
(you can ping me if you have any idea)
hi, never heard of quart framework, but have you tried setting the host on 0.0.0.0 and go to localhost:8000?
not working :/ and quart is like flask but async
i fixed my issue, but i now have another error...
OSError: [Errno 10048] error while attempting to bind on address ('0.0.0.0', 20000)
this means that your server is trying to bind to a port that is taken
found the solution
try another port
need some help deploying a fastAPI dockerized backend (with docker-compose too) to heroku
I was doing a tutorial on flask(https://www.youtube.com/watch?v=dam0GPOAvVI&t=5894s)
but I got an error but all is well don't know why
In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more. The goal of this video is to give you what you need to make a finished product that you can tweak, and turn into anything you like. We're going to also go over how you create a new user's account, how you store those...
error:
PS C:\Users\admin\Documents\Flask> & C:/Users/admin/AppData/Local/Programs/Python/Python39/python.exe c:/Users/admin/Documents/Flask/main.py
C:\Users\admin\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning.
warnings.warn(FSADeprecationWarning(
Traceback (most recent call last):
File "c:\Users\admin\Documents\Flask\main.py", line 3, in <module>
app = create_app()
File "c:\Users\admin\Documents\Flask\website\__init__.py", line 28, in create_app
login_manager.init_app(app)
TypeError: init_app() missing 1 required positional argument: 'app'
PS C:\Users\admin\Documents\Flask>
please help me I cant find it why is like this
Flask/main.py:
from website import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
Does aiohttp and asyncio have built in try and except to make a request again upon failure?
show init py file
I'm not sure if this is web development but what ever.
I have a site that has a lot of pictures and I want to get those pictures but they have to load first. How can I make a request that waits a little bit until the website is loaded?
is there any way for me to remove the selection of this?
So people can't select the text?
Check out this: https://www.google.com/amp/s/www.arungudelli.com/amp/tutorial/css/disable-text-selection-in-html-using-user-select-css-property/
We can use user-select property in CSS to disable text selection highlighting in HTML pages.It is not a standard feature, but available in all modern browsers except IE 9 & before.
That's what we all want to know
Depending on the browser you need to support, this might work for you
https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading
me too
How do I make a dependant drop down list for the admin panel
For eg, when the continent drop down is selected, only countries from that continent show up
Thank you, it works flawlessly 👍
I have a flask app that I want to use to access another server remotely. Is it best to SSH into that server or run another flask app on that server and just hit endpoints there?
Hey folks, I'm working on a Python tutorial titled "We developed a CMS web app from scratch in Python to host this Python tutorial on how to build this CMS web app"
This is trying to teach people how to build web apps in Python. To make it more fun, we developed a web app from scratch to host the tutorial, and the tutorial content is about how we build the tutorial web app. May I have some feedback on the tutorial title? I want to make it sounds like a tongue twister, but the current one might be too long... Thanks in advance!
There's a couple of ways I can think of and both require some JS.
-
On the continent select change, submit the form as is, and then reload the page with the given continent so that the countries dropdown is populated. Downside is the page reload - can be very heavy handed and UX is not great.
-
On continent select change, submit a request to some URL that can provide you a list of countries for a given continent. With the countries returned, dynamically populate them to the countries select.
Hello,
In my project I created an app that will only take care of updating the database in relation to the data received via socket. I have currently started writing code for this in views.py, although I would like to create a dedicated file for this purpose. Essentially the problem is that in the console I read the following strings:
(8180) wsgi starting up on http://0.0.0.0:5000
(8180) accepted ('127.0.0.1', 50224)
however the event handlers in views.py seem not to exist, as after connection I don't receive any message in the console.
I'm not actually able to figure out if I need to invoke something somewhere or add more in wsgi to get the event handlers in question to work.
I hope for some advice that can help me continue.
import os
import eventlet
import socketio
import eventlet
import eventlet.wsgi
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'discordwebsite.settings')
application = get_wsgi_application()
sio = socketio.Server()
application = socketio.WSGIApp(sio, application)
eventlet.wsgi.server(eventlet.listen(('', 5000)), application)
from django.shortcuts import render
import socketio
from .models import User
sio = socketio.Server()
@sio.event
def connect(sid, environ, auth):
print('connect ', sid)
@sio.event
def disconnect(sid):
print('disconnect ', sid)
where or what do people use to create website/app mockups?
Can I get a bit of help with flask-socketio?
I have an iframe that is feeding info from a text file to the client but am told using sockets would be better / more efficient.
I'm looking at the docs and I just can't translate what I've got right now to what I need.
xss attacks are only possible through setting inner html? right?
so just avoiding all inner html is safe against xss?
nope. xss attacks can happen in many, many ways. to be more specific as to what you said, dynamically adding HTML based on the user input can be an example of self-xss, or if data is loaded from a database without security validation/cleaning, can also be an example of cross-site scripting.
I'm having trouble installing kivy on my mac os
any solututions I'm on the kivy website but i can't succesfully interpret it
i want to do it the second way and i don’t mind using some js but my problem is i can’t don’t know how to make custom drop downs
what is this?
how do i link my layout to a file in my root directory for django
it is Django admin panel
https://youtu.be/UIJKdCIEXUQ?t=1935
im following this guy here
and doing what he's doing and still the alert in the bootstrap doesn't pop up
In this Python Flask Tutorial, we will be learning how to create forms and accept user input. We will also learn how to validate that user input and notify the user if the input was invalid. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
✅ Support My ...
setting a file field to "null=True" does not work
Doesn't work in what way?
well I don't know what you mean by doesn't work
blank is mostly used for forms, where null is more for the database
FileField is also a subclass of CharField so usually you should use blank instead of null, also: https://docs.djangoproject.com/en/3.2/ref/models/fields/#null
Ik I'm late to the party but
If ur using js
Then you can call the document.ready event
document.ready = function whatever()
Hello
I'd like to know if u can add notifications alert in the django admin panel for it to show like unread requests etc
Is there an equivalent in Django to Laravel Shift, where you pay a fee to have automatic version bumping to latest version
What does it do? Send a PR that updates your code?
I can't imagine that's super reliable.
I'm not aware of anything, in any case
Yes, it sends you a PR that you need to approve, it makes checks that everything works fine and bumps it.
I'm not exactly sure what you're looking for but you can customise the admin templates and have custom functionality, sure.
Bumps it in the composer.json?
But does it make code changes? e.g. if a function has been deprecated, will it update it to something that works? Or does it only bump the version?
If it's just the latter, dependabot does this for free.
I just discovered that, I don't know. I was just wondering if such tool exists
I'm not aware of anything in any case - but if it's just sending a PR with the versions bumped, github can do it for you. I'm not sure if you're using something else.
Actually looking at the package it does slightly more than just bump the version.
and there are also third party paid solutions, if you want something specific
Hmm yeah it does update code. There's nothing like that, no, and personally I wouldn't trust an automated upgrade even if the CI passes.
anyone know what is causing this error? error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/lib/python3/dist-packages/supervisor/xmlrpc.py line: 560
Forgot to activate a virtual environment?
Should i learn javascript before react or is it fine just going to react straight away?
troubling myself with the same question)
I thought to learn css first)
then javascript
then react
it looks like fundamental approach, so I go with a longer, but hopefully with better in quality path
Definitely JS first
But you don't need to learn too much JS, just the basics
Hi guys, i have a little doubt it's about the fetch function
That path is very good
You should always be able to make a site with HTML and CSS before you venture into the JS world
https://javascript.info is a great, modern way to get started with JS
how can i detect if the request is in progress or is loading it?
yup.
Django + CSS + Just Get/Post requests, and we are already having beautiful web site
I plan to go into CSS (and later into javascript) with Head First books
after finishing learning patterns with them, I can say they are awesome and really brain friendly)
So I have big hopes for their other books
the only doubt I have
thinking with reading them in online
or getting them as real books
real books are nice, can be read in a park, while relaxing from pc
anyone can help for add queue system b?
Hi, does anyone know that how to add reCAPTCHA to flask project which is working in pythonanywhere ?
Adding to the list of people who need help, can somebody please help me installing psycopg2 on windows?
I'm not getting any progress since most solutions are for linux systems
@spiral gate try using WSL
how to build a orm query where says if the model doesnt exist (object) add , but if exist then change the modified fields?
from demo.models import Person
update_values = {"name": "Alice", "age": 12, "is_manager":False}
new_values = {"name": "Bob", "age": 25, "is_manager":True}
obj, created = Person.objects.update_or_create(identifier='id',
defaults=update_values)
if created:
print(f"created {obj}")
else:
print(f"updated {obj}")
anyone here know how to web3 into the blockchain?
using python
i need help for a project im doing
In Django, I have a model for a JobOffer and it can have a 1 or more positions available for the offer. I have a table, WorkerJobOffer that link a Worker object and a JobOffer object. I need to limit the number of WorkerJobOffer objects to the number of positions available for its JobOffer object.
Should I implement that behaviour in the model, the view or the form?
how do I perfrom a upsert in django?
dddd
Hello I am working with django
the messages are not showing up after the condition is satisfied
Neither. Create a crud.py file and create a function to query and return the results. Avoid creating fat models.
I don't know what's that. Could you give me some pointers?
After thinking about it, since we always create new objects in the view after checking the form cleaned_data, I should just prevent the creation in the view and inject a ValidationError in the form saying you can't add more objects.
its....simple you have already defined the number of positions available for that offer.....just check if the number of objects in workerjoboffer does not exceed that number....you can do it in the views itself
Are you talking about inserting data?
No. About the purpose of your crud.py file and what are fat models.
Yeah, that's what makes sense to me so far.
I understand that. I am asking if you're talking about limiting the amount of related fields they can add (many-to-many, etc). Or the amount of results returned?
is anyone here knows about django ?
Limiting the number of WorkerJobOffer I can create so there can be more Workers related to an offer than there is positions avalaible.
Ahh I understand now. Ignore me on the crud file as that wouldn't work very well. Do not do this on a view as you might need to replicate it across multiple different views.
You'll want to add this functionality/check on the model itself. That way you're not repeating logic throughout your code base (or forgetting to check)
That's a very good consideration I didn't take into account. I could override internal object creation function and make it return the newly created object of None. If None is returned, it indicates me there's a problem so that I can properly handle that in the view and the form.
I would throw an exception instead. Create your own exception for it.
so that in my view I would try/catch the object creation and handle it?
Correct. That way you're sure you're always handling if something goes wrong and you cannot miss the problem.
IIRC the save() method of Model is where the stuff happens before it is included in the DB. I need to figure out what kind of error I shoudl raise
Like I said make your own! That way it's unique and not something common.
Good. I'm a bit rusty on raising custom exceptions, I'll dig back into that. Thank you for your help @jade lark it helped me a lot!
You're welcome man. Here's how you can make your own exception for example:
class InvalidJobPositionsException(BaseException):
"""
Represents that the current job offers exceeds the total positions available
"""
pass
I recommend making a exceptions.py file for each individual app in your django application.
Gotcha!!
@ember adder
You would then raise it like if a conditional check fails or passes.
if total_positions < current_jobs:
raise InvalidJobPositionsException("The provided positions is invalid")
Thanks for the refresh. I'll give this a try.
I've got a basic Flask "Hello World" setup, but apparently for production it's best to use something called "WSGI". According to the guide I'm following, I make a file called wsgi.py in my project root directory. However, I have Git in there, and that dirties things up. Should I:
- Add it to Git (maybe bad because this file could change across deployments?)
- Gitignore it
- Make the file somewhere else?
Thanks in advance!
I've implemented the check inside the object and unit tested everything. It works like a charm, thank you very much @jade lark 😄
You're welcome! Happy to help man good luck on your project!
class form_call(FlaskForm):
username=StringField('Username',validators=[DataRequired(),Length(min=5,max=25)])
email=StringField('Email',validators=[DataRequired(),Email()])
password=PasswordField('password',validators=[DataRequired(),Length(min=8)])
Password_confirmation=PasswordField('Confirmation_password',validators=[DataRequired(),EqualTo('password')])
submit=SubmitField('sign-up')
class log_in_call(form_call):
submit=SubmitField('log in')
remember=BooleanField('remember me')
logger=StringField('Username or Email',validators=[DataRequired(),EqualTo(form_call.username or form_call.email)])
the error displayed is kinda ugly for the username or email section also idk if the username or email will validate in that section idk if it's working the logic is there
check on the code idk if that might be the problem or something no ? i think that might be the thing even tho the logic is there cuz i want the logger thing to be equql to either the form_call.username or form_call.email
he might be able to either enter the email or the username so he can log in
Is the style tag part of html or css?
It's in html so you can write css
i am facing a NoReverseMatch at /app/ issue for the last 4 hours
already check my url patterns or any argument or keyword arg in urls.py
i just cant see whats wrong with the code. is there any way someone can hop on my Teletype address and take a look at the code since i have a bunch of files
thank you in advance
hey i have just finished docs of that 8 part of django https://docs.djangoproject.com/en/3.2/intro/ this one , and got an basic idea but ig im not able to make projects what should i do ?? how can i start making projects on django
https://images-na.ssl-images-amazon.com/images/I/51sB4CmErSL.jpg
People who struggle with official tutorial
can read something in addition of a more beginner friendly nature
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('template.html')
if __name__ == '__main__':
app.run(debug=True)
it says template not found BUT IT IS THERE
help me
what is the structure of your directory
no bro i dont struggle with with docs the thing i am struggling is i have done those 8 parts now what , how can i start making projects
ik good at flask how can i help @hybrid dome
instead of template.html make a templates folder and put that template,html in it
ohh alright
make that folder templates always it's case sensitive
just you know... find topic you find useful to make website for
and well, do everything for it
ok
can i get help related to html
yes ask
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
</body>
</html>```
dont u think the output should be hello world
it doesnt shows anything in website
it is just a tittle of page
oh got it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
Hello World
</body>
</html>
python is python.
using python would be similar to javascript a bit
oo
html is not really a real programming language
hardly can be compared
yes
it usually goes with
html+css+javascript
add wsgi to git, commit it, and then remote push everythng
I HIGHLY recommend using heroku -- deployment is GREAT with git and for python files.
xD, I saw people who said exactly the same, but with one extra word
"I HIGHLY don't recommend using heroku"
well if you are not developing a software on multinational level company then of course its safe
i have two models Player & Team
and i want to invite the player to the team
i can do the logic behind invitation but i have no idea how to create a unique , validate able hash/ token
<@&267628507062992896> is this allowed?
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I was talking about this guy, telling me to download cheats or smting
Can u help me out on this problem?
uuid
uuid
can you elaborate a bit?
I've only used the default django passwordauthtokengenerator
so im a bit new to tokens and stuff
idk about tutorials but this website is gold: https://ccbv.co.uk/
The best way to understand Django's class-based views is to see it in Classy CBV, so pick your version and jump in at the deep end.
thanks
it gives you the details of all the parent classes with methods and such
just grab one method like get():
and do your logic between the super() function
ok if we use super() it help us to modify that methods ?? isn't it?
how do i make my email unique in my forms , ```python
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(help_text='required', label='E-Mail')
Using super() calls its parent method and does its logic too. That means whatever the parent get method logic will also be executed
Why in forms, make them unique in models
I'll try it here as my last resort, I'm running into a problem with my django project and psycopg2 as it doesn't seem to connect properly. Psycopg2 is installed on my OS and in my django project.
self.connect()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 194, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection
connection = Database.connect(**conn_params)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\psycopg2\__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError
in my settings.py i have it connected via
how do i do that for the user table
you can just add unique=True in the field definition
yes this
where is the users model
where is the user model defined?
yes
Are you using the base django User model ?
I believe (but am not sure) that email should be unique already
yes
or did you extend the base model?
if you're using it
its the default, i havent changed anything in it since creating the project
You need to extend the base model and make the email unique
because by default only the username is unqiue
oh hm by default email can be blank right
I guess that means it doesn't have to be unique
thanks ill look into it
uhm well, if anyone has knowledge on this topic (psycopg2/django)help would be greatly appreciated!
show the whole error
are you sure Postgres is running?
yeah it is
wait a sec
i mean postgres pretty sure is running everytime i did it
but now I've been thinking about using an external python script where psycopg2 may work and connect that to the django project afterwards
i mean when i tried starting my server with the shown settings it showed this ```System check identified no issues (0 silenced).
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x04975148>
Traceback (most recent call last):
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check_migrations()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\core\management\base.py", line 442, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\executor.py", line 18, in init
self.loader = MigrationLoader(self.connection)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\loader.py", line 49, in init
self.build_graph()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\recorder.py", line 61, in applied_migrations
if self.has_table():
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\migrations\recorder.py", line 44, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 255, in cursor
return self._cursor()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 232, in cursor
self.ensure_connection()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection
self.connect()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\utils.py", line 89, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection
self.connect()
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\base\base.py", line 194, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection
connection = Database.connect(**conn_params)
File "C:\Users\Megaport\Desktop\Dev\hatemap_2\env\lib\site-packages\psycopg2_init.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError:
<a href="https://www.google.com"><img src="https://www.imagefu.com/86849983-f222-4f81-8bc3-566acefcdb56.png"/></a>```
why this doesnt shows image
HI, I have a simple problem.
I wrote this code to redirect a url to another url already provided by view. For test i used a random word like "hola/" . It successfully redirected but after changing it to "people/ " it still redirects to "hola/". I cant figure out the problem 😦
urlpatterns = [
path('', lambda request: redirect('people/', permanent=True)),
path('people/',include('people.urls')),
path('admin/', admin.site.urls),
]
here what show in browser
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/hola/
Using the URLconf defined in peopletrack.urls, Django tried these URL patterns, in this order:
people/
admin/
The current path, hola/, didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
The problem is when i request " http://127.0.0.1:8000/" it redirects to "http://127.0.0.1:8000/hola/" but i already changed hola/ to people/ but django is not redirecting to latest path
Clean your browser history a bit
<a href="https://www.google.com"><img src="https://www.imagefu.com/86849983-f222-4f81-8bc3-566acefcdb56.png"/></a>```
WHY DOESNT IT WORKS

Thanks man after some googling i found the main culprit is chrome
Picture is not available
if we will replace to cat picture
<a href="https://www.google.com"><img src="https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png"/></a>
everything is fine
because cats are cool
lmao
to be fair tho
heroku + git --> soulmates
this works!
why doesnt mine does
bad image service
show me ur views.py
<a href="https://www.google.com"><img src="https://www.imagefu.com/86849983-f222-4f81-8bc3-566acefcdb56.png"/></a>```
UHHH DOESNT WORKS
show me
can I know:
- What stack are you using
- What your working directory looks like
- How your Procfile and requirements.txt files are configured
@forest knoll ?
are you using django/flask to build your app?
Hi, I need some help,, I've hosted django website on windows server 2016,, the website is accessable with the server ip now,,,
How can I add my .com domain to this website?
is it a home server or have you deployed it on Azure or something
Amazon ec2 windows server 2016
Well first, buy a domain.
Then, add it to a list of hosts in your 'ALLOWED_HOSTS'
there should be some sort of option to configure a domain name there
can you show them to me
Yes I can
great
please don't show any credentials of course, protect your privacy as much as you can
hello
Thanks 😊
I've found the solution
I actually have to setup DNS inside AWS
Not in the server instance
oh great
Well, I have a problem
I'm trying to pop up a small flash message every time a new user is created, and i'm having some sort of template error while rendering it.
class UserCreateView(SuccessMessageMixin ,CreateView):
template_name = 'users/registration.html'
form_class = SignUpForm
success_message = "%(username) was created"
def get_success_url(self):
return '../../'
Here's my template (it's a bootrstap sample for now don't laugh cuz there's no dynamic content yet)
home.html
{% if messages %}
<ul class="messages">
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
</ul>
{% endif %}
Just showed the logic part here
It's giving me a 500 error, any idea what I should do?
reported
<@&831776746206265384> ^^
anyone?
why not use js for alert
how'd that work? details?
JS has an alert() function
If you add a script tag, you can call that
like there is a sign up button use on click on that button and use the alert function...
so how do I tell my frontend about the signed-up user?
will it be 'if request.user.username != "anonymous": `?
Plus I want to try the messages feature
plus I don't want a dialogue box
any idea why the terminal shows this error? I already installed flask in the virtual enviroment and selected it as the interpreter
here is the pipfile
@slow gazelle open terminal and type pip freeze and verify your python environement has that package
should i input that in the pipenv or normal terminal
use the vscode terminal. vscode has assigned your pyenv as 3.8.5 from what i see in your screenshot
yes its there
in the windows terminal its not there
but it should't be an issue since i'm using virtualenv right?
no, pipenv is your python virtual env and separate from your machines default python environment
