#web-development
2 messages · Page 103 of 1
yeah everything is on it. Everything that I have on my computer
...
is that supposed to happen?
So the venv was not activated
yeah ig
so activate the venv in vs code so it uses that as the interpreter
source venv?
You could do it through the terminal or set it up so vs code automatically activates it
you need to source the activate script inside
how do I activate the script?
it might be something like source venv\Scripts\activate
oh ok
Did you not go to the link I sent?
yeah I went to the link
'source' is not recognized as an internal or external command, operable program or batch file.
pip install source?
@devout coral
how to break up sql query results in a for loop
@swift sky Did you get a QuerySet object?
try:
fragment = render_template_string('''
{% for item in data %}
{{ item[ 'load_date'] }}
{{ item[ 'content'] }}
{% endfor %}
''', data=data)```
<td>{{ fragment }}</td>
</table>```
oh ok it worked
def staffdashboard():
connection = db_connection_content()
cursor = connection.cursor(pymysql.cursors.DictCursor)
sql_query = "SELECT * FROM roll_call"
cursor.execute(sql_query)
data = cursor.fetchall()
try:
fragment = render_template_string('''
{% for item in data %}
{{ item[ 'load_date'] }}
{{ item[ 'content'] }}
{% endfor %}
''', data=data)
return render_template("staffdashboard.xhtml", dict_to_be_passed=parse_311_sitemap(load_articles()),
fragment=fragment)
finally:
cursor.close()```
what do I do now? @devout coral
nvm
it didn't create the requirements.txt file
do I have to install something for it to work?
oh wait nvm
it worked
the requirements.txt is just an empty file
do I push this to my VPS?
ok
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
Is this what's supposed to happen?
since I haven't installed anything
@devout coral
k
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
@devout coral
oh I didn't
let me do that
ModuleNotFoundError: No module named 'rest_framework'
I think I have to install djangorestframework
Yes...
does anyone know how to program in html? dm 🙂
You can ask here, user's who know the solution to your problem, will answer
@mortal mango Did it work?
@devout coral I uploaded all the files including the requirements.txt file but once I go onto my VPS and do ls, it doesn't show requirements.txt. I confirmed that it's uploaded to the VPS in filezilla, but it isn't sensing it for some reason.
Make sure you are looking in the right folder
oh nvm I was in the wrong user
I can't open my exo_api folder with my user
if I edit something with the root user, will it update for my other user?
@devout coral
oh ok
should I start my virtual environment and then install the requirements.txt?
@devout coral
I have a Flask webapp. When I use it, it works as intended, but my users are running into anIndexError: list index out of range.
I added a print command of the list in question and had the user try again. The list that was printed looks completely fine, but the user still got the IndexError.
How is it possible that users get an error, while it is working on my end?
@mortal mango yes activate the vent then install
what's the command to activate?
It should be source path_to_activate_script
Normally it is in venv/bin/activate if I am not mistaken
it's venv/Scripts/activate for me
but it says syntax error near unexpected token
there seems to be a syntax error inside the activate file
should I just create a venv like how corey shafer did?
@devout coral
no I'm deleting the venv files
Alright.
I just went into filezilla and deleted it
Ok, whatever works I guess
yeah it's still deleting lol
Probably would have been quicker to delete it on the server but too late now
yeah
@devout coral it's trying to install from pypi
it's trying to install from https://pypi.org/simple/requirements-txt
try pip install -r requirements.txt
restart apache and then test
yes
ok
is that it?
now do I go to the vps Ip address?
@devout coral
it works!!!!
after like 2 days
it works
yeah
I'm trying to set up a sub-domain but it says webserver is down.
the sub-domain is pointing to the VPS Ip Adress
this is my A record
@devout coral do you know why this is happening?
Idk
i am making a tkinter GUI app and i want to add a button that goes to a game i made in pygame, is there a way i can do that?
oop wronge channel
Hi all, I'm using django 3.1. I want to get a form where I have a dropdown list where i can select multipe items. However this is not working. Any suggestions?
# #https://docs.djangoproject.com/en/3.1/ref/forms/widgets/
# Working
# source = forms.MultipleChoiceField(
# label='Select Source',
# required=False,
# choices=SOURCES,
# widget=forms.CheckboxSelectMultiple())
source = forms.CharField(
label='Select Source',
required=False,
widget=forms.Select(choices=SOURCES)
#widget=forms.SelectMultiple(choices=SOURCES) working
#widget=forms.CheckboxSelectMultiple(choices=SOURCES) NOT WORKING >.<
)
is there much of a point reading a book on django 1.5?
but django is like 3.x, why would you read a older version?
cuz i have an old book, so i was asking if there is a point of reading it
i know that django changed a lot from then, so i guess, i should order something new
Need Guidance - for steps to be followed for developing a SNMP based Network or Element Monitoring System(NMS) for element like wifi AP's (FCAPS(fault, configuration, accounting, performance, security) model). Below are the feature I need to accommodate:
A WebBased GUI to adding the wifi AP over SNMPv2 or v3.
Monitor wifi-AP RF and other performances using wifi-AP REST API.
Saving elements statistics and other information into the database.
Alarm and Event monitoring
Presenting realtime performance graph over NMS webUI.
Configuration of device parameters.
This is the idea which I want to learn to develop, and I am having experience of Python and JS. Need support on how I can proceed further for developing such web base monitoring system using Python as I have experience on it.
@velvet lion You kind of are asking for a lot. I would first begin by breaking down all your requirements into small bite size chunks and just start implementing little by little. Or if you need a larger scope I would suggest you make a road map with all the requirements broken down into smaller sections.
could someone take a look at this issue i am facing with django ```python
extention of auth.User model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
middle_name = models.CharField(max_length=20, blank=True)
phone = models.CharField(max_length=10, blank=True)
registration form to register new users
class RegistrationForm(UserCreationForm):
# first_name = forms.CharField(max_length=20, required=True)
# last_name = forms.CharField(max_length=20, required=True)
email = forms.EmailField()
class Meta:
model = User
fields = ['first_name', 'last_name', 'email', 'username', 'password1', 'password2']
# fields = ['first_name', 'middle_name', 'last_name', 'email', 'phone', 'username', 'password1', 'password2']
form to take extra fields
class ProfileForm(forms.ModelForm):
middle_name = forms.CharField(max_length=20, required=True)
phone = forms.CharField(max_length=10, min_length=10)
class Meta:
model = Profile
fields = ['middle_name', 'phone']``` for some reason I am getting a `NOTNULL Constraint violation`
when i am tring to enter data into the form
Can you show the error please?
also no need to put ```
middle_name = forms.CharField(max_length=20, required=True)
phone = forms.CharField(max_length=10, min_length=10)
1 minute
The view home.views.register didn't return an HttpResponse object. It returned None instead.
right now this is the error
def register(request):
if request.method == 'POST':
user_form = RegistrationForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
username = user_form.cleaned_data.get('username')
user_form.save()
profile_form.save()
messages.success(request, f'Welcome { username }! Your account has been created. Sign in to continue.')
return redirect('login')
else:
messages.error(request, 'There was an error processing your form. Please try again.')
else:
user_form = RegistrationForm()
profile_form = ProfileForm()
return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form })```
Ok so show me the home.views.register view
You are not handling the error properly. There is no neeed to add the error. Just do the following instead return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form })
Inside the else for the is valid
like this ```python
def register(request):
if request.method == 'POST':
user_form = RegistrationForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
username = user_form.cleaned_data.get('username')
user_form.save()
profile_form.save()
messages.success(request, f'Welcome { username }! Your account has been created. Sign in to continue.')
return redirect('login')
else:
return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form })
else:
user_form = RegistrationForm()
profile_form = ProfileForm()
return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form })```
Yes
same
same wht?
The view home.views.register didn't return an HttpResponse object. It returned None instead.```
it should work i dont know why its None
Ok
now NOT NULL constraint failed: home_profile.user_id
for some reason [None, 'middle', '9966335544'] is getting passed to the Profile Model
auth.user table
profile
does anyone know how to set a sub-domain with cloudflare? I have an A record in my DNS pointed to my VPS IP address which I have my apache web server on. But when I search up the subdomain, I get this:
signals.py```python
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
@red pine What are you trying to do exactly?
You should probably be making a custom user instead of using the pre built django one
i want to register users with phone and middle_name
i am following CoreyMS and have extended the user model with aa Profile model
the Profile is getting created in the DB and I can see the Profile in the admin panel but the data is not getting saved in the table
Ok so that is the only part of coreys tutorial that is not great
yes struggling with it from 3 days now
even the django docs say to make a custom user EVEN if you do not need extra stuff
I need to leave here soon so I cannot help you too much but I can send you a link to the docs
for making it
for some reason the iduser that is created is not getting passed on to the FK of the profile model
thanks i will read this now
@devout coral yes I am trying to make it in small chunks, like
Fetching data from device using REST Aapi(GET/POST)
Inserting data into SQL DB tables
Accessing saved data from GUI and making it visible in raw formate or in Graphs.
Only confusion is it good to use Django framework?
@devout coral yes I am trying to make it in small chunks, like
Fetching data from device using REST Aapi(GET/POST)
Inserting data into SQL DB tables
Accessing saved data from GUI and making it visible in raw formate or in Graphs.
Only confusion is it good to use Django framework?
@velvet lion Django is pretty all-in-one, so that's nice, I guess
how do I change the port django is running on?
that's on django test server
is there a way to run it on a specific port in apache2?
@mortal mango https://ostechnix.com/how-to-change-apache-ftp-and-ssh-default-port-to-a-custom-port-part-1/
How to fix ?
@native tide wrong channel, also because your combo array only have 1 element so it can't get to index 1
I need to implement snoozing in my api i,e a user can snooze alerts for some time what is the best way to do it?
@pine bane generate an api call for that
Time is my concern
can you elaborate it?
Say a user puts the snooze on alert for 5 minutes another for 10 minutes
how to call the api endpoint after 5 minutes and 10 minutes
just send an alert to user after the time which is provided by user
heyy @stable kite sorry for the ping bro i wanted to ask something related to css grids
how can i avoid the space under 4b
i have given a grid-gap of 1em
just remove gap
whats your code?
okay
.container{
border: 1px black solid;
height: 50vh;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-gap: 1em;
}
.container > div{
background: grey;
text-align: center;
border: 1px red solid;
}
.container > div:nth-child(odd) {
background: lightgray;
}
.box1{
grid-row: 1/ all;
}
.box2{
grid-column: 2/all;
}
.box3{
grid-row: 2/all;
}
.box5{
grid-row-start: 3;
}
like i want the gap
@winter spindle ??
@winter spindle i think this will workgrid-gap: 0em,1em;?
oh okaky i will try it
tht doesnt solve the probelm
i think i should wrap them in a seperate container and do it
@stable kite
@winter spindle ya try that i don't know the prefect solution for your problem
may someone help me with this. I type something on my register page and click on submit and i get datas with post method but those datas won't be insert into my table in database
did i do something wrong?
@wanton ridge use an orm instead of raw queries its prone to sql injection
i use mariadb as database
yeah thats fine use something like sqlalchemy as orm
your code has an sql injection in it
also don't store passwords instead store their hashes
so you mean i use sqlalchemy instead of mariadb am i right?
for query on flask better use sqlalchemy orm for safety and easier to use
mariadb is a database and sqlalchemy is an orm
it does not, he is using the proper form for interpolating strings into queries afaik
sqlalchemy is just an orm, it doesn't replace your database engine
so i type import sqlalchemy right?
except the fact you are passing a set
ok let me use sqlalchemy then
that is probably a good idea
even so i just tend to avoid raw sql at all cause, because there too many security reasons
ohh yes
so what will be result of this query if I pass ' as name? @dapper tusk
you get sql injection possibility into your database XD
it will get escaped properly
he is not sanitizing data so you can never claim it is not immune to sql injection
cur.execute does that
@stable kite how will I know the time is over?
hello, can someone tell me how to integrate google authentication with my django rest api?
django-auth-all
django-allauth is much better
don't spam pls
test
@high ledge please do not just repeatedly spam test
he is not sanitizing data so you can never claim it is not immune to sql injection
@pine bane the driver will do it for you
as long as you let it, instead of using Python string interpolation
it is perfectly secure.
that is exactly the same as what a full-fledged ORM would do.
hello, I'm trying to follow this article to get id_token provided by google to work with django-allauth, but it suggests making changes in the files of the package I have installed on my system itself, I dont think that's a good idea, is there any other way I could do this instead?
https://medium.com/@gonzafirewall/google-oauth2-and-django-rest-auth-92b0d8f70575
After checking and reading a lot of issues, and explanations I found some that fits to my needs.
that is a bad tutorial if it required you to modify package code
yeah, seems like a hacky fix
@unborn dust https://www.youtube.com/watch?v=NG48CLLsb1A this one is from one the good youtuber and it's recent
In this video, I talk about how to set up Google authentication for your Django project.
https://learn.justdjango.com
☝ Get exclusive courses & become a better Django developer
New to Django Allauth? Watch this tutorial
https://youtu.be/dXZim_jgaiI
✌️ Stay in touch
Faceboo...
hmm, it is for django itself, I wanna integrate this with django-rest-framework
there's not many tutorials for this 😦
@vestal hound and @dapper tusk got it
@unborn dust sadly no, why you not using django authentication for DRF ?
u mean email and password?
I already have it, need to integrate google authentication support as well
if that then sadly you have to write your own authentication to serve that purpose
but for google login on the interface i would still go for my suggestion
#help-pear
web scraping problem
May someone explain me what scoped_session(sessionmaker(bind=engine)) does?
@wanton ridge i'm not look into it myself but it would probably work like other orm, when you request to a function of an url it will open an sql connection session to the data, after you completed with your query it will close the database connect session
for example 2 request to url at the same time, open 2 connect sessions and gather all the query from both in 1 database transaction to the database then close when it finish
ahh thanks
how do I enable access-control-allow-origin for one spesific route in flask?
Guys how would you display image from database on site?? with flask
@fickle fox get the URL of image & pass it to html & render it
Hey
So I was using websockets to transfer images and then view them with cv2 but now I want it on flask can somebody help me out. Like how I can change picture real time on flask server
hey people
can flask do things like some javascript does like
button listener?
or is it ike just backend
negative, flask is the server part of the relationship
by creating endpoints that the javascript talks to through AJAX
i pressed this button and then javascript asks flask to scrape that data once that data is scraped it comes back to javascript
so you would have something like this
post get and stuff dont work here right
const resp = await fetch('/my/route');
and your endpoint would resemble
@app.get('/my/route')
def scrape_stuff():
# do things
return data
oh so i gotta fetch
yeah, that would live in your event handler somewhere
is def a function just like javascript?
yes
the @app part is called a decorator
you can, I was just giving you an example of what your code would look like
flask has a good intro tutorial on their website that has you build a simple blog platform
https://flask.palletsprojects.com/en/1.1.x/quickstart/
no i already stared a project with static files and that
brb
hey whats up @pine yew
@vivid spear ?
so um yeah so i was saying
how did you get the app.gwt
like you are gonna fetch a thing on python right
@app.get('my/route')
whats that route
okok
there no?? app.get on there?
so um so what i am saying back again that like
for example
i made a index.html right and it has button in it and a form input
and i wrote a string on it and pressed the button
and it makes a new html page on the template
so it does something like this
how am i gonna do that?
read. the. tutorial.
does anyone know how to set up a sub-domain with django and apache2?
do you already have a subdomain?
Hey guys I need help starting to make a website
So can anyone send me a yt or post which helps me out in making a website
Pls
Oh hi
@gleaming basin Look at Django's quick start guide
K thx for the help I guess
Google it. Seriously.
I will go check it out
@pine yew If people are annoying you with silly questions how about not answering?
@gleaming basin Do you prefer written guides or videos?
Both are good
@devout coral "how about not answering" how about people do a modicum of work to help themselves. I gave them a direction and instead of doing their own work, they just keep asking for everything to be handed to them. This is a constant theme on this server
Also this is my first time making a website
@gleaming basin The django docs are really good and can help you get started. If you want something more in depth in video I can send you a link to a yt series about django.
@gleaming basin The django docs are really good and can help you get started. If you want something more in depth in video I can send you a link to a yt series about django.
@devout coral I Googled it I can't find it so I need a. Link for it
I think I got it
@pine yew I understand that might be a constant theme but you don't have to act annoyed. You have no obligation to answer.
Yeah, they will have a quick start guide.
That is probably the best yt django tutorial out there.
@devout coral oo
@devout coral bro for Mac it is pip install Django but what for window
do you already have a subdomain?
@pine yew I have a domain hosted on GitHub Pages
github pages does not host a web server. it's static pages only
github pages does not host a web server. it's static pages only
@pine yew yes I know. I have my domain on GitHub Pages but I want a subdomain that points toward my django page on my vps
Guys how to install Django on windows
I have an A record in my dns that points toward the VPS IP address but it's not working
Guys how to install Django on windows
@gleaming basin pip install django
But it doesn't work on windows
do you have python installed?
so install it
@pine yew do you know how to make a subdomain?
I tried this but it's not working
@mortal mango OK so I installed the latest version of python and now I have to go to cmd and do the pip command right?
yeah
what does it say
did you add python to the environment variables
and i installed python 3.9.0
did you add python to the environment variables
@mortal mango ?
in the installation page
yeah
i downloaded the latest version
and then you have to go through the installation wizard
and did you check install pip and add python to environment variables?
idk about that
type python --version
go into the path of the python folder
search python in the windows search bar and then click show file location
heyy
@gleaming basin It seems you did not add it to path. The best course of action is to uninstall it then re install it. While you re install ensure you click the checkbox that says add to path.
@gleaming basin I would suggest you get a grasp of python before trying to use Django. Take a look at some of that same guys tutorials.
@gleaming basin It seems you did not add it to path. The best course of action is to uninstall it then re install it. While you re install ensure you click the checkbox that says add to path.
@devout coral ok
I got it
I didn't install python
Lol @winter spindle That does not seem urgent but I can try
Can you show me the html and the css?
yeah
<div class="form-container">
<h1>Log In</h1>
<form action="">
<div>
<label for="email">Email</label>
<input type="text" id="email" class="foo" placeholder=" Email" autocomplete="off">
</div>
<div>
<label for="password">Password</label>
<input type="text" id="password" class="foo" placeholder=" Password" autocomplete="off">
</div>
<button>Log In</button>
<span class="sign-up">Don't have an Account?<a href=""><b> Sign up</b></a></span>
</form>
</div>
Lol @winter spindle That does not seem urgent but I can try
@devout coral hey i have a coompetition goin
There is your issue. Your place holder has a bunch of space
add padding to the input instead.
@winter spindle What kind of competition?
<div>
<label for="password">Password</label>
<input type="text" id="password" class="foo" placeholder=" Password" autocomplete="off">
</div>
You see all those spaces in the placeholder property?
Hi can anybody give some pointer with Flask ? I want to have a website with a form to fill then use the data to generate an image to show to the user. The catch is that the processing take 1-2 minutes (if the image has not been generated yet) and I will need a wait/polling page of some kind. What is the best/standart way to handle such case ?
@stray nexus So you want the user to not have to wait for the processing and just it happen in the back end?
i did tht only for spacein the place holder a biti
i want the cursor to move forward
not the placeholder to move backwards
@winter spindle remove the spacing then add padding. Have you tried that?
You want both to move together.
paddin is getting added to the whole contianer
@devout coral ideally have a 'processing....' page first and load the one with the result when available automatically
like i want the padding to be inside the box only but tht isnt happening
like the whole box is gettind mover
moved
this happens when iadd pading
@winter spindle What did you add the padding to?
@stray nexus You will want a pre loader then.
let me seee the css for the foo class
i have just done the padding right
Add padding to the left not the right.
@devout coral My first idea is to serve a page depending of the presence of img.png or img.png.tmp (meaning a process is generating one) and just slap an autorefresh on the waiting template
yeah wait i will try
@devout coral Nice ! thanks for the pointer ! seems like that was the name I needed 🙂
Alright
@devout coral Hello, where would I put the static HTML and CSS files for my home page?
@mortal mango Normally you want one CSS file for your entire site which you include in your base.html and then when you extend base.html for the rest of your templates it will include it.
For my projects I normally have a app called main which has anything that is general purpose stuff like the main home page, base.html and any JS that will be shared to everything.
I thought the home page is supposed to be called index.html
or is base.html and index.html just the same thing
@devout coral where do I tell apache2 where the index.html file is?
Can some one tell me why Django does not call get_prep_value() when used lookups for filtering data.
is Flask's test_client not a context manager anymore?
nevermind, just missing parentheses
For some reason after I createviews I automatically get thrown into my delete template after submitting, I'm sure Im redirecting incorrectly somewhere
user/views.py (a little messy rn but just started using generic cbv https://dpaste.org/dTG7
models https://dpaste.org/t3iy
goes from straight from users/new to users/pk/delete
yooo boi
@stable kite wdym
@devout coral I have <link rel="stylesheet" href="{% static 'css_files\index_style.css' %}"> to get the css file but it's not retriving it for some reason. It says not found. Do you know why this is happening?
Guys, i need to choose between django or flask for a project
i have worked with flask on a couple of projects, but i have not touched django yet
the project is a real time examination system with AI proctoring, i'd count that as pretty big project
what'd you guys think, should i go with django or flask
Hey I created a server on tech, coding, etc... Would you like to join?
@mortal mango Send me the static files setting in settings.py
@hollow ingot Are you going to need users to authenticate?
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
How about you apache conf. Did you set that up properly?
@mortal mango Are you using wsgi for this?
@devout coral yes
I'm testing on my computer right now
Hey I created a server on tech, coding, etc... Would you like to join?
@empty agate I am not sure that promotion like this is allowed.
@hollow ingot Then django it is lol. Their authentication system does so much that if I ever need auth I automatically use django. Unless you want to re create it all with flask.
@mortal mango static files are handled differently in production and in development.
@devout coral How's that diffrent from flask-login?
has anyone dealt with this error before redefinition of group name 'pk' as group 2; was group 1 at position 34
@mortal mango No... What you need to do is to read or watch a tutorial on django and how to set it up.
@devout coral Django is described as a framework meant for large products, why is that?
is it because its got many features preinstalled?
@hollow ingot I mean it is similar, but django has all of that included no need for other packages
@hollow ingot Django is like a batteries included type thing.
@mortal mango Both...
Would flask and django have simlar performance in case of large projects?
@plucky tapir Nope, what are you doing to cause the error?
So the only main selling point of django is its a batteries included framework?
@hollow ingot Technically flask performs slightly better since it is smaller but it is negligible performance.
@devout coral Using createview to send some input into a form. In my models I am doing ``` def get_absolute_url(self):
return reverse('users-home', kwargs={'pk': self.pk})
@hollow ingot Development would be faster with django. That is the selling point.
@devout coral The HTML works fine. It's just the CSS files aren't being found for some reason
@mortal mango Not just the css files. All your static files I am guessing.
@mortal mango How about your images, JS etc?
@plucky tapir So that reverse is the thing giving you the error? Also note that reverse does not return absolute url
Oh, Okay, Thanks a lot @devout coral . You're awesome!!
@hollow ingot YW!
I hope yall have a super great bug free day.
@mortal mango Glad you got it figured out. We live and we learn, I bet you won't be making the same mistake again.
@devout coral I believe so, getting redefinition of group name 'pk' as group 2; was group 1 at position 34
@plucky tapir Is that the full traceback?
@devout coral The html and css works fine, but the whole page is shifted left for some reason.
Do you know why?
@mortal mango It seems to me you are having some sort of css issue nothing to do with your server set up.
yeah but I just copied the code from my other website. So it should look the exact same right?
In Theory Yes.
traceback: https://dpaste.org/3TK2
What exactly are you trying to do? Can I get some context?
@devout coral inputting data into a database using createviews, then go to the details page. I looked up the pk error but I do not see much of anything about it so its worrysome
oh... I rarely use the class based views. Let me do some digging through the docs one sec
@plucky tapir Can you send me the code for the view
@vale knot Sure. I have heard that it was much simpler to use CBV initially is why i went in that direction. https://dpaste.org/jC9M
Also just from your knowledge, am I using reverse correctly if i have a url named 'users-home' and I want to redirect there? return reverse('users-home', kwargs={'pk': self.pk})
@devout coral I tried changing the width and stuff but it's just staying the same
I'm gonna push it to my VPS and see if it stays the same
I pushed the files and ran it with apache and the inspect console says this: Refused to apply style from 'https://mydomain.com/index_style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
@devout coral
@plucky tapir Are you trying to redirect them? Or just return the url?
@mortal mango Paste bin your css file
@vale knot I want to go to the details page after creating a new input path('<int:pk>', PostDetailView.as_view(), name='users-home'),
@plucky tapir Use redirect instead of reverse. Reverse simply will return the url where redirect will actually return an http respone
@devout coral #web-development message
@mortal mango Your css file has some issues.
oh
Also, remove all of the comments and see if you get the right result as well.
ok
Hey, can I ask someone that knows Django really well to help me at private chat? As I don't really want to interrupt their chat. Thanks!
@pulsar hinge I can help you out here but I am not sure if I qualify.
Also, remove all of the comments and see if you get the right result as well.
@devout coral still the same indentation thingy. The whole page is shifted left.
where are the issues in the code?
@mortal mango Is the css file being loaded now? Or still the same error?
let me upload it onto my vps
yeah it's not working
same error in the inspect console
Line 91, 226. Also, what are you doing in line 31?
it's my brothers code so idk
@mortal mango Did you remove the comments?
yeah
after you fixed it push it to github so I can check it or paste bin it
@mortal mango Check line 90, 166, 225. Seems like those are errors.
Okay.
I'm creating ecommerce site, and i'm trying to handle cart view so that it can render items in a table that this user has added to cart. Adding is done but items are not rendering. Either I'm getting(objects.get method) 'Order' object is not iterable or it just doesn't show at all (objects.filter method). I'm looping through them at my cart. He is views.py - cart function
try: # Using try/except here, as it was meant to work well with .get()
context = {
'items': Order.objects.filter(user=request.user, ordered=False)
}
return render(request, 'cart.html', context=context)
except ObjectDoesNotExist:
messages.error(request, 'You do not have an active order')
return redirect('/')```
cart.html
```<tr>
{% for item in items %}
<td>{{ forloop.counter }}</td>
<td>{{ item.title }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.price }}</td>
{% endfor %}
</tr>```
And whole models.py as i'm inheriting classes.
https://paste.pythondiscord.com/ikoloxulur.py
@mortal mango Check line 90, 166, 225. Seems like those are errors.
@devout coral oh ok. Do you know what to fix? I don't know HTML and CSS. That's all my brother.
Line 90 seems like there is an extra "Z" just remove it. Line 166 just has em you either need to delete the line or specify how many em's.Line 225, I do not think SmokeyWhite is a color.
@pulsar hinge It looks like your query is returning only one item and you are expecting a query set.
@mortal mango I really do not think you have set up your server properly. Reasons why I keep suggesting to just develop in your local machine then later push it all up once you are done.
yeah that's what I was doing but you said the development and production are different
so I would have to change it anyway once I go into production right?
I'm gonna look into my .conf file
@mortal mango Ah.... yes they are different but you only have to add three lines to ensure your static files are working in development and then in production all you need to do is add the static route to your conf file and you are done.
@pulsar hinge It looks like your query is returning only one item and you are expecting a query set.
@devout coral Isn't filter supposed to get me all filtered objects, and .get get just one? I saw that i'm getting one item as well, coz my forloop.counter is only rendering 1, even though i'm having 2 different items at admin, but all other cells are blank.
Just finish the entire project in development first. You are running into issues now that are hindering your ability to develop.
@devout coral it worked!!! I had the wrong path in my .conf file
@pulsar hinge Oh wait yeah, you are using filter. Do me a favor. Get rid of the useless try except and then add a print(type(Order.objects.filter(user=request.user, ordered=False))) before the return
@mortal mango Cool
<class 'django.db.models.query.QuerySet'>
<class 'ecommerce.models.Order'> And this with .get, just to compare or smth
@pulsar hinge Yeah you want the top thing to ensure you always can use the for loop
Is it working now? Or what is the error you get now?
I'm getting blank table,
{% for item in items %}
<td>{{ forloop.counter }}</td>
<td>{{ item.title }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.price }}</td>
{% endfor %}
</tr>```
Is not rendering anything
Just the hardcoded '$' and {{ forloop.counter }}
So no error now that is good. Now do a print(Order.objects.filter(user=request.user, ordered=False))
<QuerySet [<Order: admin>]>
And in admin panel, I'm having 2 different items in Orders assigned to admin
alright do this in your template
<tr>
{% for item in items %}
<td>{{ item }}</td>
{% endfor %}
</tr>
Getting 'admin' in my cell
Ok, show me the admin model please
My apologies the Order model
https://paste.pythondiscord.com/ikoloxulur.py It's in here as I'm having only 4 models total
There is your problem item.title is not a field in the order object
I think what you are trying to do is pass a queryset with the items not the order.
Yea, I thought it's going to look at items, then go to OrderItem as I'm inheriting it in ManyToManyField. How am I supposed to pass it then?
Yea, it will take everything
What you can do is make a list of of the items for the order in the view.
Do you have any idea on implementing it?
I think you need to change your stuff a bit. You might want to change it so that Items has a property called order and that is the M2M field. This way you could just query items for a specific order.
If that makes sense
# index class based view
class IndexView(ListView):
model = Question
context_object_name = 'posts'
template_name = 'home/index.html'
def login(request):
context = { 'title' : 'Sign In' }
return render(request, 'home/signin.html', context)``` How do I pass `title` like in the `login` view to my `IndexView` which is a class based view ?
I think you need to change your stuff a bit. You might want to change it so that Items has a property called order and that is the M2M field. This way you could just query items for a specific order.
@devout coral Hard to do, or just for me as im also inheriting Item at OrderItem, so i'm getting variable undefined error
you need to override the get_context_data method
thanks i will check the docs
also if i need to access the request object, can i do that within a template using class based views ?
You should be able be able to access the request var in the template with {{ request }}
i tried {% for i in request %} but it did not do any thing
did i do it right ?
i was reading the docs and i want to access the IP address that is a meta data exists in the request object
HttpRequest.META REMOTE_ADDR
@marsh canyon so i tired python {% for i in request.META %} <p>i</p> {% endfor %} it is printing a bunch of i s
it should be {{ i }}
cool
bleh
i am getting a The method is not allowed for the requested URL.
i have a survey form, and that's what happens when I hit submit
I suspect it's because of the way I have/don't have the submit button coded
<form method="POST" action="/">
<div class="form-field space"> {{ form.terminal_number.label(class="is-medium is-fullwidth")}}: {{ form.terminal_number(class="field" )}}
</div>.
<!-- start of the survey -->
<div class="form-field space"> {{ form.was_this_a_pandemic_related_call.label}}: {{ form.was_this_a_pandemic_related_call(class="select")}}</div>
<!-- start of the survey -->
<!--yes1 selection -->
<div id="yes1" class="form-field space" style="display: none;"> {{ form.what_was_the_call.label}}: {{ form.what_was_the_call(class="select")}}</div>
<!--yes1 selection -->
<!-- non pandemic question 2 -->
<div id="no2" class="form-field space" style="display: none;"> {{ form.was_the_inquiry_resolved.label}}: {{ form.was_the_inquiry_resolved(class="select") }}</div>
<!-- non pandemic question 2-->
<div id="yes3" class="form-field space" style="display: none;">
{{ form.was_the_inquiry_resolved.label}}: {{ form.was_the_inquiry_resolved(class="select") }}</div>
<div class="center space">
{{ form.submit(class="button is-primary is-rounded") }}
</div>
</form>```
specifically this portion here
{{ form.submit(class="button is-primary is-rounded") }}
</div>```
@devout coral My HTML and CSS is working fine but it isn't loading the images
do you know why?
I just successfully made a django environment in VSCode.
I want to learn how to hook a webscraper and collect data online, unbox the data into my own database types, and then box them to a UI of my choice.
I will do this with MVC pattern
I like how in python you can create your own microservice though venv.
@cold haven django is great but why would you need it for just a simple webscraper? even if you want a webscraper with a webinterface i personally would rather go with flask since it's a lot more lightweight
Oh ok, yeah I really love Django but I use it only for bigger projects (as it's intended to) but if you want to create a webscraper project to learn Django it also makes sense to use it
but specifically as I said, this could potentially be a big project
i'm using the webscraper to collect data from the web.
so the database could be huge potentially.
Yeah but with size wise I didn't mean the database size, I rather meant the size of overall code base
what webscraper software would you suggest I use?
Since Django allows you to better structure a big codebase rather then flask
You mean what scraper api or do you want to create your own scraping service
Never heard of that but I honestly never used a webscraping saas so far only coded one from scratch for a client
but scraping on the back end means you can actually unbox your own elements or capture them, and send them to your own UI, unlike scraping from the front-end frameworks.
I don't think there is a way with front-end frameworks to put the data in a UI
I don't really get what you want to scrape
front-end is used just for testing, but I could find a better use of data collecting on the back end.
for example, if I wanted to scrape a few databases from a few different websites.
I collect it and put it into a database
then I can send it to the browser via html
and bootstrap
I guess you can not directly scrape databases of other websites 😄
you need to connect the scraper api to a browser so the back end works as the intermediary.
But I know what you mean you want to scrape data from different websites and save it to your database and then show it in your ui
Right?
smortToday at 4:29 PM
I guess you can not directly scrape databases of other websites 😄
@ebon gust clarify?
I mean to "scrap from a databse" you would need to have database acces 😉 😄
You mean to scrap the data from the website (html)
oh no, not to hack into a database through sql injection
I mean just perform a search from search bar.
Yeah but that means you scrape it from the rendered webpage (html)
yeah
that's how it works
I know what you are getting at.
but you could use a webscraper to do sql injection on websites.
I wouldn't advise it.
Webscraper has nothing to do with sql injection since the only thing a webscraper does is scraping data from a rendered webpage
all you have to do is enterKeys into an input box and then it returns a webpage.
you can do that in browser automation
Yes but thats automation as you said and not webscraping you are precise 😉
you would enter a script into an input box and then it accesses the database and returns results.
Without using sql params in your code, you may have problems.
yeah I suppose you can reverse engineer anything. Protractor is dangerous and can be used to make BotNets
heyyy
@near ridge hi
Why was I pinged?
@near ridge Sorry mistyped
he was trying to ping me
can you look tht link and tell how is it ?
Box was writing about webscraping and then he started talking about sql injection no idea why 😄
@ebon gust
That link seems incredibly sketchy
@winter spindle sorry but i don't like to click on suspicious links
hey mahn it is just a one page website made by html and css
tht's it
i aint a pro hacker
im sorry don't want to startup my vm for just looking at one page
ohh okay then
I'd rather look into it first
i think thats a good idea
Fair enough. Apologies, I'm just paranoid for the sake of the server
I guess every dev is 😄
I like the color scheme but it looks a bit like a mix of different ui styles in my opinion
Guys, how to use that "Lazy loading" feature from Werkzeug with gunicorn ?
ohh okaayy @ebon gust
@ebon gust It does seem to be:
<link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="register.css">
@winter spindle but i really like the wave in the background and the graphics
ohh okaky thanks
@ebon gust It does seem to be:
<link href="https://fonts.googleapis.com/css2?family=Lobster&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="register.css">
@near ridge yeah .. you got it right
tht lobster is just for tht logo
Today I learned that you can get the source code of a site without having to go to it
Pretty handy
yeah 😂
@near ridge fonts are not the problem it's more like everythink in the header is straight and then the signup form is only rounded
how can i make the navbar rounded
i made the form rounded cuz it looks good tht way
otherwise it's tooo flat
@near ridge you can still use a webserver in front to view the source code without having to open the page 😄
@near ridge Oh ok nice 😄
@winter spindle do you use images as background for the inputs?
what ?
Because it looks like it from the different color on the border
i didnt get what you tryna say
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Yeah that would be helpful
oh okay
actually its just been a month since i started learning html and css
@ebon gust
Oh ok wow then it's actually pretty good if you only started a month ago
Then it's just a rendering issue on your webbrowser you use cause the inputs look like they have 2 different colors but in the css you only set a fixed color
should i make the navbar of full width ?
@winter spindle I personally would remove the line under it
and increased the space below a bit
ohh okay but then i was confused like how to style it
ohh oky
i will make it full width
on scroll i would add a box-shadow on the header (and the header element should have a white background and be fullwidth)
but you can put a container inside it (if you use bootstrap the class is .container)
so that the content like the logo are not on the far left
@native tide a bit but the spacing between the menu items is far to big make it smaller
and as i said but a container inside the header element so that your the logo is not on the far left and the menu is not on the far right
you know what i mean?
yeah i have to add a search box to it too
thts why i have kept tht space
@ebon gust and yeah does this look like a shopping website form 😂
you could just put in a small search icon and when somebody clicks on it you display the search input over the user menu or something like that
what kind of shopping website?
from the screenshot i don't really get what the website is about
does the website sell stuff or just link it?
oh ok
because i really would add some kind of information or tagline so people know what the website is about i mean who would input personal data and signup for something they don't even know what it is 😄
ohh okay soo like can you suggest a tagline or something for tht
@ebon gust
this is the login page
the thing is i still don't really understand if the purpose of the website is to be a shop and sell products or just link it or something else
link means ?
its like only frontend
i will make a website tht will have grid in which i will place the items
He means add something that will tell the user what this website is about.
and like ppl can select tht
like just linking products from other websites or something like a price comparison website
Are you trying to make this to like sell it as a template?
Then just add a random tag line or nothing if you do not want to. 🤷♂️
Anyone want to give me some feedback on the looks of my website?
@devout coral do you suggest fbv if I'm just staring in django?
@plucky tapir fbv?
function based reviews rather than class based @devout coral
That is just me though. It is a preference thing.
I was told flask was easier to use
Oh awesome, dajngo is great
Flask is somewhat easier yes. But you do not get all the functionality like django out the box.
I prefer Django but I am biased.
I would rather sacrifice performance and get more automation building.
Sacrifice performance? With what?
Flask does not really have a performance advantage...
I was told it is lightweight.
What it does have is more freedom.
Well yeah, there is less stuff included. Like if you are just making an api it is probably better to go with Flask because you will not need all the features of Django. But if you are building a website both are good options
I want to hook a webscaper api or use something like protractor to unbox a database and box the data into my own UI.
it's more or less going to be like a specialized search engine or cache proxy of sorts.
I specialize in info systems tech and have a degree in it.
I'm thinking of Data Analyst type implementations to put it on my Resume 🙂
maybe even build a devops pipeline from github, and put it on an AWS
@devout coral <img class="space-img" style="overflow-x: hidden;" src="exo-images/space.png" alt=""> will the image work? I have the exo-images folder in the same directory as the file that this piece of code is in. The problem is that the images aren't showing up.
@cold haven My guess is you are wanting to build a site around all this and maybe have users be able to sign in and use it?
@mortal mango Why are you not doing {% static %} ?
Is it not in your static folder?
no it's in my normal folder where the html file is
Why...
should I be in my static folder?
Well of course. I am guessing your html is in your templates folder??
Actually, just show me a screenshot of your directory tree for the entire project.
sup people, new to flask any tips?
i only use js but i dont use these stuffs {{}} and {%%} what should i use them for?
This is what a project directory would typically look like. You have the project "DivisionManagementSystem" then 3 apps: employees, main, operations. Each app has it's own templates/static directory. @mortal mango
@vivid spear You mean in your html?
yeah
That is part of a Templating Language. It allows to re-use html and also add logic to build your html, it is a beautiful thing.
oh
You technically do not have to use it but it will speed up development and reduce headaches.
For example you could pass a list of names and use a list to unpack it and put them all in <h1> tags
so um im kinda new to python since im just learning flask for web dev can i use something like multiple python files
@devout coral
@mortal mango What does your conf file look like?
Also, where is the image?
And have you ran collectstatic?
@mortal mango I do not see the image inside that directory...
@vivid spear Honestly I am not entirely sure how flask works 100% but I think you need to install jinja as it does not come pre installed
okok thanks gonna look for it
@mortal mango Ok... You are not pointing static there tho...
Look at where you are pointing static to
that is where you need to place your static files
Granted if you are using multiple apps I would suggest one static folder in the project root directory so all you have to do is a collectstatic command and django will make sure all your app files are there. Then you only need to point the server to that one static file and you are done.
should I move the exo-images folder to static or css_files?
to static...
ok
Then in your template you can reference it like so {% static 'exo_images/whatever image.jpg' %}
Do you understand what that entry is doing in the conf file?
Ok just making sure
it works!
hey @devout coral just gonna ask. Is there a python module that create a new html page?
i was planning to do something like a button and a form and once you wrote something on a form like hello it makes a new html template in /template/room/hello and the javascript will redirect that
@devout coral well maybe down the road. I'm just going to get it to work first.
SnowballfuryToday at 6:36 PM
@cold haven My guess is you are wanting to build a site around all this and maybe have users be able to sign in and use it?
@devout coral The css for my rest_framework page isn't working for some reason
it's just an html page without the css
it works on my computer but it's not working on my server
@vivid spear there probably is. Just gotta search for it
@cold haven if that’s the goal then maybe using Django from the beginning will be helpful
@mortal mango what do you mean the case is not working but it is a html page with no css?
yeah
@devout coral yeah lol but nvm i used flasked first just gotta stick it out
https://exoapi.tk/exo I don't mean to send the link but you can check it out here
it's not showing the css
I accidently deleted the css files
and then I brought them back
Ooooof
but now they're not working
You are not returning the html stuff
Anyways I am with my wife now bye
We link up tomorrow
Hi guys. I have a Django ManyToMany field called users. I'm making a post request to create a note, and this note is linked to users.
Here is my request:
And this is my Notes model:
class Notes(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
last_updated = models.DateTimeField(auto_now=True)
users = models.ManyToManyField(Users) # note_object.users.add(user object) adds a user to this field```
The issue I'm having is that I don't know what to input for the users field in my API call. Is it an instance of my Users model? I'm totally lost on what to input there. Does anyone know?
I have to input a list. But what's inside that list I can't figure out.
probably user ids
hey people, using flask rn and why cant i use the static folder
like i just made a static folder
slap the css in
Wdym you can't use it
and if you're using render_template() you can do {{ url_for('static', filename='style.css')}} in your template
but im on pc rn
ah i see
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
use that
and np
ehat about js?
oh ty again
ofc 😛
@vivid spear recommend u read this
Can i hire anybody
For what
Sure, is there payment involved
ofc
alright bet, dm me
<@&267629731250176001>
@trim star we don't help people do things that aren't ethical here.
@native tide Requests for paid work are not allowed on this server.
no above that
I am looking for how to prevent it
With modern software, it's pretty much impossible.
i have some web dev questions abut cross site forgery
@trim star you mean like CSRF?
There are many security checks that are already in place.
@vestal hound yes
There are many security checks that are already in place.
@manic frost and then you can't figure out why your Django server isn't working properly so you just disable all of them on the server side 🥴
💀
Well, if you disable the checks, it's your foot and your gun 🙂
So it seems like with csrf basically what happens is that a hackers is able to replay your session token and make unauthorized requests?
well "authorized" because the session token matches, but it was not submitted by you
in django how to validate data from this val = request.POST.get('val')?
@stable kite wdym
@toxic flame Code for custom Query
Post.objects.filter(title="ShahProgrammer")
#sql
'SELECT "CryptographicFields_post"."id", "CryptographicFields_post"."title", "CryptographicFields_post"."body" FROM "CryptographicFields_post" WHERE "CryptographicFields_post"."title" = 9319c221fb87f14a26a104c1c2db'
Post.objects.filter(title__startswith="Shah")
#sql
'SELECT "CryptographicFields_post"."id", "CryptographicFields_post"."title", "CryptographicFields_post"."body" FROM "CryptographicFields_post" WHERE "CryptographicFields_post"."title" LIKE Shah% ESCAPE \'\\\''
@toxic flame Code for custom model
from django.db import models
from .modelfields import CharField
# Create your models here.
class Post(models.Model):
title = CharField(max_length=100)
body = models.TextField()```
**Code for custom model fields**
```py
from django.db import models
from .cryptography import encrypt,decrypt
class CharField(models.CharField):
def get_internal_type(self)-> str:
return "TextField"
def to_python(self, value: Any) -> Any:
print("to_python",value)
return self.clean(super().to_python(value),None)
def get_prep_value(self, value: Any) -> Any:
print("get_prep_value" , value)
return encrypt(super().get_prep_value(value))
def from_db_value(self, value:Any, expression:Any, connection:Any)-> Any:
return decrypt(value).decode()
def clean(self, value, model_instance):
"""
Convert the value's type and run validation. Validation errors
from to_python() and validate() are propagated. Return the correct
value if no error is raised.
"""
self.validate(value, model_instance)
self.run_validators(value)
return value```
y would u do that
@toxic flame I am encrypting data but when query the data django calls get_prep_value() but when i use lookups it does not calls that function
so you're trying to lookup data, but it doesn;t exists?
have you tried the superuser /admin to verify if the data is saved?
@toxic flame it exists
but when u query it, it doesn't appear?
@toxic flame you didn't understood my problem?. I am telling that Django didn't processed the query value before generating SQL when used lookups but it process query values while not used with lookups
but when u query it, it doesn't appear?
@toxic flame wdym?
i dont know english too good
Are there any free services out there for keeping an inventory of products with prices and then displaying that data on a website that I'm making with django? (It should handle payments for me)
Anything that handles payment will not be free.
I mean maybe there is but I doubt it. Since making monetary transactions has a cost.
ok well im making a website for a client
and i need to have a store front and handle transactions
like ... real transactions? You're building an ecom system for someone and you don't know how to do that and they're paying you for that?
Nothing is going to handle payments for free. The CC companies will take their fee, and so will the payment processor.
Look at Stripe for instance. Their APIs are a gold standard in ecom payment processing.
So usually you're going to have a flat monthly fee and then usually around 30 cents plus 2.6%-2.9% of the transaction as a fee.
Stripe, authorize.net, and more can process but again ... never for free cause the CC companies don't do that for free and no one is going to absorb that cost for you.
Are there any free services out there for keeping an inventory of products with prices and then displaying that data on a website that I'm making with django? (It should handle payments for me)
@native tide you want a lot for free I gotta say
@warm igloo ok i meant i needed it to be free so i can test it without paying
gotcha gotcha
Generally they have dummy systems set up for testing. Stripe does I believe, and I've used authorize.net like that too. But Stripe still may require some sort of account and default payment, but I'd be surprised if they didn't have a way to build on their platform without giving you demo time for fake transactions.
i just need some kind of inventory system that i can access and display the items on my web app
and then direct the users to where they can pay
well, see, that's the challenge .. there is payment processing and there is inventory management
i wont be dealing with the transactions directly on the site
