#web-development
2 messages ยท Page 111 of 1
@native tide There is no real built-in way to do this unless you want to write your own template loader function. With that said however I do not see any benefit in doing something like this. Other django developers are used to this convention will be expecting it and will make things easier for the next person reading it since it is explicit.
@native tide Did you have a question?
I personally have not used it so I cannot have a very good opinion. Maybe someone else here can.
I asked a question here and all questions have been answered except mine can someone help me please
https://discordapp.com/channels/267624335836053506/366673702533988363/773641036340658246
@late gale Lets give it a try.
?
You are using crispy forms correct?
yes
using the |as_crispy_field filter right?
yes
Yeah that is the problem. If you want crispy forms to render your entire form for you then use the crispy tag. If you want to have your individual fields to organize them yourself then you need to use |as_crispy_field and pass it each field you want to display with the crispy forms css/js
Cool, no need to be sorry. Do you understand how to sort of do it now?
Yes, you could add css and js to if you want.
yea i sorted just between an open div tag and close i add the field with the crispy field with it
Yep, and ensuring you pass a field as opposed to the entire form will get rid of that pesky error you were getting.
Hey @late gale!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
No, did you post the HTML?
Where is it?
there
Could I see the error again?
Alright, so let the debugging begin.
Go ahead an comment out every single field but the first one please
you mean i comment every field and run the server and see if thats working ?
i think boundfield is in django.forms, not in django.forms.forms
i cant find find boundfield
there is no bound field in my models or forms.py in all apps lol
oh ok then forget what i said
programming is hilarious
Have you tried commenting all the fields but one?
Ok
ok i commented the whole form
and the error didnt remove
so i believe the error doesnt come from the template
wait
yea no change
so the error is not in the template file
Ok cool
@late gale your error is in your form not in template
So put it back to normal. and lets go look at your views really quick (granted the issue is probably in forms but better safe than sorry)
Shouldn't it be django.forms
@native tide ik i swear but i dont even have boundfield
look my forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1', 'password2']
# USER UPDATE FORM!!
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
#PROFILE UPDATE FORM
class ProfileUpdateForm(forms.ModelForm):
Committees = (
('IT','IT'),
('Design','Design'),
('ER','ER'),
('Design','Design'),
('Marketing','Marketing'),
('Coaching','Coaching'),
('Media','Media'),
('Branding','Branding'),
)
committee = forms.ChoiceField(choices=Committees, required=False)
class Meta:
model = Profile
fields = ['bio', 'image', 'position' ,'committee', 'achievement','awards', 'experience']
ok gonna show u my views
@login_required
def update_profile(request):
for userp in User.objects.all():
try:
u = userp.profile
except ObjectDoesNotExist:
u = Profile.objects.create(user=userp)
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
profile_form = ProfileUpdateForm(
request.POST,
request.FILES,
instance=request.user.profile,
)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('/profile')
else:
user_form = UserUpdateForm(instance=request.user)
profile_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'user_form': user_form,
'profile_form': profile_form,
'title' : 'Editting Profile'
}
return render(request, 'users/update_profile.html', context)
Views
there
thats the part where django refers to the url
and thats all the import things
from django.shortcuts import render , redirect
from django.contrib import messages
from .forms import UserRegisterForm , UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from .models import Profile
from django.core.mail import send_mail ,EmailMessage
from django.template.loader import render_to_string
from django.conf import settings
from .token_generator import activation_token
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_text
from django.contrib.auth import login, authenticate
@late gale you're using crispy forms?
yes
i hope we can fix this error
idk why this error refers to a thing that doesnt exist in my code
its like my computer wants to make an error without even know why
lol
@late gale the error is not in your code it is in crispy forms i think so
Well you would not get the error unless you used the filter tag. So I am not sure why you are still receiving the error. Try commenting out the include for the crispy filter.
ok
you case seems to be the same as this one https://stackoverflow.com/questions/64499993/why-is-django-crispy-forms-throwing-module-django-forms-forms-has-no-attribut
they fixed it by updating crispy form
are you using conda to manage your package ?
oh ok
pip install django-crispy-forms should i update it by this?
pip show django-crispy-forms to show which version you have first
do a quick pip show django and pip show django-crispy-forms
from crispy form django
django-crispy-forms supports Django 2.2, 3.0 and 3.1 with Python 3.5+. Note: Django 3.1 requires `django-crispy-forms` version 1.9 or higher.
Yeah update to 1.9.2
yeah you need to update
That should install the latest but just to be sure do pip install django-crispy-forms==1.9.2
ok
``` will update your package to latest version too btw
cool let me try now
omg
it worked
xDDDDDD
Thank you all of you
so it was that thing
stupid packages
How long have you been working on this project
Did you upgrade Django recently or something? Just seems odd this happens out of the blue.
like 5 months i believe and even more
yea i just upgraded recently
didnt believe that packages need to be updated too
lol
silly me
for development i recommend not using the latest version of your django, as latest version would sometime required other packages to update their package to support latest django version too
how to know if a package need to be updated
without getting into errors
and yea thank you as well
you could use a package manager
you too @devout coral
like pipfile
in pipenv
because everytime you update pipfile other package get updated too
can conda update them as wel
i don't used conda, i used it once and stop using it XD
i just use pipenv or poetry for packages managers XD
but most ppl seems to say
DOWNLOAD ANACONDAA
its perfect for python
and it seems its not
nothing is perfect, based on people opinions
poetry is newer, but i'm not familiar with. Pipenv is easier to use for me
just install pip env and go into a folder type pipenv shell in terminal
it will auto create virtual env for you
great let me try it now
but still better to follow pipenv document
Which version of django changes the admin page to have this side bar like this?
That is so weird. I just updated too, not used to it.
3.1 @devout coral
Granted I am going to replace my admin page soonish so I will just leave it.
i had 3.1.2 and didnt see that change
Well I have 3.1.1
Yes
You can overwrite the admin templates.
let me see
Yeah, so just go into the venv to find all the template names and pick which one's you want to override. From there in the django projects template directory you can make a folder called admin and put whatever templates you decide to override.
you can even do sick stuffs with override like creating a package like this https://github.com/otto-torino/django-baton
A cool, modern and responsive django admin application based on bootstrap 4.5.0 - https://otto-torino.github.io/django-baton - otto-torino/django-baton
Yeah there is a few packages out there to do that. However, you probably want to just have it styled to what your page normally looks like so users do not feel a disconnection when going to the admin page.
baton package has a tour
lol
and also seeing google analytics is super helpful
in admin page
it's all javascript
Also, to not violate the django license I believe you need to at minimun remove/replace the text that says Django administration.
@devout coral really? where does it mention D: ?
I renamed it
to my website name
are all these charts working or just javascript
like if a user viewed my website will these charts changes
or just a look
@devout coral do you use any cryptography for storing data in databse with django?
@gaunt marlin It does not explicitly mention it anywhere but by reading their license I get that.
@stable kite Nope
@devout coral ok because i created one
@stable kite Created a what?
you mean this ? https://pypi.org/project/django-cryptography/
@devout coral a django app that uses cryptography to store & retrive data
you mean this ? https://pypi.org/project/django-cryptography/
@gaunt marlin i have my own
@gaunt marlin https://pypi.org/project/Django-CryptographicFields
oh i also made a hash data system before, but it's for a project so i didn't make it a package
@gaunt marlin i did'nt use django-cryptography because it does'nt allow us to filter data
yeah crypting data have trouble with searching for it in database
because hash data are randomly hashed
yes but in my one you can do that also
you use key pair crypting way ?
@gaunt marlin no
or just 1 key for all data ?
or just 1 key for all data ?
@gaunt marlin yes
oh cool i would check it out
my previous system don't have the search system because i can't filter on it
my previous system don't have the search system because i can't filter on it
@gaunt marlin that's why i created my own
@gaunt marlin thanks
@gaunt marlin do you think i should make JSON &CSV field also?
because i don't think many people use it
json field i think maybe, but it's only if people use postgresql
ok
@stable kite Very cool.
@devout coral what?
The package. I responded late because I stepped away from my computer. I am at work so yeah.
ok
@stable kite suggestion maybe add a function to decrypt and encrypt data too
@gaunt marlin which string?
mistype i mean data
what data?
ok but i think you mean not to store it in database
it's just a suggestion
it's just a suggestion
@gaunt marlin ok i will think on it
So I'm making a website with Django, but later on I want to turn the same website to an app on Android
Is it possible to use the same code or..?
@vernal furnace you can use react as frontend if you want to do so
@vernal furnace because django is backend & do stuff related to server
yes react.js or react native
lol I suck at java
wait so I have to redo everything from scratch
?
ohh
So I can turn my website to an application but that will cost me performance
guys
@modest shale what type of authentication?
ya but we have different authentication method so which one?
like session based,token based, jwt based ?
session based
i don't know about flask as i use django sorry
@modest shale check this out
https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login
Ou thank you again
dudddd
im looking this btw
but i get the
internal server error
hell...
paste your error and code someone who know flask will help you
i cant paste
why?
internal server error not showing my error
just shows 'internal server error'
i must do debug
@modest shale You deployed using apache2?
what is that
You are not getting anything in your terminal?
nope
When you get the error I mean
just code
oh
im getting error at the sign up page
im entering email
name
and pass
and clicking enter
BOM
Internal server error
@modest shale check this out
https://www.digitalocean.com/community/tutorials/how-to-add-authentication-to-your-app-with-flask-login
@stable kite i writed this code
I- I dont know the error
cuz im new at the web programming
and i wanna learn authentication
@modest shale what framework youre using? or you want to choose?
Flask framework
so you need some extensions like flask_sqlalchemy(for storing the data in the database) and flaask_login(to login the user)
whats the error?
so you need some extensions like flask_sqlalchemy(for storing the data in the database) and flaask_login(to login the user)
@nimble epoch i did that
ok i got it whats the error?
ok...
getting Internal server error
:c
and i cant create any table at the database
maybe this is the problem
?
no problem, did you do something like db.create_all() command because maybe it couldnt find the database
include code please, it is guessing game
ok to make sure do a query on the use table
ok to make sure do a query on the use table
Sorry i meant User table
from project import db, create_app
db.create_all(app=create_app()) (pass the create_app result so Flask-SQLAlchemy gets the configuration.)
look at this
i writed this = db.create_all(app=create_app())
oookay -,+
๐
I am trying to save session variables from being deleted on server reboot or session close. Can I use pickle to serialize it and save to database? Bad/good idea?
@proper owl sorry havent used pickle
@nimble epoch have you ever tried to save session like that?
i just have that pickle idea, not sure what else is possible
somethin like session['username']????
more complex
what you mean cause i dont use session myself i do it using flask_login
guys !
yep?
why cant you just paste code?
@modest shale ok now in the cli type FLASK_APP=flaskappname.py
i writed
(venv) C:\Users\Cireael\Desktop\code\blog>set FLASK_APP =project
(venv) C:\Users\Cireael\Desktop\code\blog>set FLASK_DEBUG = 1
?
instead of doing this...
w-what ?
in your file where you have the app veriable type if name == 'main': app.run()
im curious
0-o
is there any free and easy use website to learn and code a website?
so find it where you have the flask app var @modest shale
ohoh, okay
is there any free and easy use website to learn and code a website?
@mental prawn like what html css javascript??
python
is there any free and easy use website to learn and code a website?
@mental prawn i was do the learn at youtube
flask or django @mental prawn ?
cuz i know the basics of python so i want to use my knowledge to do a website
flask or django @mental prawn ?
@nimble epoch not sure
flask is for beginners mostly but you can do a lot of thing with that and django is another popular one
which one is easy, free to use?
i heard that django is difficult to use
but flask is a bit easy for begginers
thank you for your help
and if you need any resources i recommend...
or
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://githu...
@modest shale fixed it?
Thanks alot
@mental prawn yw
im trying
๐ bro its just a file
my advice watch youtube first
@modest shale do you have any videos you recommend?
wait i will send u at dm
ok
thanks #_#
guyz i have question regarding django forms
can anyone help me with it
i have template with form
with two submit buttons for different purposes
both requires post data for calculation
so how do i differentiate it
@devout coral what's your opinion about this
#web-development message
I would say yes for JSON and hold out on csv until someone requests it unless you have spare time. Won't hurt to have but I do not think it is essential.
guyz i have question regarding django forms
@narrow jasper a way is to have different values for each submit button and check what the value of button is in the view.
<input type="submit" name="calc" value="add">
<input type="submit" name="calc'" value="sub">
do this and check what the value of calc is in the view @narrow jasper
how do I homehost django sites
Do I have to get an error when I open a local link
It says
dial tcp [::1]:80: connectex: No connection could be made because the target machine actively refused it.
When I open a localhost
a
https://codepen.io/Yuvaraj15x/pen/XWKBegE
i created this
any tips on integrating slack channels into a webapp
i need to build some chatrooms for some staff to communicate in
yes make seperate applications and merge them
In Flask and with flask-jwt-extended how do i get JTI of a JWT outside of the method handling that endpoint/http method? Without app.app_context it says no context, but if i do with that, i get an empty jwt ๐
Hello people I set-up a django signal following the tutorial video of Corey Schafer to create profiles when a user registered. I checked the documents too everything seems fine and development servers runes no error. But when I register a new user the signal does not create a profile model
what could be wrong
okey guys I fixed it myself add the appconfig to the settings.installed apps properly lol :7
@native tide https://flask.palletsprojects.com/en/1.1.x/cli/#watch-extra-files-with-the-reloader this is what you want?
I'll check
@tardy heron I already do app.extra_files=['./json/data.json']
but that doesn't work
so idk
me neither :]
Guys
Can I get help from here?
Please someone say yes
@native tide I can try to help maybe
@native tide Instead of asking for help or asking to ask, just like .. ask
state the problem, we'll see if we can help
yes
I don't use it anymore but yes
do you know your service is running
not angry, did I come off like that?
So, you wrote a python app running on a port of some sort (let's say 5000).
Flask? Django? Let's start there so I can help more.
Here's how ngrok works with one of those:
- I make a Flask app that listens on port 5000
- I use ngrok to do their port forwarding magic so that http://blahblahblah.ngrok.io forward internet traffic to my localhost:5000
If you don't know #1, #2 isn't forwarding anything.
sure
I'm making a collaborative note taking app. But I just want to know which would be a better idea...
On the dashboard, there is a sidebar which lists the notebooks linked with a user's account. Once they select a notebook, it will show the notes associated with that notebook.
Should these notes be rendered in the same sidebar? Or should they be rendered in an adjacent div?
I'm thinking of rendering the notes in the same sidebar, and removing the notepads once something is selected.
I think you're more concerned about design decisions. As far as im concerned this is more about technical questions
yes make seperate applications and merge them
@toxic flame was this in response to me
Django Channels:
All tutorials and blogposts always put Django with Docker and Redis. Is there a particular reason for that or is it possible to use django channels without it ?
hi guys need some help here
Briefly select two transaction handling criteria that they may want to evaluate in selecting the appropriate RDBMS, and provide a comparison of how Oracle and PostgreSQL support these features
i found some answers but not sure, the first one is ACID
A- Atomicity
C - Consistency
I - Isolation
D - Durability
the second answer is from my notes
Backup, checkpoint and recovery facilities
โDatabase log facilities
โConcurrency methods and granularity
โDeadlock resolution strategies
โAdvanced transaction management
โParallel/distributed query processing
thats the question ๐ but dont know how to compare, im not getting the answers
anyone willing to help
anyone willing to help
@civic kiln Go to #databases pls.
Is it possible to update a flask blueprint without restating the whole application?
Hi, so i am using this to make animation on button click. However the button can only be clicked once. The second time the animation doesn't appear.
Its because the clicked class is added to the button, if this is removed then it can be clicked again? How could i change it so i can achieve this?
https://codepen.io/MinzCode/pen/pogqVVX
You can always remove a class, from an element, which would fix that.
yo
is it a way to see how much percentage an action in django has taken?
and send it back to frontend?
example this is started with a put request
---->Last visit for 195506055044 remain at 2019-12-13 00:00:00+01:12, with 9.328641413095976% done
how can i get the 9.3
alright thanks
@native tide is your output like this each time?
like same format?
@native tide DRF and return JSON I guess
Hello #web-development , I got a question relating to "cursor.execute()". I think I am a little stuck over here: cur.execute("SELECT id FROM persons WHERE id LIKE (?)", (id)) I've seen a lot of examples online, where they show something with the question mark and with the percentages like: (%id) although I can't get my head around it.. Can someone please give me the right directions on what I do wrong? Thanks in advance.
(id,) ?
Hello, @mellow granite I am sorry, I don't understand your answer.
@wanton tulip It's known as a parameterised query. It's a way of pre compiling the SQL statement so that all you need to supply is the parameters. It protects from things like SQL injection too. So the ? is just a placeholder for the parameter that you will pass there. There's more to it that this but that's the basic for this channel.
Hey I think you should put a comma after the id in parantheses
Oh yes, thats what I read, because of injections and stuff. @mint folio Thanks for your wide answer.
@mellow granite But If I dont add any more, why would I need a comma? If id is the only value?
And try your query like this:
cur.execute("SELECT id FROM persons where id like ?", ('%'+id+'%',))
You add the comma because the function expects you to pass a tuple
(123) is an integer whereas (123,) is a tuple of 1 element.
This way the placeholder ? can be replaced with the first element of this tuple
aahh! Thank you very much for your example code and answer. So this would be the most secure way of using it, right?
Secure from SQL injections yes
Can you guys please let me know in what situations you would use raw SQL (like that), rather than an ORM?
I don't know why, but the ('%'+id+'%',) part looks a bit cumbersome.. Am I right? Or are there other solutions for?
@native tide If you use a mixture of Orms and raw SQL, then generally the raw SQL will be used for when you want better performance from certain queries.
SQL is just query language, to be used with databases
Will it help? It will definitely make you understand more on how they work.
Yea I guess that was what I was going for. Alright, thanks for that. I'll do some internal debating...
Tbf most orms now can write faster sql than most devs who don't actively work in it
Sure you can write raw sql to apply indexes and the likes but equally you can set that up on le orm as well if you're a orm user
@mint folio Hello, by using your example it's returning this example cur.execute("SELECT id FROM persons where id like ?", ('%'+id+'%',)) TypeError: can only concatenate str (not "int") to str What does he see as an int here?
Then your id is an integer so you must convert it to a string
Oh.. ofcourse! haha sorry..
Thank you! ๐
What is the best way to deploy a Django server?
Can u use something like blue host?
@torpid pecan Yes, blue host should work.
Am I the only one that people dont answer my questions..
I do not see your question
@native tide feel free to ask your question. It looks like you asked if someone knows a specific tech, if you have a question about web dev, feel free to ask it here.
ngrok
Do you understand on it
I mean I made a localhost link using a port, but now the link is stuck on that port forever
I want to change the link from that port
Like for example
This port contains a link, but this link is stuck on port 4444 forever
I want to change that link from the port
Hmm, I am not familiar with Ngrok, but I did find this https://stackoverflow.com/questions/36018375/how-to-change-ngroks-web-interface-port-address-not-4040
You will likely need to restart the service though.
What do you mean?
If you are already running ngrok on one port, you need to restart and change the port.
Yes, how to change it is the question
The article i sent shows how to set up a config file
Or the command is ngrok http <your port here> to run it using http on a specified port. https://ngrok.com/docs
Yes I'm following it
Or the command is
ngrok http <your port here>to run it using http on a specified port. https://ngrok.com/docs
@acoustic oyster This is not my problem, my problem is that I want to make a HTML file listen to the port
I am not familiar with ngrok, to make your html listen to a port and accept events, I would use some sort of backend, such as Express.JS or django/flask
Are you using flask?
It's actually coded in bash
I am confused. Are you trying to change the port ngrok is running on? Or you are trying to point it towards a web app you have?
I'm trying to change the port that the code port
Well, if you programmed your webserver, you should have specified what port it is listening on. Then you would run ngrok with whatever port your webserver is listening on. From what I can see from the docs.
So it's specified inside the script?
Your webapp/webserver should be listening on a specific port that you probably would have to specify, depending on what framework you may be using, that port may be automatic and may vary
Can I change the port?
You should be able to. It should depend on your webserver/app. I am not sure what stack you are using though.
Inside the script?
I am not sure.
Typically you would use environment variables and specify the port when you run your webserver.
The default ports are 80 for http and 443 for https
What are you using as a webserver?
Hmmm, I think netstat may show that. You should really be specifying in your server.
What webserver are you using?
I.e nginx, apache, gunicorn?
Well, you need to configure nginx to listen to ports 80 and 443. As well as setting up your firewall to give permissions.
It sounds like you just want to host static html, so you need to tell nginx where to find those static files and you probably need a config for them.
You would be better off following a tutorial for this.
Look, it's already listening to the port
but i need more HTML links to listen to the port too
Well, html does not "listen to a port"
Servers listen on a port to redirect traffic to html.
So in order to add html, you just need to add more html files whereever you need them
I already have them
If you already have the webserver setup and serving html where you expect it, then you just need to use "hrefs" to link to other html, or manually enter the path into the browser to see a complete website.
If you already have the webserver setup and serving html where you expect it, then you just need to use "hrefs" to link to other html, or manually enter the path into the browser to see a complete website.
@acoustic oyster But HTML Doesn't load pictures..
And stuff like that
How can I make HTML load pictures?
How I can make a localhost public?
How can I make HTML load pictures?
@native tide what do you mean HTML doesn't load pictures
@native tide what do you mean HTML doesn't load pictures
@vestal hound That's what I mean.
@native tide well, most websites use HTML to display images, so...
how are you trying to do that?
I...am not sure what you're saying
like you saved the HTML of another website?
one that exists on the Internet?
I noticed Facebook is the only website that doesn't load the pictures when you save it as .index
you said you used nghix right? did you served your static files with it ?
@narrow jasper a way is to have different values for each submit button and check what the value of button is in the view.
@near bison can you explain me that .. ping me whenever you r free
After python what should i learn for web dev? ping me wid reply
@jade salmon Web development consists of front end and back end. Python is only for backend so you will need to be familiar with front end technologies (the bare minimum is HTML and CSS), and some JavaScript would also help.
yes JS is also used alot in frontend and backend too @jade salmon
Oh, that's nice!
How can i send variable from a flutter app to python?
Just a general question, any of you django developers ever used any JS frameworks/libraries like React or Vue as front end with django?
I used alpine.js, but generally with the frameworks that require compilation you just make an API in django and serve the react/vue website as static files
So you mean, front end frameworks make api calls for any backend stuff and the api itself is written in Django
yes
Actually, I am new to Django, have been thinking of some project ideas to work on using django and had this thought if we could do, what i just asked you.
i tried to serve React spa with my django server once, the url paths of those 2 really conflicting with each other. I would just use django as an api for React SPA
hey guys, for some reason my static css file is not rendering it?
even when i loaded static
@buoyant shuttle which framework are you using ?
did you set debug=False ?
just check what it's currently being set right now, don't change it
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.
this what happened
when i set it to false,
it was true before
for some reason the css rendered, once i set it back to True
ok i see, can you post the html templates code where the css is not applied ?
just the lines with {% static '' %}
if you wrote it correct in your template it should be like this
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
make sure that all your css is in a folder name static
in the root of your project
This is my base template, my css worked but i changed the color to black no effect
oh then try to restart your server
you running with python manage.py runserver right ?
ctrl + c on the running terminal to stop the server
and run it again
@buoyant shuttle Also use ctrl f5 to reload the page
it worked when i used ctrel f5
@buoyant shuttle Also use ctrl f5 to reload the page
@nova nacelle Thanks
by bg color is back to black, just testing to see if it will render.
Yeah, it clears the browser's cache on reload.
yeah browser save previous css loaded so ctrl+f5 clear the cache
@nova nacelle Thanks
@buoyant shuttle Np
wadddupp
so this my post creating form
what I want to do is to add a submit buttons with integers to the field list
class PostCreateView(CreateView):
model = post
fields = ['title', 'content']
for example a submit buttons with the number 3 - 4 - 5 just under the content
Why would you want that?
@vernal furnace What would that do?
^^ haha
I want these to be the number of bedrooms,bathrooms etc
so when I create a search bar later on the search engine will search for these variables
I'm not sure if i'm doing it right tho
:c
Forget that method for now, and explain me what you exactly wanna do.
you can simply add a field that says no. of bedrooms in your model
can u show me how to do it
wait
All I want to do now is the beds(just one field)
bedrooms=models.CharField(max_length=2, choices=(("2","2"),("3","3"),("4","4")), null=True, blank=True)
add this to your model
and then add the field bedrooms in your view
@vernal furnace
bedrooms=models.CharField(max_length=2, choices=("2","2"),("3","3"),("4","4"), null=True, blank=True)
^
SyntaxError: positional argument follows keyword argument```
bedrooms=models.CharField(max_length=2, choices=(("2","2"),("3","3"),("4","4")), null=True, blank=True)
@vernal furnace read it properly
Dude this is so cool
Wait can I make it more user friendly?
like just buttons
This is for posting a post. It's fine... on the user's side you can add buttons as filters
Hi, im working on a project what can compare TechProducts using webscraping. I created the website using just plain html and css but i wanted to do the webscraping using bs4 because i did not know how to do this with javascript. After i did this i tried Flask for the first time so i can render my html template using render_template but when i do this the localhost "server" keeps loading, if i remove the render_template and just return text it loads instandly. ```py
from flask import Flask, redirect, url_for, render_template
app = Flask(name)
@app.route("/")
def home():
return render_template("index.html")
if name == "main":
app.run(debug=False)```This is my simple Flask code. And yes index.html is in the folder templates
I have a function that gets every filename from a directory, reads it, converts it to base64 and then returns it into an <img> tag that is served to the user, but it only returns 1 image, and not all of them, but if I have the function print every filepath, that works fine.
def getPosts():
for filename in os.listdir(image_dir):
if filename.endswith(".DS_Store"):
continue
else:
with open(os.path.join(image_dir + filename), "rb") as img_file:
image_data=(base64.b64encode(img_file.read()).decode(charmap))
image_element=("""<img src="data:image/png;base64, {}">""".format(image_data))
image_container=("""<div class="image">{}<br><p>filename: {}</p></div>""".format(image_element, filename))
return image_container```
```python
image_list=("""<div class="images">{}</div>""".format(getPosts()))```
yes I'm aware it's horribly inefficient, but for the purpose it's serving and the http.server module I used, it's what I'll have to put up with
How are svgs made ?
Hey guys I need help in Django project
I thought to develop a chat application with Django
So What front-end I can use for it
Pls help me it is my first project
How are svgs made ?
@near bison complex math
Damn
@verbal linden Are you sure ? You mean all those symbols and logos in svg out there are made with code. i don't think so
math, not code
You can't just draw ?
that's why you can rescale them without losing quality
and why you can't convert a png to an svg(?)
Because it's vector
yes
I made some simple svgs in figma. so i don't think it's just math. there must be way's to draw it or something
@native tide You need to make your chat interactive so you'll need JS. You can go old school and use plain JS or jQuery, but it's highly recommended to use a JS Framework. The most famous are Angular, Vue and React (React is the most popular).
There are 2 main solution to use Django with a JS framework : Django serves as an Restful API and the front is independant, or you can integrate the compiled JS in your Django template with the help of webpack
inkscape is the most popular one
Yeah it's a common projet but not the easier
linux
ok
then Inkspace
or check this out
what is that device you use to draw called ?
I don't think you can. it's just for static documents as far as i know
yeah
@buoyant shuttle your python file should prolly be called main.py, but also the main html file is index.html not main.html
does anyone know if you can put asp.net files on GitHub Pages?
@mortal mango are you asking about blazor, or the db connection and alll?
hi
@cold haven hi
@limber edge im using flask_sqlalchemy but i have no idea about your question but in the same site that youve posted there was a solutionmaybe thatll help
@mortal mango are you asking about blazor, or the db connection and alll?
@jolly bone just a static .aspx website
Static sites are possible, but any dynamic content is not hosted by Pages
I'll suggest you see this guide
With ASP.NET Blazor WebAssembly you can create .NET applications that run completely inside of the browser. The output of a Blazor WASM project are all static files. You can deploy these applications to various static site hosts like GitHub Pages.
Hope it is what you were looking for
hello
im trying to figure out how to pull multiple fragments into my html
basically, i have a webpage that gets updated by using mysql queries
currently i had only one section that needed to be updated
I was going to now add another section, using a different query
I thought that I could just duplicate the code, this didn't seem to work
@app.route("/")
@login_required
def staffdashboard():
connection = db_connection_content()
cursor = connection.cursor(pymysql.cursors.DictCursor)
sql_query1 = "SELECT date_format(load_date, '%m-%d-%Y') as the_date, content from notification_content order by load_date desc limit 5"
sql_query2 = "SELECT date_format(load_date, '%m-%d-%Y') as the_date, content from roll_call order by load_date desc limit 5"
cursor.execute(sql_query1)
cursor.execute(sql_query2)
data1 = cursor.fetchall()
data2 = cursor.fetchall()
try:
fragment1 = render_template_string('''
{% for item in data %}
<p class = "notification">{{ line }} </p>
<p class = "load_date">{{ item[ 'the_date' ] }} </p>
<p class = "content">{{ item[ 'content' ] }}</p>
{% endfor %}
''', data=data1)
fragment2 = render_template_string('''
{% for item in data %}
<p class = "roll_call">{{ line }} </p>
<p class = "load_date">{{ item[ 'the_date' ] }}</p>
<p class = "conent">{{ item[ 'content' ] }}</p>
{% endfor %}
''', data=data2)
return render_template("staffdashboard.xhtml", dict_to_be_passed=parse_311_sitemap(load_articles()),
fragment=[fragment1, fragment2])```
how do i refference multiple fragments in my code
fragment=[fragment1, fragment2] is this viable?
because it seems to be placing the same fragment into both divs
<section class="hero is-info welcome is-small" style="height:200px; ">
<div class="hero-body">
<div class="container">
<h1 class="title">
Hello,Expdient staff < username?? >.
</h1>
<h2 class="subtitle">
<table>
<tr>
<td>
{{ fragment|safe }}
</td>
</tr>
</table>
</h2>
</div>
</div>
</section>```
that is one section
this is the other
<div class="tile is-parent" style="height:400px;">
<article class="tile is-child notification is-warning ">
<div class="content" >
<a href="{{url_for('roll_call')}}">
<p class="title"> Roll Call </p>
</a>
<p class="subtitle"> These are the last 5 roll calls </p>
<main>
<p class="title center">Roll Call Log</p>
<div class="center" >
<h7 style ="width:95%; height:150px; overflow-y: scroll;">
<table>
<tr>
<td>
{{ fragment|safe }}
</td>
</tr>
</table>
</h7>
</article>
</div>
</main>
</div>```
umm
so just the order
testing now
so
that didnt help, but basically it's placing query 1 in both divs
maybe i need to close the cursor
the content of this cursor.execute(sql_query1) data1 = cursor.fetchall()
<section class="hero is-info welcome is-small" style="height:200px; "> <div class="hero-body"> <div class="container"> <h1 class="title"> Hello,Expdient staff < username?? >. </h1> <h2 class="subtitle"> <table> <tr> <td> {{ fragment|safe }} </td> </tr> </table> </h2> </div> </div> </section>```
gets placed here
and
<div class="tile is-parent" style="height:400px;"> <article class="tile is-child notification is-warning "> <div class="content" > <a href="{{url_for('roll_call')}}"> <p class="title"> Roll Call </p> </a> <p class="subtitle"> These are the last 5 roll calls </p> <main> <p class="title center">Roll Call Log</p> <div class="center" > <h7 style ="width:95%; height:150px; overflow-y: scroll;"> <table> <tr> <td> {{ fragment|safe }} </td> </tr> </table> </h7> </article> </div> </main> </div>```
here
the goal is to have query 1 go to the first div and query 2 go to the 2nd
yea
but idk much about fragments, idk what to even google
so idk if i can just change the name
how would you refactor it
i need to redo the whole thing tbh
i need to learn about blueprints
and
{{fragment[1] | safe}}where you want fragment2
@limber edge this worked
blueprints is nice, but really only practical for larger sites imo
@limber edge this is the direction im headed
for your database stuff
@limber edge yes i have to do a major refactor, right now im not using the orm
thank you for your help
hello
ABstraCtiยคn{Bยคx =>(bindObservable = n2sFiles{network, security, storage}) Unbยคx =>(bindObservable = i2rData{reliability, integrity, redundancy})}
Is it stupid for me to be running two backends for my website? I am using Node.JS to run the API and Flask to fetch and process data from the API
yes thats a pretty dumb idea
@reef rover your question was inactive, what happen if you run rq worker high default low ?
@granite mirage it just says listening on those queues
and you visit that path on browser, and no task got sent?
The task gets queued but the worker does not start it
hmm idk...this one is the closet to your https://github.com/rq/rq/issues/758. the last comment on there is to dequeue and enqueue again.
Seems like a bug
Does anyone have any ideas on how I could make the image on the left inherit the height of its sibling on the right using CSS grid?
stackoverflow is your best friend for those type of Qs
Just use px
like img {height:20px} and p {height: 20px} you can just use some Javascript (or Python) to change a variable.
@silk gorge Show me the snippet of how you have your html set up?
Just the parent and everything inside.
Set it in a parent div container and set children at relative height is what I would do.
Django probably
Oh.
It's a python framework
Ik,
I just think it would probably be more supported, if it's a Python framework.
What would be more supported?
there are loads of Python web frameworks
FastAPI
Sanic
Starllette
AioHTTP
Japronto
Tornado
Flask
Django
apidora
thats just a small list :P
how do you guys handle wtforms validators and inherittence
like
class PhoneSurvey(FlaskForm):
email = StringField("Email", validators=[Optional()])
terminal_number = IntegerField('Terminal number', validators=[Optional()])
#pandemic?
was_this_a_pandemic_related_call = SelectField('Was this a Pandemic related call',
choices=[('yes', 'Yes'),
('no', 'No')],
validators=[Optional()])
#pandemic topic?
what_was_the_call = SelectField('What category was this call', choices=[('',''),('get_food', 'NYC Get Food'),
('covid_test', 'COVID-19 Testing'),
('remote_learning', 'Remote Learning'),
('other', 'Other')], validators=[Optional()])
#did you resolve this call [APPLIES TO: PANDEMIC AND NON PANDEMIC]
was_the_inquiry_resolved = SelectField('Was the inquiry resolved', choices=[('yes', 'Yes'), ('no', 'No'),
('other', 'Other')], validators=[Optional()])
#were you able to
submit = SubmitField('Submit')
class PhoneResults(PhoneSurvey):
start_date = DateTimeField(label='Start Time (mm-dd-yyyy)', format='%m-%d-%Y %H:%M:%S', validators=[DataRequired()])
end_date = DateTimeField(label='End Time (mm-ddd-yyyy)', format='%m-%d-%Y %H:%M:%S', validators=[DataRequired()])```
basically i have my survey, and i have my results (which is a class i use to pull data into xls and send to user)
and as u see my results inherit from my survey
but if i put in some DataRequired() validators in my survey, i am not able to actually download the report, because well i guess PhoneResults is expecting required data that is not being input by the reports users/since in my view function this is not a field that I actually use (in the reports page)
i believe there might be some OOP principles to help with this
but i was curious if anyone had suggestions
So if you have the DataRequired validator, and even if you provide data in that field, it doesn't submit?
no so for example
the phone results class, the variables in there, those are the only things i ask from my user to input
so if i put a data required under some variables in PhoneSurvey i can't download the PhoneResults report, because I've inherited DataRequired() validators
and my end user who is trying to use PhoneResults to pull the xls report, does not actually need to input values for the PhoneSurvey, but because there are DataRequired() validators which are inherited from PhoneSurvey the xls file wont load.
i hope that makes sense
Hello
I need some help
I'm just a beginner in Python.
So beginner that I just know the syntax.
I really want to climb up fast.
I love the web dev.
How can I come from my level to yours?
I'm so bad right now that I don't even get the logics of my academic assignments.
Someone, help
I'm just stuck in tutorial purgatory and live helps
do u know html ?
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, be considered malicious or inappropriate. Do not help with ongoing exams. Do not provide or request solutions for graded assignments, although general guidance is okay.
Django: I have a user logged in, they want to enter personal info about themselves into a table in the database, they should only create and submit a max of 1 time, is that a one-to one relationship? That is not with a foreign key correct? The other tables I could use a foreign key because they can enter posts multiple times?
use a boolean field, if he create one then true, if not false
Django: I have a user logged in, they want to enter personal info about themselves into a table in the database, they should only create and submit a max of 1 time, is that a one-to one relationship? That is not with a foreign key correct? The other tables I could use a foreign key because they can enter posts multiple times?
@plucky tapir onetoone field
is python a good option for backend dev?
@vestal hound thanks. Would a one-to-one prevent the user from making another post to that table or I have to check that some other way? Through views possibly
?poll
@plucky tapir onetoone field ensures that there is only one related object
another one will not be allowed to be created
Does anyone have any ideas on how I could make the image on the left inherit the height of its sibling on the right using CSS grid?
@silk gorge is this solved?
Anyone know how to get around circular import errors?
ImportError: cannot import name 'Hospital' from partially initialized module 'app' (most likely due to a circular import) (/root/Tactical/app.py)```
If you import a module that imports the main file, it will cause a circular import error
Hmm why can't I import 2 files to each other?
Like if you have import hi in one file and in hi.py you have import main, then it will import hi, which will import main, which will import hi, and so on and this causes an error
That's why you usually have one main file with all the variables and separate files for classes
And those class files usually don't import anything from the main file
Oh I see the problem
This has happened to me a lot, so I would just say combine both files
Unless you can somehow make Hospital.py work without importing from app.py
Good Luck!
So Hospital is a class (table in SQLite) in app.py
And im trying to access it in another file
So I imported it from app. But I also use functions from the other file in app.py
So yeah I import them in each other
yep
So I should just take everything in the second file and put it into app.py
That happens to me a lot when I try to create a new file for my db.Model class when using SQL... you just have to move the other file to app.py, I can't think of another way
Good Luck with the rest of your project!
Thank you kind sir!
Hey guys what is a better framework django or flaskl?
Full Stack Web Development
If you want an industrial-scale website with great organization and multiple features...
Use Django
I want to become a full stack web developer that's why
I would recommend starting off with Flask then... if you haven't done web dev before
and is there any other framework to make a rest api
I don't know much about Rest APIs, so someone else can help you with that
But if you haven't done web dev before, I would recommend you get started with Flask
It has some cool features and works really well even though it's very simple
I know that is why i like rest api's
FastAPI is great to try too. Weโve been using that instead of Flask lately.
{% if object.auther == user %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
{% endif %}
yoo why its not working
๐ฆ
The server is working just fine, everything is working but the buttons for update and delete doesn't show
{% if object.auther == user %}
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
{% endif %}
try to get end if like this as its the normal if statement
nope
it looked like {& url &} at first but I fixed it
isnt it corey's tutorial ?
it looks very familiar to me
corey schafer
i was getting into his repo so i can see what u did wrong but u actually solved it so nice job
Why can't I send mail using gmail? I already sent mail using sendgrid, but my email is on a blacklist, so i made a gmail account to send, but it hangs. Same with my other account.
i mean sendgrid is on a blacklist
my mailbox doesn't get any mail from them ๐
but why the ide didn't tell me about it
When I added gmail to thunderbird it asked me about it on my phone. Now it doesn't ask. Is there some thing about this I dont know about. Like having to authorize an app using my credentials
Hi Again,
I added another field for my requirements to post here it is:
bedrooms = models.CharField(max_length=2, choices=(("2","2"),("3","3"),("4","4")), null=True, blank=True)
That code was in my models.py
and that one is in my views.py
class PostCreateView(LoginRequiredMixin, CreateView):
model = post
fields = ['title', 'content', 'bedrooms']
it gives me this error
OperationalError at /post/new/
table blog_post has no column named bedrooms
Request Method: POST
Request URL: http://127.0.0.1:8000/post/new/
Django Version: 3.1.2
Exception Type: OperationalError
Exception Value:
table blog_post has no column named bedrooms
Exception Location: D:\Python\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute
Python Executable: D:\Python\python.exe
Python Version: 3.9.0
Python Path:
['D:\\buybeit_project',
'D:\\Python\\python39.zip',
'D:\\Python\\DLLs',
'D:\\Python\\lib',
'D:\\Python',
'C:\\Users\\Fw admin\\AppData\\Roaming\\Python\\Python39\\site-packages',
'D:\\Python\\lib\\site-packages']
Server time: Sat, 07 Nov 2020 09:40:10 +0000
table blog_post has no column named bedrooms ๐ค
Anyone knows what to do?
I fixed it, makemigrations.
Hello guys. Im making simple website in flask. When i enter name and classroom in POST method and click submit i get error: return render_template("elo.html", ucenik=ucenik)
NameError: name 'ucenik' is not defined.
Here is main piece of code. I reckon solution is simple i just cant find it.
hi guys i am beginner i need a friends or a team that have the time and the ability to help and share mme to expand #I-need-help ๐
@agile wedge you have a scope error, ucenik is only defined in the home function
not the elo function
How do i make elo function "see" ucenik from home function?
define it outside of the function.
use a database or some basic store for the objects
@meager pecan if you have a question, feel free to ask in the appropriate channel, or see #โ๏ฝhow-to-get-help if you need some targeted help with something
can i ask a question? how old are you @agile wedge & @tribal python
since you are very pro!
i am 16 years old and learning python ana java in school but i need to expand more
@tribal python Ok ill try to implement basic database. tyvm
i am beginner!
how old are you @tribal python for having this ability of learning python and when you started learning?
wow nice
11 years
i started in 2 months
๐
but i read too much i love!!!!! team work!
OperationalError at /post/new/
table blog_post has no column named bedrooms
Request Method: POST
Request URL: http://127.0.0.1:8000/post/new/
Django Version: 3.1.2
Exception Type: OperationalError
Exception Value:
table blog_post has no column named bedrooms
Exception Location: D:\Python\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute
Python Executable: D:\Python\python.exe
Python Version: 3.9.0
Python Path:
['D:\\buybeit_project',
'D:\\Python\\python39.zip',
'D:\\Python\\DLLs',
'D:\\Python\\lib',
'D:\\Python',
'C:\\Users\\Fw admin\\AppData\\Roaming\\Python\\Python39\\site-packages',
'D:\\Python\\lib\\site-packages']
Server time: Sat, 07 Nov 2020 09:40:10 +0000
@vernal furnace make migrations in your app
I fixed it, makemigrations.
@vernal furnace oh, you did that already.
How can I use JS to get data from django backend? or a way to pass data from template to a view in django so that the view can update it and send back
@empty saffron use sterilizers
that might help i was going for the same problem and that helped me
I don't want data from db
I want it from a function
I want to pass data from user to a function in the backend and get the result and display it
Basically, the user will enter 2 fields in a form and press "Run" then it should feed that data to a function in the backend and get the results and add a row in a table
Hey guys i have a question
class UpdateProfile(LoginRequiredMixin, UpdateView):
model = Profile
template_name = "users/update_profile.html"
fields = ['user']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
profile = self.get_object()
if self.request.user == profile.user.id:
return True
else:
return False
and here is the template
Hey @late gale!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
โข If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
โข If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
is there a difference if i code on pycharm or python app it self?
and i have this error
@mental prawn nope
Pycharm will let you do a virtualenv for your project which is something cool for your package management
@mental prawn you don't mean the interactive interpreter?
what i mean is that for example if i want to make a website there is no difference if i use pycharm or some other editing apps
visual studio
no theres a lot of choises. Some have more features than others
vscode = Visual Studio Code not Visual Studio
because it's very fast and doesnt consume much ram
unlike Pycharm
though pycharm has amazing features
that vscode doesnt has
vscode has plugins, but i found pycharm easier to use. Don't know how others feel
it depends on everyone's perspective
heared pycharm first time o.o
If u are working on a big projects i would recommend pycharm
well when am coding on pycharm when i right some letters or words it pop ups some other words for example if i right pr it will show me different stuff to use
I only use vscode for websites
lol firstly i used notepad
eww
notepad ++?
nah simple ๐
idk how to use that cuz am used to pycharm
notepad?
there are really some people still use notepad and idk why
yeah

