#web-development
2 messages · Page 166 of 1
i found the error now, I'm starting the app the wrong way
for me its this
hey, im trying to host a flask webapp on docker is there a hosting provider yall recommend that isnt expensive?
i'm using this one to start my app, for some reason, even i activate the pipenv shell in the terminal, that start button is not working
but when i type py app.py then it works
uninstall that code runner its annoying
im using python and selenium. My problem is that this for loop isnt running, he comes through the if loop but not continues the for loop...
for multiple_tasks in driver.find_elements_by_xpath("//div[@color='" + listed + "']"):
the weird thing is, that this is working perfectly on other loops, but not here
AWS maybe?
Digitalocean is good too
are you sure you've selected the right element?
security is BIG in django
mainly the fact that it creates so much stuff for you is insane in itself
Yeah, its weird, my code gives the hex ouput „#ff4002“ but the website wants the hex „FF4002“, it took me way to much time
i dont have a creditcard, i tried AWS, but i needed to add a creditcard
gonna check that one out thanks!
pythonanywhere.com is easy if u r a beginner.. vultr is good
pythonanywhere doesnt support docker right?
right
isn't that a good thing?
@ivory bolt good but
Can u guide me sometimes i have done docs that 8 parts
anyone interested to learn django together ??
im transitioning from frontend lets do it
small insignificant question, but does anyone know PyCharm gave this .py file a "dj" icon?
I'm assuming it has something to do with django
but I'm working on Flask...
where can i ask js questions
in one of the off-topic channels, or in a server that has JavaScript help
Here is fine
Assuming it's related to web dev
What is the purpose of a wsgi.py file for Gunicorn? Can you not just use the app.py file itself?
can someone help me with drf-yasg - Yet another Swagger generator?
guys can anyone tell me how to clone 1 website if i like theme ?
python apps decide which protocol to use depending on the file names, either as wsgi or asgi applications
asgi would be your async related stuff, while wsgi is sync, standard http
i can help
how do you need me to guide you
what all have you done
Yep
@ivory bolt i will tell what i have done from where
U tell me what to do next
How
From where and help me if i have doubt or any error plz
alright
I'm not overly experienced with django, but I generally have a knack for the
'what to do next' thing
I have learn function base view now i want to learn class base but i can't understand it
wait, so the file name is actually important? I just hand it over to Gunicorn...
alright
Super() ... Is confusing 🤣🤣 dont know about mixin ... Which should i learn first
so class based views are really good when it comes to inheritance, and there are two ways to go about them:
- Using the generic CBVs offered by django
- Creating your own
ah I feel you
there are things that you can freely write in function based views that you just can't in class based views
I realy dont get this mixin ... There are lot of stuff going on and dont know where to start..
Is it even possible to use websockets for refreshing the content of an iframe?
no I just wanted to if anyone can show how to build todo app
You can ask in off-topic
very much so
for example, you can check out my barebones site that uses a discord widget -- that itself uses async
it's mandatory to specify, at least for django in that aspect
Mixins basically let you reuse the class via inheritance
Thank bro still confuse i will try to do some stuff with it and if i get stuck i will ask you
I'm not using Django
That's why I'm confused
hey guys
can anyone clone this website -? www.faceit.com or can do same with python ?
no no
i will create my own database
i need just running script like this website
people register to my website
and they find match
I gotcha
they play on my country gameservers
Cloning faceit would probably be very hard. Maybe something like popflash would be easier
Why is the color property scratched off under the a.home selector?
yep, noticed that use of decorators!!
Are you familiar with synchronous and asynchronous code?
basically, synchronous code has to make an http request every time a resource is updated -- it will not update on it's own.
Asynchronous code keeps a TCP connection open, where the server could be constantly sending information via some pipeline of sorts -- those are your websockets.
That's why in a messaging app, or an app like discord, you don't need to refresh the page every time the app has new information for you: a message, a server invite, ANYTHING
wsgi is a standard file name that deals with synchronous code
and asgi, async
I still don't understand why it's being labelled as"Django" though.
oh. that's simple
you must have installed an extension for python web development or some icons pack
since django is more recognised
and it is MANDATORY in django to define the wsgi.py file (though that is made for you every time the project is made)
Oh... If I knew that, I probably would've started with Django 😅
No I mean you don't need to
Hi , I want to ask how can I pass the ValidationError messages from my custom validation functions to the template
look there's no such thing as one framework being superior to the other (everything > php)
Is there any point whatsoever in having a wsgi.py file for Flask and Gunicorn? Could I not just use app:app instead of wsgi:app or something?
I want to use the same design for my messages as the design from django forms validation
Well, python app packs are basically designed to see the protocol separately
could you elaborate
I want to use the same design for my custom ValidationErrors as the design which is given from django
Just to pass the message from my validation error to the frontend and to show at the same way as the django error
I can't specify more
just pass it along as context or via an api
Yes but it doesn't look at the same way as the django showing error
doesn't matter I will use HTTP message
thanks anyways
Oh!! That's just a whole lot of javascript on your end
im new to coding and want to know how to make a website
@smoky shore
step 1: make an html file named index.html and open in notepad.
step2: type hello world and save the file
step3: double click to open the file in your browser and wallah! you have a local static website
to make it more exciting, follow the django or flask install guide
then take your hello world index.html file and place it inside flask or django template directory.
From there you can configure flask or django to serve that static index.html file.
To make even more exciting you can then start adding css the actual HTML markup. Try using bootstrap css as a starting point.
@autumn hedge would u prefer django or flask
Ehhhhhh
That's not exactly best practice
You should put a tag around "hello world"
@smoky shore Flask!
Django if you want the full power of a database and many other tools, Flask for a smaller project
ok thank you
Django is a full on web framework, Flask is a microframework
i would like to do flask cause im new and want a smaller project
@calm plume the question is for a beginner and I later referred to using HTML markup in a later step
Ehh, you should still teach good practice from the start
@smoky shore Start with Flask
That's a wonderful idea
good practice is developed ... not taught
For the basics of HTML and CSS, Codecademy's courses are rather good
It's not just good practice, tags are the essence of HTML
do i install it in python?
@calm plume yes, but that doesn't help answer the question
No, HTML is a whole other language that comes with your computer
However, you would install Flask or Django
@smoky shore what are you asking to install?
how do i install
yes, Flask and Django are python packages that you will install to your local machine
@smoky shore I recommend you learn the basics of HTML and CSS first
Otherwise you'll be completely lost
I learned them from Codecademy's courses, those were good
@smoky shore you can watch videos, pay for online courses, or learn by reading and following docs..its entirely up to you
I learned by reading the docs
i would rather take the free rout
can u send some docs in dms if thats possible?
also thanks for all the help
Thanks for the info , I was just about to ask the same question, lol 😂. I will definitely use Flask for a smaller project .
Hello, I have a question there is a way to do a "contol S" in a python script? Other than with urllib.request... to save an image on a web browser
Anyone here pretty familiar with the Django ORM? I need some help.
what happened to “don’t ask to ask” 😉
Hey friends, i'm launching my MVP soon. We are testing with 1000 users. Im hosting the front and backend separately on digitial ocean. Will the 5$ droplet for both front and back end be sufficient? It's an ecommerce app
After getting a model object I want to disconnect it's connection to the db but still be able to use that objects static information from the time it queried the db. Any ideas?
HUH.
that's interesting
why do you want to do that
what do you mean by "disconnect"?
by default if everything has been loaded it won't hit the DB any more
if I understand what you mean
I want have a long running celery task
like you need to explicitly call .refresh_from_db()
But I get max connections when I run a few of those
Yeah, I do this now.
Changing to updating with redis
Pushing updates to redis then having one thing that reads from redis and updates everything as needed.
hm I'm not sure if Django will support this easily
However, I want to access everything like normal as their objects.
When does django "disconnect" an object? I do not seem to find anywhere where that is stated.
honestly
I have no idea offhand
I would have to look through the source code
but having a long-lived model instance
is probably not something that is contemplated
and...I don't think each instance holds on to one connection...?
the connection pooling should be handled by the driver
AFAIK
Like, the idea is get everything from the database and make it static and disconnected from the db. Then when I need to update the database I put something in redis and have another celery task that reads from redis to update the database.
The second part I got figured out
Well wjem I run 100 of the celery tasks the 101 gets that max connections issue.
Alright
Maybe you could just use the builtin JSON serializer on the model, store that, and immediately do a del instance?
I'm not sure what Django does on model __del__s but I'm fairly sure the DB connection will close once it's garbage collected
how do i fix this heroku error, ive tried everything and it dosent work, at=error code=H10 desc="App crashed" method=GET path="/
hiiiiiiii
I am pretty good in python and still learning django but I need to training on my skills there's a group or smth can help me?
You can ask here
So if I have that model object unless I do a refresh_from_db it is not connected to the db?
it shouldn’t
i need help
Ok, cool. I need to find exactly when it disconnects and I should be golden.
What do you need help with?
this thing keeps saying:
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 57, in on_message
options = options + db["encouragements"]
TypeError: can only concatenate list (not "ObservedList") to list
Looks like db["envouragements"] is an ObservedList. You need to turn it into a regular list to concatenate.

How can i master Django
I have readed those 8 parts but cant so something' like post req and fetching stuff
Can't get that logic
def index(request ,question_id)
n1=get_object_or_404(pk=question_id)```
im using the python auth_views.LoginView.as_view in my projects urls.py for a login, how do i make a custom view where i can pass custom variables to it
Assuming you're referring to template vars, you can subclass LoginView and override the get_context_data method to add variables to the template's context
wait then how did you create a polling app?
can I see the project you've worked on
i made a custom user model but when i try to make a superuser with my cli it does not hash it
so i cant login to my superuser account
but normally registering works
got it, thanks
Hey guys, I want to make a lucky draw in my website, First I thought that I should use random to show one random item in the list
but then I thought I should make it like after rolling this many times a probability of getting a good item should be higher
so then i thought that after rolling 9 times the tenth item should be that good item and I make it fixed
but It will become odd that every 10 times you roll the 10th item will be that item
so is there a way to add probability on items like every 10 times you draw you will get that item one time. I hope You are understanding what I am trying to say
how do i fix this error, im getting this after i created a custom user model (1146, "Table 'app.auth_user' doesn't exist")
<a class="nav-link active" aria-current="page" href="{% url /'app1:index' %}">Home</a>```
def index(request):
return render(request,'app1/index.html')```
app_name = 'app1'
urlpatterns =[
path('',views.index,name='index')```
maybe I don't know what I'm talking about but url /'app1:index' probably thinks you're trying to divide
anybody can help me for making dynamic database in using django
fixed
this was not issue 
but tq
Hey so
@app.route('/logs')
def view_logs():
contents = []
with open('logs.txt','r') as logs:
for line in logs:
contents.append([])
for item in line.split(' | '):
contents[-1].append(item)
titles = ('Entered Value','Result','IP','Browser')
return render_template('viewlog.html',
the_title = 'Logs',
the_column_titles = titles,
the_data = contents)
``` this is the piece of the code
and this is the txt file it reads from
but the problem is
{% extends 'base.html' %}
{% block body %}
<h2>{{ the_title }}</h2>
<table>
<tr>
{% for column_title in the_column_titles %}
<th>{{ column_title }}</th>
{% endfor %}
</tr>
{% for log_row in the_data %}
<tr>
{% for item in log_row %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endblock %}
``` with this html code, it does not show any table or any column
see, it is supposed to form a table, im quite sure I have passed all the variables correctly but got 0 idea why it would not work
anybody can help me for making dynamic database in using django
how can i use variables in python in a html code?
i work on django not flask, but i guess u'll have to pass
the_title = 'Logs',
the_column_titles = titles,
the_data = contents
the above variables as a dict
nvm I figured it out
programming is so tricky
one little mistype and you have to figure the whole thing out
Flask users, is there a way to make an exception and hide an html object from displaying from the main html file from which we extend our templates?
so
in here, this object ('smallest divisor of a number') and its background are in the main html file
I want to hide it in a specific html file
can you be more specific
how do i change the name of the tables so it dosent become like this in my db
Hello friends, I am building a website with Django, I decided to create a filter for my items, you can filter items like this: Item.objects.filter(type=item_type), so basically I created an url which takes a slug:item_type, and returns a JsonResponse with the items parsed as JSON.
Then I created an Ajax call in my js file and when I wanted to call the url I keep getting an error:
function filterItemType(type) {
$.ajax({
type: "GET",
data: $(this).serialize(),
url: "{% url 'boring:filter_items' type%}"
The Error:
Not Found: /boring/{% url 'boring:filter_items' type%}
[21/Jun/2021 11:32:54] "GET /boring/%7B%%20url%20'boring:filter_items'%20type%%7D HTTP/1.1" 404 6103
So basically JS is not parsing the Django {% url .... %} 😦 I have no idea how to do it in order for JS to build the route...
PS: I also tried to build the route with the type separated as -> url: "{% url 'boring:filter_items' %}" + "/"+ type;
But it's not working either, same error.
does anyone know why this produces a index out of range error?
return cursor.fetchall()[0][0]
If i were to just print the cursor.fetchall() i would get this: [('admin',)]
Do you believe it's possible to make a Colab clone?
Using Jupyter's docker stack?
Yeah that's not really possible because the template is rendered on the server side, while the JS is happening on the client side. If you want to do it you would need to hardcode the URL and add the type at the end, depending what the url should be exactly.
It might be to do with you calling fetchall() twice rather than the code itself. I think once you run fetchall() the first time, the results aren't available anymore.
I suppose models.ImageField doesn't deal with bytearrays of pngs immediately does it?
I'm not exactly sure what you mean. ImageField just stores a string with the path to the file, but it does validate that it's an image.
After experimenting I decided to put the image directly in a BYTEA field. They show up in DBeaver but if I use ImageField I can extract them like that?
When I use models in the shell, it shows a memory object
<memory at 0x7f5067ca0e80> like so
oh do you mean forms.ImageField? For validation?
No, I'm trying to show them through DRF
"creation_date": "somedate",
"img": null,
This is what happens when I use a simple serializer.
Yeah
Ah ok, I'd suggest you use BinaryField then
for your API you could have some explicit conversion function in your serializer to handle the encoding
ok but you're still using Django's models, right?
Yeah, for reception
well it should be a BinaryField.
For DRF the best thing is probably to write your own serializer field to do whatever encoding you need.
So it's a custom field just like vanilla Django?
a little different but nothing complex: https://www.django-rest-framework.org/api-guide/fields/#a-basic-custom-field
Django, API, REST, Serializer fields
you should override to_representation() and do your encoding there.
Looks quite similar indeed.
Also I've seen a guy implementing methods within the models that takes the image and creates it through PIL.Image. He imported them as a field.
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
"id",
"name",
"get_absolute_url",
"description",
"price",
"get_image",
"get_thumbnail"
)
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
slug = models.SlugField()
description = models.TextField(blank=True, null=True)
price = models.DecimalField(max_digits=6, decimal_places=2)
image = models.ImageField(upload_to='uploads/', blank=True, null=True)
thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-date_added',)
def __str__(self):
return self.name
def get_absolute_url(self):
return f'/{self.category.slug}/{self.slug}/'
def get_image(self):
if self.image:
return 'http://127.0.0.1:8000' + self.image.url
return ''
def get_thumbnail(self):
if self.thumbnail:
return 'http://127.0.0.1:8000' + self.thumbnail.url
else:
if self.image:
self.thumbnail = self.make_thumbnail(self.image)
self.save()
return 'http://127.0.0.1:8000' + self.thumbnail.url
else:
return ''
def make_thumbnail(self, image, size=(300, 200)):
img = Image.open(image)
img.convert('RGB')
img.thumbnail(size)
thumb_io = BytesIO()
img.save(thumb_io, 'JPEG', quality=85)
thumbnail = File(thumb_io, name=image.name)
return thumbnail
so what's happening here is that the image isn't saved as a bytearray, it's uploaded through django's file upload system... so the image is generated, converted to an in-memory file and then added to the image field
so the field here isn't byte array or anything, just the path to the file.
and the API is just showing the URLs, not the whole encoded image.
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\User\PycharmProjects\Johnnypricer\main.py", line 28, in decorated_function
return view_function(*args, **kwargs)
File "C:\Users\User\PycharmProjects\Johnnypricer\venv\lib\site-packages\flask_limiter\extension.py", line 702, in __inner
return obj(*a, **k)
File "C:\Users\User\PycharmProjects\Johnnypricer\main.py", line 74, in update_item
return jsonify({"success": True, "name": data['name'], "sku": sku})
TypeError: 'Response' object is not subscriptable
127.0.0.1 - - [21/Jun/2021 22:55:45] "POST //items/5703;6 HTTP/1.1" 500 -``` how to fix this error?
Ok I see. Probably because the author wants to get them with axios through his Vue frontend
Well, probably they will just be served by the webserver directly I think.
That's much more efficient that storing binary blobs in the database and streaming them out to the server, then to the user
generally you should avoid storing binary data in a database
anyone?
im following this guy and while he does this it feels like something is off like why he does it in terminal instead of the flaskblog module also shouldn't he extract that data from the template
idk
It's because the database isn't created yet.
With Flask-SQLAlchemy you have to create it manually
He didn't cover an important section from server-db interactions called migrations. You have a separate module handling each change done to your models called alembic.
In data['name'], what is data?
data is a dictionnary. jsonify interprets the JSON response as a dictionnary.
well, the issue is that data = jsonify(pricer(sku)) is a Response object which isn't subscriptable, so data['name'] is invalid.
also - pretty sure jsonify serializes the dictionary into a JSON-string instead of the other way around.
Instead of using jsonify(pricer(sku)) just use json.loads(pricer(sku))
@violet dock
can u teahch me webcoding
how do i get the value of a textbox using a button in html?
im working with python and html
TypeError: 'DefaultAdminSite' object is not callable
Got this while adding the models to django's admin part
oh nvm I forgot register
it doesnt works
what specifically?
ObjectId types are BSON
you gotta either remove the id key from the data
or you use pymongo's helper converter
del data['_id'] with this?
YEah, I realized that, although I founded a solution!!!! 😄 I basically passed the {% url '...:etc' type %} as an argument to the JS function! 🙂
that would delete the key which mongo inserts as a object id by default yes
Hi guys,
Does django provide integration with aws??
mhm seems like it's not
i did remove _id everywhere but im still getting it
Or you mean an aws bucket and such to storage files only?
show your code
and an example mongodb document
is somewhere wrong here?
return json.dumps(sku_listing) or return x == data
and is that where the error arises from
not exactly
what is the pricer function
and is sku when you send that post request 5021;6
from what i can see
mhm what is causing it?
Django question: Why, if I render a view from another view, the path does NOT change!?
Im under this path, then I make a "transaction"
oh found it
but i removed_id in x = mycol...
When the transaction finished and returns "profile_page_view" which is the view of the SAME page where Im at. the path does not changes...
I end up with this path
Shouldn't the return to "profile_page_view" reset the path?
isnt it the same thing? lol
Why this happens?
@quick cargo is something wrong here?
mmm nothing massively sticks out
how to add a if statement to check if _id exist or not?
find sku_listing['_id'] and del sku_listing['_id']
does the find works like that?
del sku_listing['_id]``` or this @quick cargo
well you could just use dict.pop("key", None) so it removes the key if it exists otherwise does nothing
so in my case it should be sku_listing.pop('_id') right?
you'll need to explicitly add the explicit None in that pop because it key errors without a default
still getting it but lesser
Pycharm
My old love
data is apparently a string
what should i do?
I mean that will require a bit more debugging on your behalf
wdym?
Do you want to return the path of (profile page view)??
Do you guys know how to serve static files with django using cyber panel?
I used the guide provided https://cyberpanel.net/blog/2019/01/10/how-to-setup-django-application-on-cyberpanel-openlitespeed/
I know when I hosted it with IIS I would need to add a virtual host and put my static files there to be served, but I don't see that option here, and the static files aren't being served
Why even when using django rest framework do most companies embed the frontend into django instead of being standalone back and front ends?
How to integrate my discord to my website??
probably less effort to know just Django than Django+Frontend framework
a small addition of javascript into django template looks less thing to learn than alternative
So if I already know a front end framework it should be fine to have them be standalone
I’m new to django so it’s weird seeing several tutorials use embedding
Almost all of the ones I’ve seen
👍 it sounds about right.
the only consideration to take when it is appropriate using SSR and CSR frontend perhaps
Django makes SSR by default
regular front end frameworks are usually CSR only
Next.js combines both types at the same time
Ahh yes I’d probably use next for Ssr
it depends on the context of the project
Thanks sir
I will prefer using CSR when possible
because it is faster and easier scalable in my opinion
but SSR sometimes is a must to have
Maybe for SEO right
yup
You sound like a full stack?
when we have a lot of dynamic data, extracted from database
nah, just learning
or more like... I am only responsible for backend
but at the moment partially responsible for front end decisions too, due to imcompetence of our front end person%
You were saying
I am wishing to learn being full stack as soon as possible though
planned already learning materials
to dive into front end)
Nice react is fun but I feel easier than backend?
for example we have web site full of tutorials
which are stored in our database
in order for search engines to index them, they should be pre rendered on the server side
with Django or with SSR front end frameworks like Next.js
and we are having like Dynamic hundreds amount of tutorials
which are made by users all the time
If those tutorials would be made only by our developers, as often as we produce commits to front end
we could manage with pre-rendering them, instead of going full SSR
it would allow us remaining in CSR way, while having server side builds only during project building into bunch of those static files
anyway to make a websocket server in python without using the async lib / an alternative lib
so... if tutorials are written by users = we should use Django or Next.js
if tutorials are written only as often as commits to front go with our developers, we can use React(with React-snap?), or Gatsbi
just recently researched this topic
Next.js is universal frontend framework though
That sort of makes sense :x though i don’t fully comprehend the part about doing CSR when commits to front by developers
Next.js can be used as SSR, as CSR with prerender or as purely CSR
in any way mixing all those three paths
universal thing to use
Next is nice
but its definitely orientated for vercel to host
not saying vercel does a bad job as a host
yeah I noticed that too
but it made geo deploying with other cloud systems more awkward than say a regular react app
its not a big issue, but it can cause issues
for example we are using react, with pre render with react-snap
we keep updated three tutorials about A,B,C stuff.
due to pre-render, when we would write 'npm run build` command
those tutorials would be compiled into bunch of html/css/js files
which will not be changed until we next time re deploy our web site
that makes updating those tutorials for search-engines not more often than we make commit in essence
Ah I understand you explain really well
Kinda killed my existing questions about CSR vs SSR with regards to SEO
generally the fact it complies to 'static' assets makes life much easier with deployment in terms of latency
things like github, cloudflare etc... all offer geodeployed static content serving
which is a bigggggg plus for user experience
SSR has it's place, if you have a page which changes often but is easy to cache e.g. it's rendered once then served hundreds / thousands of times before rendering again, it makes more sense to SSR it and stick it on a edge worker or just let cloudflare cache 90%+ of the requests
Not sure if this is relevant to the conversation but are the .xyz domains free?
no
Ahh ok
Yo dark if I know JS and react pretty well would it be hard to transition to django? I’m asking this knowing everyone learns at different pace but in general wondering about what you think transitioning to backend would be like if I already know a language and can pick up python decently fast
I know backend is trickier and there’s a ton to it
I have a year and a half in job exp only
In front end lol
Like I’m sure basic CRUD stuff and basic relationships can be learned easily and there’s even an ORM for queries
But there’s much more to backend
So ya..idk
uh. hard to say.
I mean... I am sort of in your foots on the backside of the coin at the moment.
I can say that experience in backend would be much smoother, if you are friendly with Linux
Ahah you can pick up front end easy as long as you dive into JavaScript deep
like a lot of back end things require easy navigation in Linux%
I use zsh same cli as Linux not sure if that’s what you mean
in my opinion back end person should be able doing small stuff like
installing database for himself, setting webserver like nginx, able to attach ssl certificates, or getting domain for web site on his own
later goes stuff with caching through redis/memcached, celery which goes into redis database too, ci/cd with github/gitlab/jenkins piplines
docker with its many variations, docker-compose and e.t.c
all this stuff is easier when you are in linux
I’ve done a bit of node so I know how to do simple stuff other than like redis haven’t look into that yet
But some of those sound like dev ops stuff
oh you worked with Node?
I’ve worked with micro services
that would make transition to Django much easier
But not too In depth
Node is basically backend like Django
Yeah but just the basics
anyway
i like this map
https://github.com/kamranahmedse/developer-roadmap
it makes nice goals to learn in any path
I can build api end points am familiar with some lingo
Ahh ok
I have it book marked hah
yeah, it is.
but backend skill is really highly improved with a touch of devops skill, those two skills are highly adding to each other
like frontend person could be improvied with design ui/ux
Ohh
I see
Yeah I’m not too into uiux stuff that’s why I wanna get into backend now that I’m in between jobs
That makes sense
Can I add you? Maybe we can exchange two different sides of the coin sometimes
sure 😉
So I take it your company does embedded react
embedded as in?
we are using standalone react with django rest framework, both are completely separated
react, we are using Create React App verison
perhaps if I'll be knowing both things together
I'll consider going with embedded too ;b
may be
Ahaha I know there’s some benefit to embedded
But I prefer standalone
Easier to separate the logic
Like being able to use react router instead of relying on backend
For the URL’s
well, I would go as first step for learning standalone front anyway
because it would make better dive into frontend
once I'll learn standalone, I'll consider using other ways
Nice that’s probably good to know both
I am going to start on learning frontend on the next weekends probably
on thursday going to arrive book which I plan to use getting started
Head First O'Reilly Html + CSS
- Head First O'Reilly Javascript
Haha nice dude like I said I’m in between jobs so hit me up anytime
For JS
Or React
heh, it would be probably not the super fast learning
like I am having a big queue to learn of backend + devops things%
I’m reading effective python and doing some tutorials on django
plus working at the same time
is flask being used in production?
nope, Django.
flask is nice to learn and getting started though ;b
yeah i got bored thou xD
Django is full battery included framework
a lot of things pre setup for you
a little bit... easy to get used to it%
when do you think is good for using flask? in my observation i think its good to used for simple services like firebase
Ya also a lot more magic to understand and gotta dive in the source or docs a lot haha
or still django
well, there appeared major new Flask verison, perhaps it will start going on the same pair as other async frameworks... one day
shrugs
I am not sure what for flask is useful. I did not get it tbh.
before its major upgrade it was not useful in my opinion
because any framework had some feature that made it better than flask in every way
with last major flask upgrade, perhaps it will stop being this way
then go for django 😉
I heard Fast API is useful too though
noticed often enough in job positions
quite popular to be used in commercial too
I use Flask a lot. I really like FastAPI as well. Django often is just way more magic than I want to deal with.
Yes, for example, the authors of the Cosmic Python book (https://www.cosmicpython.com/book/preface.html) say that they're using Flask at https://made.com.
but it seems that Django is more popular.
it will vary depending on the website
you can check the robots.txt file, or read the TOS of that website
if you see "are blocked/disallowed" next to "User-agents" then it's illegal
What is Class Meta used for?
class Category(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
class Meta:
ordering = ('name',)```
Ahmed Kamran's roadmaps are GOAT
i made a custom users model but the "groups" and "permissions" are not there, how do i add them
this is what i mean
how to run a function once my api server is started in flask?
Anyone here have experience using PyCharm and bootstrap grid?
Because while I can get grid to work in Codeply....even with copy/pasted html I simply CANNOT get columns to stack properly...
<div class="row">
<div class="col-lg-6">Col</div>
<div class="col-lg-6">Col</div>
</div>```
prints
col
col
no matter how wide the browser...and it's breaking my brain. Like I said, this works in Codeply...but Pycharm? Not a sign of it working. I also have```html
head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="../static/css/bootstrap-grid.css" type="text/css">
<link rel="stylesheet" href="../static/css/bootstrap.css" type="text/css">
</head>```
So I know I'm calling the stylesheets. I've been following a video tutorial and even copy/pasting this isn't working! I'm getting to the point of ditching PyCharm to be quite frank
I really need Grid to work, and Pycharm refusing to render is driving me nuts
what do yuo mean by getting this to work in PyCharm? are you using some kind of HTML previewer?
Well, Flask...but while I'm building out the page and learning Grid in Bootstrap Pycharm has a browser function
also what version of bootstrap
4.6.
I would just open the flask app in whatever browser your nomally use
I have no idea how PyCharm does web rendering
I've got the right version of css file. And I know I do because I copy/pasted css from codeply...where GRID works!
Doesn't work in Flask either!
But codeply...perfect. Copy pasted html and css files...works on Codeply. Pycharm, no dice! GRRR
open your inspector and make sure the css files are loading
Good idea...
Yes....loading
Showing css in "Styles"
Hm....bootstrip-grid.css isn't showing tho
OMG!
So, yeah....you have to make sure that bootstrap-grid is in the header
Thank you @cerulean vapor
I'd already checked for the loading css file, but missed that they separated out grid as it's own css file!
YW
!hlep
is it better to have a seperate "profiles" table that is a one to one to the users or just put everything in one table
i think its better to put profiles in a separate table and use signal to create it upon user creation
@ocean notch
https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html
thanks ill look into it
hey, anyone wanna help me in making a website?
Dm me
anyone knows how to make mcq (multiple choice questions) quiz with html?
Hello ppl, I'm pushing django website on Heroku, only one of my webpages - 'dashboard' throws Server Error 500. I checked the templates correctly according to WhiteNoise configs, set debug=False, migrated the db. Can anyone help me with this?
I suspect line 13 is probably the cause of 500 error
This tutorial is from 2016. I hope nothing much has changed
Although it must use Django v2
I think your url should look something like this:
/int:id/ right?
can you please help?
is there something I'm possibly missing out..?
I'm not entirely sure, though I guess it is
return redirect('dashboard/<int:{}>/'.format(request.user.id))
check this out
I'll get back to you with a better answer
if it was flask i would use it like this @app.route("/post/<string:slug>"
I'll just check it out, thanks a lot mate
never used flask before 😅
url is like this now, it doesn't take <int:> / reads it as a string
can I see your views.py
check out the url parameters for django in their documentation
@login_required(login_url='login')
@ninja_only
def dashboard(request, pk):
total = Project.objects.all().count()
# Completed Projects - count()
scratch_completed = Activity.objects.filter(user_id=pk).filter(topic_id=1).count()
circuits_completed = Activity.objects.filter(user_id=pk).filter(topic_id=2).count()
robotics_completed = Activity.objects.filter(user_id=pk).filter(topic_id=3).count()
lego_completed = Activity.objects.filter(user_id=pk).filter(topic_id=4).count()
typing_completed = Activity.objects.filter(user_id=pk).filter(topic_id=5).count()
data = {
'circuits_total': circuits_total,
'robotics_total': robotics_total,
'lego_total': lego_total,
'typing_total': typing_total,
'total': total,
}
return render(request, 'webpages/dashboard.html', data)
def ninja_only(view_func):
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'admin':
return redirect('scorecard')
if group == 'ninja':
return view_func(request, *args, **kwargs)
else:
return redirect('login')
return wrapper_function
can I use flask application builder (F.A.B) as admin panel for my project?
why not.
but Django admin panel would save a lot of time btw
I get this weird error, https://paste.pythondiscord.com/kedanukoto.sql dunno why
hello
Does anyone know how to get this working with A SAMACCOUNTNAME?
why don't you replace pk with just *args, **kwargs
and is there a way to change the url to uuid or something
I'll check it out and let you know in a bit
is this flask or django?
django
doesn't work - I use pk user_id=pk
@ivory bolt can we use HttpResponseRedirect instead of redirect ?
Has anybody else manipulated django-filter with DRF? Because I'm kinda lost at a filter's creation
All i want is to have options to filter on the date
i followed the docs for the phonenumbers field and imported it like this ```python
from phonenumber_field.modelfields import PhoneNumberField
but it still says ```ModuleNotFoundError: No module named 'phonenumbers'```
i installed it like this pip install django-phonenumber-field
just write - pip install phonenumbers
does anyone know how flask's url_for() works? My understanding is that it supplies the route in the function decorator after searching for a function with the name you supply to url_for() but flask/jinja keeps insisting it can't find it
You have to import it from flask first
I did
and I believe I don't actually have to
since it's supplied automatically by flask when reading templates
or something like that
Yeah you can use it in Jinja2 templates without importing it
Anyone - what would you write @ here in url(r'^dashboard/<here>') so that it accepts all positive numbers?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link href="{{url_for(send_stylesheet)}}" rel="stylesheet"/>
</head>
<body>
waow
</body>
</html>```
gives me jinja2.exceptions.UndefinedError: 'send_stylesheet' is undefined
wait
from flask import Flask, abort, redirect, render_template, request, send_file, jsonify, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template("test.html")
@app.route("/static/styles.css")
def send_stylesheet():
return send_file("static/styles.css")
if __name__ == '__main__':
app.run(debug=True)
this is the correct py file
how can jinja not find the send_stylesheet?
url_for('send_stylesheet') the argument should be a string
oh so even within django I need to denote it as a string
doesn't help
wait
mb it didn't reload because
I didn't add the auto reload parameters
same error?
nono it worked
now I need to figure out
why it didn't work in the main project even after making that adjustment
never mind you just solved my problem
I was chasing my tail on this for so long
because I transferred this from a google colab to my local environment
and was sure I'd gotten some esoteric configuration wrong
that I didn't consider the obvious
thank you <3
can I ask a follow up question?
sure
(?:dashboard)/(\d+) should work
I highly recommend https://regexr.com/ for making regex patterns
I am not trying to regex
is it correct? @opaque rivet
I am having trouble getting something from request.form
I think it's right - write some unit tests to make sure!
what's the issue?
function onDomLoaded() {
document.getElementById("filterbutton").addEventListener("click", function() {
var weekdays = [];
$("#dayfilter input:checked").each(function() {weekdays.push($(this).val())});
$.post("{{url_for('filter_map')}}" , JSON.stringify({"weekdays": weekdays}), onAjaxResponse, "html" );
});
}```
I use this code to post the values of checked checkboxes in an array
and used jquery post to send it
but it somehow seems to be the incorrect format for flask
it sends the request with the form data
but when I try to use request.form["weekdays"] I get a KeyError
is stringifying it wrong?
it sends a different error if I don't stringify it
but it has an error in either case
hmm, seems that request.form is empty because flask doesn't recognize that you submitted a form.
I'm pretty sure you could access request.data and your data will be there. Looks more like an API call than a form submit to me
so am I doing something stylistically wrong?
not sure. Have you checked if request.form is actually empty? It could be that Flask is detecting a form, but the payload is a string because you did JSON.stringify({"weekdays": weekdays}) so there are no keys to be accessed
Oh my gosh today all the channels are full
its still giving me the same error
@opaque rivet the thing is there is something in request.form
and I figured it would be empty if it wasn't recognized
lemme trying it now
are you using venv?
yes
check the type of its contents, it might be a string since you're doing JSON.stringify({"weekdays": weekdays}) @scarlet kiln
make sure its activated when you install
it is activated
do pip list in the terminal, does phonenumbers show up in the list?
yes it shows up as phonenumbers 8.12.25
maybe im importing it wrong in my models.py?
probably
i tried using the command pip install django-phonenumber-field[phonenumberslite] but it says the package does not exist
this is what's in request.form
I am not sure how to work with it
and I feel like I'm doing something wrong in terms of style
I removed stringify
let's see what happens if I put it back
i fixed it, i had to install phonenumer and django-phonenumbers
yeah, my guess was right. Your request.form payload is a string
your error lies here JSON.stringify({"weekdays": weekdays})
so you're saying I should remove stringify?
either way it doesn't seem to enter request.form correctly
or do I need to modify the js object I'm sending as the payload?
that's up to you. You can do: json.loads(request.form)['weekdays'] to convert the str into a dict
so I was sending valid json
but flask doesn't know what to do with it
because as far as it knows it's just a string
the issue is
request.form is a ImmutableMultiDict
not a string
and I'm not sure how to access what's inside the object
and I get keyerror if I try to do request.form['weekdays']
so I think I have to supply something different in the jquery post
can I index into a dict?
keyerror
yeah, supply something else in the jquery post. request.form is a ImmutableMultiDict but its contents is a string...
maybe you could do something like:
mutable_arr = [data for data in request.form]
json_string = mutable_arr[0]
data = json.loads(json_string)
if request.form is an iterable
I don't work with flask so I don't know too well
great
how do i remove the first name, lastname, and email fields from the user model
but i want to keep all the other fields like email, password and permissions
class Meta:
exclude = (first_name, last_name,)
Something like this ^ - in your models.py
does anyone know about any android app development course
this is a web dev group on a python discord 😂
yeah ikk
i just thought if by anychance anyone knew
https://developer.android.com/guide Android Getting Started looks good
ahh thanks
see asking here wasnt a bad idea
idk
mouse over it
maybe check the docs for Button. Dunno how tkinter works.
did anyone do corey schafers django series, and if yes did you like it?
ok, ill see
@ripe lodge you tried the Django docs and getting started tutorial? There's enough info on there to be a pro 💪
whats the difference of tkinter of django?
self.botao1.place(relx=2, rely=2.0)```
haha that makes way more sense. was confused about that 😂
im gonna look into it more, i feel like it's kind of overwhelming for a noob like me, i just dont understand a lot of the vocab yet xd
like html?
Yea that makes sense. I got a job using Django before I'd ever used it. I just keep re-reading the docs all the time. The Django discord really helpfull!
i just wanted my button ):
You tried this: #web-development message ?
that's awesome man! yea once you understand the basics i imagine the docs are really useful. thanks for the tip!
yes
No, it works alongside html. You use html, css, and maybe js for the frontend, and you could use django for the backend
loads of the videos are crap. Feels like they never used Django, reading the docs and making a video based on that tutorial 😂
its working but my button it disappeared
whats is "backend" ?
it was visible but then went away?
no
The part of the website that interacts with the database, does calculations, things like that
I'm not really sure how to explain it
yea ive been through a lot already, you're so right! also did the python crash course webapp project but i feel like after just following along all the steps i still dont really get the basics, i made an app but i dont actually understand what im doing.. it's always a process i guess
but i hear the corey schafer series is supposed to be good
@glacial sky https://www.tutorialspoint.com/python/tk_place.htm
Python - Tkinter place() Method - This geometry manager organizes widgets by placing them in a specific position in the parent widget.
u.u
are you sure you want relx & rely and not just x & y
That one is really good
He's a wonderful teacher
ah that's good to hear, i'll start rn. ty!
I need relx because the application will scale for the user
relx & rely are floats between 0.0 and 1.0, but you might be better to use pack or grid then placing widgets.
work, tks
honestly redirect is just so much cleaner
wouldn't recommend that
i was using (1.5 and 3.0)
Hi
i don't know if this is the right chanel, but anyways:
I have 2 apache webserver and want to redirect from the first to the second server everytime someone gets on the website. Also show some basic text so that a user can see that is was redirected to another site.
(it's nothing serious, just for fun 😄 )
f.e like this one: https://heeeeeeeey.com
but within a network and ip's (like i said, just for fun)
As super easy solution... just host in apache regular web site, which according to apache tutorials, always in www folder. Serve its any index.html
Then add simple html syntax to this index.html for delayed redirect, I think there should be one
thx 🙂 i'll try it out
Thanks
uhm one problem 😄
it works, but when it tries to reidrect, it just puts the text infront of the other which leads to a wrong adress... 😄
Is there a way around that?
I see for example flashes arou put to the wrong pages too.
oh sorry, it works now 😄
btw do you know how i can add some text (sorry i'm a complete noob at this 😄 )
Sorry I was not keen, I am replying to the wrong message
Is one of the best tutorials on Django, imho
Tho I found it easier to start with Flask... it helped me understand the necessary concepts in web development without having to start a project full of 10, 15 files that I didn't know anything about
def statement():
if a:
a=False
statement()
else:
a=True
statement()
statement()
if a:
print('Flask is better than Django')
else:
print('Flask is still better than Django')
@inland oak hello bro , i feel like i'm stuck not learning anything new or just learning same thing's im different framework's as u and many suggested me when i was Doing Flask if u wanted to go to advaned get to Django is it structured and stuff like that now i have done , 1 yt video 8:30 hrs and 8 docs and made 1 that docs project and 1 todo app from yt and what should i do , i wanted to learn how can i use react with django that api i want to learn i want to learn postgresmysql and to use it on django how can i use phpmyadmin on django stuck bruh feeling like i cant make progress
plz help
well, if you really feel like you're not making any progress, I suggest you try to build a social media app
You can try building a simplified twitter clone
how can i dont have that much knowledge
I mean, yeah you don't, but you also kind of do
You already know how to handle authentication, create models and fields
linked tables
and managing requests and urls right?
Do you know how to create an API?
See -- here it is! Try to look at the things you know and those you DON'T. In your case, I assume it's:
- Creating an API
- Writing asyncrhonous code -- using websockets or updating data real time
- Creating a frontend
I can hook you up with all the resources needed to do just that -- I also have a tutorial SPECIFICALLY for just that (react and Django twitter clone app)
I'll send it to you separately if you want @dusk portal
I suggest you try to do something you've always wanted to and RESEARCH how to do it -- it's how I learnt and I honestly think it's the best approach
see, there you go!
I'll send you whatever you need to get started tomorrow morning, so stay tuned on the server!!
Using the Django rest frameworks's serialisers is there a way to call a nested objects update and create methods?
that would let me do something like this:
class GuildSerialiser(ModelSerializer):
snowflake = IntegerField()
channels = ChannelSerialiser(many=True)
roles = RoleSerialiser(many=True)
class Meta:
model = DiscordGuild
fields = ['snowflake', 'channels', 'roles']
list_serializer_class = CreateUpdateDeleteListSerialiser
def update(self, instance, validated_data):
self.channels.update(instance.channels, validated_data["channels"])
self.roles.update(instance.roles, validated_data["roles"])```
it seems that the serialiser fields get removed when they are created
and there you can access them through self.fields.channels that doesn't work properly
um yeah
it is possible
but I cheated
I have 'cheated' as well now
I have this horrid function ```python
def create_update_deleteList_serialiser_update_substituation(model, instance, validated_data):
# Maps for 'snowflake->guild instance' and 'snowflake->guild data' item.
instance_mapping = {item.snowflake: item for item in instance.all()}
data_mapping = {item['snowflake']: item for item in validated_data}
# Perform creations and updates.
output = []
for snowflake, data in data_mapping.items():
item = instance_mapping.get(snowflake, None)
if item is None:
output.append(model.objects.create(**data))
else:
output.append(item)
# Perform deletions.
for snowflake, item in instance_mapping.items():
if snowflake not in data_mapping:
item.delete()
return output```
https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
here how to not cheat
Django, API, REST, Serializer relations
Writables Nested Serializers section
that isn't using the nested serialiser though
it is creating the nested object in the parent
link surely uses nested serializer
def create(self, validated_data):
tracks_data = validated_data.pop('tracks')
album = Album.objects.create(**validated_data)
for track_data in tracks_data:
Track.objects.create(album=album, **track_data)
return album```
where is the link?
it doesn't call the nested create
it is only using the nested serialiser for validation
because this is horrid: ```python
def create_update_delete_listserialiser_update_substituation(model, instance, validated_data):
# Maps for 'snowflake->guild instance' and 'snowflake->guild data' item.
instance_mapping = {item.snowflake: item for item in instance.all()}
data_mapping = {item['snowflake']: item for item in validated_data}
# Perform creations and updates.
output = []
for snowflake, data in data_mapping.items():
item = instance_mapping.get(snowflake, None)
if item is None:
output.append(model.objects.create(**data))
else:
for i, value in data.items():
if i == "snowflake":
continue
setattr(item, i, value)
item.save()
output.append(item)
# Perform deletions.
for snowflake, item in instance_mapping.items():
if snowflake not in data_mapping:
item.delete()
return output```
especially when this functionality is already implemented in the nested serialiser
now it is saving correctly
but I cannot access the serialiser's .data
AttributeError: Got AttributeError when attempting to get a value for field `snowflake` on serializer `GuildSerialiser`.
The serializer field might be named incorrectly and not match any attribute or key on the `NoneType` instance.
Original exception text was: 'NoneType' object has no attribute 'snowflake'.```
I failed to return the instance in a .update() function
I am trying to send an object via WebSocket and am unable to do so. I want to send an object to js WebSocket on a page
How to convert to string this object, or something what prevent to send
https://www.youtube.com/watch?v=44PvX0Yv368&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH&index=6
i couldn't get what and why he's doin so and what's that thing is doin is called cuz when i googled it with flask it gave me the application structure
In this Python Flask Tutorial, we will be learning how to restructure our application into a package rather than running from a single module. This has major benefits in terms of importing modules across our application. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Pyt...
when im calling the first module so i can use it in the second and vice versa in the vid he used main and it did work but didn't get his explanation also i googled it and people used a different method
if TYPING_CHECKING
import xxxxx or something idk
but that one ssems a bit tricky well both of those seemed tricky
viewspy def contact(request): if request.method=='POST': name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') message=request.POST.get('message') entry=Contact(name=name,email=email,phone=phone,message=message) entry.save() return render(request,'app1/contact.html') urlspy path('contact/',views.contact,name='contact')
ValueError at /contact/
The view app1.views.contact didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/contact/
Django Version: 3.2
Exception Type: ValueError
Exception Value:
The view app1.views.contact didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\essentials\python\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\essentials\python\python.exe
Python Version: 3.9.4
Python Path:
['C:\\Users\\91834\\PycharmProjects\\dj_todoapp\\TODO',
'C:\\essentials\\python\\python39.zip',
'C:\\essentials\\python\\DLLs',
'C:\\essentials\\python\\lib',
'C:\\essentials\\python',
'C:\\essentials\\python\\lib\\site-packages',
'C:\\essentials\\python\\lib\\site-packages\\win32',
'C:\\essentials\\python\\lib\\site-packages\\win32\\lib',
'C:\\essentials\\python\\lib\\site-packages\\Pythonwin']
Server time: Tue, 22 Jun 2021 17:12:33 +0000```
error
done!! working now
simple , when u see views.py i wrote return render in iteration so it was not catching it is the end then later i removed that from iteration and it got fixed
I don't see an iteration…do you mean the if statement?
ohh yea
wow k yea you didn't specify anything for a GET request so
is there any way to interact with a django database model outside the app
ex. i'd like to add some entries to the database from a separate python script
my first question is why u wanted to do that @nimble radish
cez it doesn't make any sense ;-;
Well, I'm figuring out the structure of my project right now.
I know I'll be using Django for the web app, but I'll have another part of the project (a separate Python script) that takes data from elsewhere and I need to add that to the database to be used by Django. I'm just trying to see what my options are.
I'm trying to figure out if for the separate part if I need to use actual SQL queries, and if I do, then maybe I shouldn't use the Django models at all. I'm not too sure, it's my first time using Django.
I shouldn't use the Django models at all. why
Are you reading my posts? I said I don't know what I'm doing, I'm using Django for the first time, and I'm just trying to get ideas on whats possible.
By an API, like GraphQL is a nice and simple,
or just import the models and use the django functionality
any django exp. dev?
show code and error
i was pretty good in flask
post.description= updateoriginfo.description.data #after this line where db.session.add line where is var u passing all the items
are u sure u r doing right?
tks @subtle frost I managed to finish my mini project for today , if you can give a star please
its like the db didnt receive an email value because the null value not allowed by default
so what should i do
if u dont want the email to be required
u need to provide default value for email field, like default=''
or allow the the db to store it as null, by doing null=True
also to tell the html its allowed to be blank, put blank=True
ohk
yes you can, identify your database -> create connection -> using pandas, you can read data and add to your database
you can't leave email empty OR you are using an email field right now
Hi does anyone have any idea on how to fix this error ?
at=error code=H10 desc="App crashed" method=GET path="/"
this occurs when I deploy my app
through herkou
did you specifically look at your heroku app's logs?
You should be able to get more traceback info there
So I have an async routine, that sometimes works and other times fails.
Couple of time when it failed it returned 500 status code, which means the server is temporarily down?
This async routine worked fine when it made around 600 async api requests. But now it's making around 800 async api requests. Could the increase in async calls be a problem?
probably
you may have unintentionally overloaded the server
or the service the api runs on may be overloaded bc of ur requests
also a 500 means the server went and did something weird
I can try to catch the error, put the program to sleep for 3 seconds and then retry again. Thanks!
It's moments like these I just think to myself programming is more about hacks then programming.
I felt more so this way about Frontend. Python and backend for the most part is well thought out logic with fewer "hacks".
can you elaborate on that
500 is a general "something went wrong on the server" code
some servers will return 503 in case of overload
why not make that script a Django management command?
then you can interact with the database using the ORM
ultimately it's just SQL tables so you can write raw SQL if you want, but I don't see why you'd want to
first time working with django, i've read through some documentation but im mostly learning through cs50's django lectures. i'm not sure of the full capabilities of django
okay so
i'll look into that though, thank you.
you know how you can run, for example
./manage.py makemigrations?
that's a management command
defined in Python code
that just does stuff with the Django framework loaded
you can do the same thing in your own code
so you have access to all of Django's capabilities
including the ORM, so you can work with model instances and save them etc. and it'll take care of writing to the database for you
https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/ is this what you're talking about?
Response that I get is an XML in bytes so to capture the error, I did this fast, but dumb thing:
str(response).find("HTTP Status 500")
Hey I have a question, if I know that I can create a whole website using Django, I have no experience in this library, but what I know about it that we can create websites on it, my question is, so when we inspect the web page of it we will get a python code ? Or how ?
function addStar() {
const geometry = new THREE.SphereGeometry(0.25, 24, 24)
const material = new THREE.MeshStandardMaterial({ color: 0xffffff})
const star = new THREE.Mesh(geometry, material)
const [x, y, z] = Array(3).fill().map(() => rand(50)) // random float from -n/2 -> n/2
star.position.set(x, y, z)
scene.add(star)
}
Array(200).fill().forEach(addStar)
currently messing around with three.js, but there's some weird array stuff that I'm seeing when I follow a tutorial. what does Array(200).fill() do, and how does map work?
what is the opposite of the @login_required method, i want to do it so that if the user is logged in
is_anonymous, guest_only ?
or you mean is_authenticated?
anyway, it depends on used library
i have a question about flask apscheduler. is the time get trigger once the function executed(which means it triggers the time once it executed the first line of the function) or after the function executed(which means it triggers the timer once it finished executed the last line of the function)?
you probably have an sql query issue there
I am using default sqlite 3 @trail crest
@trail crest sorry for late reply
def contact(request):
if request.method=='POST':
name=request.POST.get('name')
email=request.POST.get('email')
phone=request.POST.get('phone')
message=request.POST.get('message')
entry=Contact(name=name,email=email,phone=phone,message=message)
entry.save()
return render(request,'app1/contact.html')
```
path('contact/',views.contact,name='contact')```
class Contact(models.Model):
name=models.CharField(max_length=50)
email=models.CharField(max_length=50)
phone=models.CharField(max_length=50)
message=models.TextField()
def __str__(self):
return self.email```
@dusk portal can you explain me how to POST using forms
sure
i also learned something's in very difficult way and learned myself and some ppl helped in between , so that day i promised if anyone will ask me anything im gonna explain himm clearly and with full concepts and my 101% efforts
i followed some youtube tutorials and they all seem to use postegresql for post but i want to do it in sqlite
if you can share a project with me i could learn from it
I am getting this error,can somebody help?(django)
damn stuck at same place
bruh
r u new to django? @eternal flower i mean less then 1 month?
yes
oh u learning from where and exactly how much hrs u do daily
youtube
docs are boring
but best for concept;s
do u made any todo app? @eternal flower
todo project
I am trying to make it
ohh
but now I got this error
let's make together in vc , with vs code live share extension will be fun learning together i can help u so i will revise and u can help me
how's the plan?
good
and i can show u docs power
:D
so should we?
yea
Yes
Do the flask, django or fast-api tutorial depending on your needs.
You still need to use html, css and js for the front end . Or is that what you want to avoid
||how to get the value of previous that object have in update form for further validations of field ||
whispered quietly:
||making secret field, which stores the previous value and sending it with the next submit, along with the new value.||
an example please new to django
an example is different for different frameworks
for django
https://stackoverflow.com/questions/6862250/change-a-django-form-field-to-a-hidden-field
google hidden fields for django
https://docs.djangoproject.com/en/3.2/topics/forms/
they are described in their official wiki as well
{# Include the hidden fields #}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{# Include the visible fields #}
{% for field in form.visible_fields %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
http://www.semicolom.com/blog/add-a-hidden-field-to-a-django-form/
this is probably new enough
How to add a hidden field to a Django Form or a Django ModelForm
from django import forms
from .models import Player
class PlayerForm(forms.Form):
name = forms.CharField(widget=forms.HiddenInput())
Actually scratch it
hidden fields probably will not work for this case
better or may be it will
if it will not work, store previous values in query params or cookies or smth
storing in cookie sounds actually the easiest way
cookie can be well managed with backend
can someone help me and tell me how to get my flask app to work with my domain?
depends on what you have as your domain
is it just domain and nothing else?
a regular solution... would be getting vps server
getting ssl certificates for your domain
and deploying on the vps server, your app with attached ssl certificates
while setting in your domain provider, things to point to your VPS ip address
