#web-development
2 messages · Page 141 of 1
But if you dont have previous experience with dynamic web sites and js
Django is your way to this app
im just trying to resize images but keep proportions using it
and the docs dont explain it
Are you resizing
with proportion
to the original size ?
Or are you just setting a height or width ?
Well I m making a community for programmers and other innovative people. But I need to work on it at a high speed so do someone want to contribute ?
trying to proportionally resize uploaded images. could be any size. or horizontal or vertical like if i resize a vertical image to 100,50 then it wont be vertical anymore. you get what im saying.
finally found the things i needed reading the source code, im gonna mess around with it just to see what happens
use implicit waiting feauture (google it)
use global variable for that request['Files']
I fixed it by adding this ```py
from django_filters import CharFilter
title = CharFilter(field_name="title", lookup_expr="icontains")``` To my filter class
I just found this regarding my situation:
This is a restriction of HTTP that POST data cannot go with redirects.
Using sessions with files is also not a good idea, I think I will have to redesign backend because of that..
I just forgot the percentage sign
my image is not showing in website
<svg width="400" height="140" xmlns="http://www.w3.org/2000/svg" style="border-radius:160px"><image src="twice.jpg" alt="Twice" height="200" width="70%" ><title>Placeholder</title></svg>```
this is code
the image is saved in folder where i my html file is stored
also how to make a round image in html ?
are u using django?
if u are then it won't work like that
u will have to set up static files
it is a simple process
oh no [Errno 13] Permission denied: 'media/media/'
django
Hi, this is my code for my contact form ```py
def contact_view(request):
# I have aldeady imported send_mail and settings above
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
contact_name = form.cleaned_data.get('contact_name')
contact_email = form.cleaned_data.get('contact_email')
form_content = form.cleaned_data.get('content')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'form_content': form_content,
}
send_mail(f"Message from {context['contact_name']}",
context['form_content'],
context['contact_email'],
['my_mail@gmail.com'],
fail_silently=False
)
# return HttpResponse("Sent!")
return render(request, "contact_view.html", {"form":form})
my settings.py py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mail' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
hello
can i ask something about html?
<video width="1000" height="600" controls>
<source src="" type="video/mp4">
<source src="" type="video/ogg">
</video>
what should i write at mp4 and what a ogg
what's up with this error?
TypeError at /food/register/
type object argument after ** must be a mapping, not set
Request Method: POST
Request URL: http://127.0.0.1:8000/food/register/
Django Version: 2.2.5
Exception Type: TypeError
Exception Value:
type object argument after ** must be a mapping, not set
Exception Location: E:\Anaconda\lib\site-packages\django\contrib\auth\password_validation.py in get_password_validators, line 30
Python Executable: E:\Anaconda\python.exe
Python Version: 3.8.3
Python Path:
['E:\\Shrish\\SHRISH PROJECT\\Project-2-College\\HotelManagement',
'E:\\Anaconda\\python38.zip',
'E:\\Anaconda\\DLLs',
'E:\\Anaconda\\lib',
'E:\\Anaconda',
'E:\\Anaconda\\lib\\site-packages',
'E:\\Anaconda\\lib\\site-packages\\pyzmail-1.0.3-py3.8.egg',
'E:\\Anaconda\\lib\\site-packages\\distribute-0.7.3-py3.8.egg',
'E:\\Anaconda\\lib\\site-packages\\win32',
'E:\\Anaconda\\lib\\site-packages\\win32\\lib',
'E:\\Anaconda\\lib\\site-packages\\Pythonwin']
error seems to be here but what should i do?
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
print(user.password)
user.set_password(user.password)
user.save()
@native tide pythonanywhere.com
thx
what you want to do here ? you want to change the password??
hash the password and store in the database
nvm i found the probelm and i just removed it lol
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {'min_length', 8}
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
I added that options there and that was the problem
Hi, I'm struggling with associating a Video DB to a User. I tried but when you upload a video, it runs public and not only for you, everyone who creates an account can see what everyone uploads. this isn't what i want to do. Anyone for some help? Here are my main files.
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Videos
class UserRegisterForm(UserCreationForm):
class Meta:
model=User
fields=['username','password1','password2']
class AuthenticationForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'username','placeholder':''}),
label='Utilisateur')
password = forms.CharField(widget=forms.PasswordInput(
attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':''}),
label='Mot de Passe')
class Meta:
model=User
fields = ['username', 'password']
class Video_Form(forms.ModelForm):
class Meta:
model=Videos
fields=('caption','Video')```
forms.py
def Profile(request):
all_Vid=Videos.objects.all()
if request.method=='POST':
form=Video_Form(data=request.POST,files=request.FILES)
if form.is_valid():
form.save()
else:
form=Video_Form()
return render(request,'Utilisateurs/Profile.html',{'form':form,'all':all_Vid})
def Delete_Video(request,pk):
Vd=Videos.objects.get(id=pk)
if request.method=='POST':
Vd.delete()
return redirect('/profile')
return render(request,'Utilisateurs/Delete.html',)```
view.py (but only the main fuctions)
from .validation_taille import Taille
# Create your models here.
class Videos(models.Model):
caption=models.CharField(max_length=100)
Video=models.FileField(upload_to='video/%y',validators=[Taille])
def __str__(self):
return self.caption```
and models.py
have u tried one to many association between user and video
wdym?
a user has many videos right?
yes
and videos are specific to the user right?
yes
ur reporter will be user and video will be article
no need to worry about the meta there
Okay thanks!
So I have to create an other class User ? Sorry for wasting your time I'm new to django 😅
ur registration creates new users in admin right?
Yes
And AuthenticationForm allows you to connect
from django.contrib.auth.models import User
Done
is that supposed to be some sort of login form?
Yes
I creataed my own one
Instead of using the implemented package with login
if request.method == 'POST':
form = AuthenticationForm(data = request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = django_authenticate(username=username, password=password)
if user is not None and user.is_active:
django_login(request,user)
return redirect('MonProfile')
if user==None:
messages.error(request,"Le nom d'utilisateur ou le mot de passe n'est pas bon")
else:
form = AuthenticationForm()
return render(request,'Utilisateurs/Connexion.html',{'form':form})```
Here's the login fucntion
Ok
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username', 'email', 'password')
u can do something like this too
that's from the code i'm writing right now though lol
I see
u got some hints from that? if yes noice
Adding a Meta class ?
caption=models.CharField(max_length=100)
Video=models.FileField(upload_to='video/%y',validators=[Taille])
def __str__(self):
return self.caption
class Meta:
model=User```
try once
would it work like this?
all_Vid=Videos.objects.all()
if request.method=='POST':
form=Video_Form(data=request.POST,files=request.FILES)
if form.is_valid():
form.save()
else:
form=Video_Form()
return render(request,'Utilisateurs/Profile.html',{'form':form,'all':all_Vid})```
It makes something wiered with this func, i think because it's no longer Videos.objects but User.Videos.objects ? @stiff ferry
that would be something like
# APP
import routes
#routes
import app
look for something similar
Utilisateurs_videos.user_id```
migrations maybe?
look for that pattern. where you have 2 files importing from each other. dont know what else to tell you.
I migrated and here's the new error : return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: Utilisateurs_videos.user_id
When I asked to make migrations , It said that:```You are trying to add a non-nullable field 'user' to videos without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
- Provide a one-off default now (will be set on all existing rows with a null value for this column)
- Quit, and let me add a default in models.py```
I chose option 1
and entered 0
u have some data right?
dont know how flask works for sure, look at the docs
you should set it as None/null not 0
How can I go back ?
just open your db up and change it. thats, just better db patterns.
when i faced that problem i emptied my database, the error is because u are adding a new non empty type of field in the database where the previous one didnt have that
from what i understood that is
if you add a field that you said cant be empty and already have database data, you have to set a default. otherwise the rows you already have will not pass the NOT NULL constraint. so usually when you add fields, just add blank=True and itll work. then you can remove blank=True after you migrate
yes that works too
u can easily add the foreignkey values from django admin than any other new fields too
Issue : https://github.com/sc0op-creator/Programming-Community
Language(s)/Framework (s) : HTML, CSS , JS and Flask (python framework)
Description : I am making a programming community web app and I want someone to contribute and work with me because alone I cannot work at high speed DM me for more.
I'm not sure where should I ask that but how do I get the avatar of a user who logged in? I'm using Flask for that btw
@app.route("/@me")
def me():
code = request.args.get("code")
at = Oauth.get_access_token(code)
session["token"] = at
user = Oauth.get_user_json(at)
user_name = user.get("username")
user_discriminator = user.get("discriminator")
user_id = user.get("id")
user_avatar = user.get("avatar")
with open('bal.json', 'r') as f:
load = json.load(f)
money = load[str(user_id)]["Money"]
username = load[str(user_id)]["Username"]
return render_template("my.html", money=money, username=username, avatar=user_avatar)
Hello everyone. I have this code enrolled_courses = user.students.filter(is_trial=False).order_by('-id') remaining_courses = list(Course.objects.filter( active=True, is_trial=False, hidden=False ).exclude( id__in=enrolled_courses.values_list("id", flat=True) ).order_by('-id')) courses = list(enrolled_courses) courses.extend(remaining_courses) I was thinking if is it possible to replace the courses.extend part with chain of itertools. If so will it improve the performance?
Hello, what do you mean by get the avatar? are you passing it through request? If so then the request wont have the avatar but what it will have is its path.
getting it from the json file
can you post the key: value for the avatar from json file?
Anyone here developing with Odoo?
Shoot
I get info such as the user ID, name and discriminator from a json file with the get_user_json function, i wanna know how would i get the avatar of the user as well
@staticmethod
def get_user_json(access_token):
url = f"{Oauth.discord_api_url}/users/@me"
headers = {"Authorization": f"Bearer {access_token}"}
user_object = requests.get(url=url, headers=headers).json()
return user_object
and right here in my html code i need the card to have a circle with the user avatar
<body>
<div class="card"></div>
<div class="pfp"></div>
</body>
<style>
body {
background-color: cadetblue;
}
.pfp {
height: 25vh;
width: 25vh;
border-radius: 50%;
border-style: solid;
border-color: darkred;
background-color: #555;
position: absolute;
top: 3vh;
left: 87vh;
background-image: url({{avatar}});
}
and i get it right here using this
code = request.args.get("code")
at = Oauth.get_access_token(code)
session["token"] = at
user = Oauth.get_user_json(at)
user_name = user.get("username")
user_discriminator = user.get("discriminator")
user_id = user.get("id")
user_avatar = user.get("avatar_url")
@frigid pawn
how can I get file type in django ?
If there are any folks who are experts at Python Flask forms and can help me with the issue described in my stackoverflow post linked here, I would be very grateful. https://stackoverflow.com/questions/66630554/cannot-access-form-responses-in-dynamic-flask-form-python
what div bg color goes well with blue bg color?
Hey. I have a big problem. I want to make a Bot and for this i need to login into WhatsApp web. I want it to make verify automated so i don't need to use my phone. Is there a way to do it with a automation or with a emulator?
sounds like something that would break their ToS, not sure we can really help with
nah that's 100% against ToS
white, or a complimentary color or a shade or tint
any collor that fits that category?
pretty much yea
https://htmlcolorcodes.com/ to find what colors work well together
https://coolors.co/ is a good color scheme generator
Good utilities i could use
Awesome Job
Only one default export allowed per module? I cant have 2 components in react?
in the same file?
hey guys, I'm pretty happy with a flask app I built, but struggling with consistent template 'control' - should I consider a frontend framework, and what do you recommend?
I'm quite happy with some designs I made on Figma, but unsure how to go from there.
Congrats on the app
You can only have one default export per file. The others are named exports.
so its just normal export?
export const exampleComponent = (props) => ...
^ This is a named export, you import it like this:
import {exampleComponent} from ...
When you do a default export export default exampleComponent you are setting the default export of that file, there can only be one. To import you do:
import exampleComponent from ...
@buoyant shuttle
Hey! I forgot to git pull before adding new features in the code. When I git push now, will it overwrite the changes that my co-worker made on GitHub? Or will it somehow merge those? I don't want those things to be lost. Is there any way to do this easily?
I think you will run into a conflict:
https://stackoverflow.com/questions/54278883/forgot-to-git-pull-before-working-and-now-i-cant-git-push
I wish I could help more, I'm a beginner to git (my random guess is that the branches aren't synced so you'll run into an error).
I'm working on a simple page that will allow users to make posts for their profiles, and the handling will be done through a standard api. I'm wondering what is the most standard way to format an endpoint for something like this? If a post has 3 main parts, a set of images, a caption, and a description, how should the API accept this data? Base64 encoding the image in a JSON body or some multipart request?
Hmm, this question may be better suited for #software-architecture
@clear musk Look into pull with rebase
And good luck, git is still such a complicated thing to me
I like Bootstrap.
so I would like to listen for webhooks from the monday.com api but they require that I send a challenge key back to them for the webhook. I would need to set up like a flask/django webserver for this, right?
ye
is this a table?
yes
pase the code
alternativaly what you could do is play with the td(table data) width
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 50%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
width: 166px; height: 30px;
}
tr:nth-child(even) {
height: 23px;
background-color: #dddddd;
}
</style>
</head>
<body>
<table class="center">
<tr>
<td>Current session</td>
<td>csgo</td>
</tr>
<tr>
<td>Players ready</td>
<td>stuff</td>
</tr>
<tr>
<td>Max players</td>
<td>5</td>
</tr>
</table>```
code
@buoyant shuttle
alright so each row has a td right? so your going to have to style the td so give it a class name, like firsRow, for td in the first row, control the width,
could you please make that
its 5am im about to head to bed, been up working
lol
but ill give you a snipper and tell you where to go from there
@native tide what i used to do is download Microsoft Web expression
its a GUI for html. I use it for tables cause it comes extremely useful, instead of coding
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 50%;
}
table .row1{
width:"Play with this, it determines the widht od the line. ideally keep it decrease the number to decrease the width";
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
width: 166px; height: 30px;
}
tr:nth-child(even) {
height: 23px;
background-color: #dddddd;
}
</style>
</head>
<body>
<table class="center">
<tr>
<td class="row1">Current session</td>
<td>csgo</td>
</tr>
<tr>
<td class="row1">Players ready</td>
<td>stuff</td>
</tr>
<tr>
<td class="row1">Max players</td>
<td>5</td>
</tr>
</table>
here is the wikipedia to webexpression
Microsoft Expression Web is an HTML editor and general web design software product by Microsoft. It was discontinued on December 20, 2012 and subsequently made available free of charge from Microsoft. It was a component of the also discontinued Expression Studio.
Expression Web can design and develop web pages using HTML5, CSS 3, ASP.NET, PHP, J...
download it here https://www.techspot.com/downloads/2934-microsoft-expression-web.html. its disconitnued no more updates
but its helpful to save tins of energy coding
thanks!
Can anyone here help me figure out how to access data from a FieldList on WTforms? I have a FieldList of SelectFields where items are added Dynamically on initialization, and when I submit the form I always get none as the value regardless of what I choose. Full code is here: https://stackoverflow.com/questions/66630554/cannot-access-form-responses-in-dynamic-flask-form-python
How can I change the position of an element without effecting other elements using CSS?
position absolute positions the item based on the width of the display staticly
if you mean you want it to move from where it was while everything else stays where they were
position: relative
absolute or fixed if you want to pull it out of the flow entirely
(depending on whether you want it relative to container or viewport)
Ok, I'll try that, thanks 
Can anyone pleaseee help me with a few things if so dm me
i really need help
Need help with Django channels ERROR:-ValueError: No application configured for scope type 'websocket'
can somone help me attributes to UserCreationForm forms because i want to use bootstrap for the fields but its not being applied and adding widget hash map isnt wrking as well
i also want to add a placeholder but again the widget dict isnt working or applying any changes
Hello their! I have this error when i launch my flask app. Any idea?
End of file? Sounds like an unclosed quote or bracket or something
That my code, i don't where can be the error ?
discord = DiscordOAuth2Session(app)
HYPERLINK = '<a href="{}"><span>Connection</span></a>'
@app.route('/')
def home():
return f"""
{HYPERLINK.format(discord.create_session())}
"""
return render_template('jonque_home.html')
# Launch app.
partial_run = partial(app.run, host='127.0.0.1', port=50879)
t = Thread(target=partial_run)
t.start()
# Launch DevBot.
TOKEN = os.getenv('TOKEN')
DevBot.run(TOKEN)
Can you help me?
Why the two returns? And no I personally don't really know how to start investigating this
Okay i see, i don't know it's for add session to a button in another html file.
u can install the django-boostrap package
pip install django-bootstrap4
and how would that solve my issue
in the templates
u should add {% load bootstrap4 %}
add bootstrap4 to settings.py INSTALLED_APPS
THEN HOW ARE U CALLING THE FORM?
{{ form.as_p }}?
nah im having to do a for loop and just write the for loop name
but u mentioned a usercreationform
yeah
in my views, the view function is calling the form thn being passed as a context into the html
okay can u show the template?
my forms are created from UserCreationForm
<html>
<head>
<title>
Simple Form Application
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body style="text-align: center; background: #DF2B4F">
<div class='container' style="text-align:center;">
<div class='card' style='margin-top:30px;' width='20rem;'>
<div class='card-body'>
<a href="/"style=" float:left;"> <img src="static/icons/back.svg"> </a>
<br><h2 class="card-title">Register</h2>
<form method="post" class='form-group'>
{% csrf_token %}
{% for field in form %}
<div style=" text-align:center; color:black; margin-left:-500px "><h4> {{ field.label_tag }}</h4></div><br>
<div style="margin-top: -30px; " class='float-middle'>{{ field }}</div><br>
<p style=" color: #FC4445;">{{ field.errors }}</p>
{% endfor %}
<a href="/reg"><button class='btn btn-success' style='margin-top:10px;'>Register</button></a>
</form>
<p> if you have a account please <a href="/login">login</a></p><br>
</div>
</body>
</html>
{% csrf_token %}
{% for field in form %}
<div style=" text-align:center; color:black; margin-left:-500px "><h4> {{ field.label_tag }}</h4></div><br>
<div style="margin-top: -30px; " class='float-middle'>{{ field }}</div><br>
<p style=" color: #FC4445;">{{ field.errors }}</p>
{% endfor %}
hmmm
this is such a bad practice
why not {{ form.as_p }}
it does all of this in a line
because if i write form on its own its going to polute the page with the "help texts"
nah tbh, im rethinking everything
okay u need bootstrap for this?
yea
but ive imported it through css
the only reason that im using this shit is because of another issue which was solved after implimenting this
so its not important but if you can find a way for me to be able ot have bootstrap forms
that would save me so much time
there isn't any straight solution for this
class UserRegisterForm(UserCreationForm):
class meta:
model = User
Fields = ['username', 'email', 'password','password2']
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter Email'}),
'password': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Password'}),
'password2': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Confirm Password'}),
}
def __init__(self, *args, **kwargs):
super(UserRegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
self.fields['username'].widget.attrs['placeholder'] = ''
self.fields['password1'].widget.attrs['placeholder'] = ''
self.fields['password2'].widget.attrs['placeholder'] = ''
yeah ik
its fucked
i need to make my own form and just make sure that i save the user to the abstract model and not a completely different model
i was trying my hardest to see if there was anyway that this shitty class could have any way for me to allow some passthrough but no it is what you get
exactly
nah ill just make my own template ive realised what i need to do
ya
for django restframework, which one do you guys prefer
functional based API views, or class based API views
for exmaple when click on link then run code test.py
do u use flask or django
if you're not using either of them u can use ajax
Example :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
function goPython(){
$.ajax({
url: "MYSCRIPT.py",
context: document.body
}).done(function() {
alert('finished python script');;
});
}
</script>
</body>
</html>
u can use <a> tags instead of input if u want a hyperlink text and add the onclick property and It'll work as above
@proven carbon
thanks
don't forget to add jQuery as mentioned
what's the best method to add a payment option in your django application
it will have cash on delivery, what i want is to add online payment too
probably stripe or paypal @stiff ferry
I personally use stripe
Mhmm
stripe will cover pretty much all the credit card stuff
except paypal
but both stripe and paypal have pre-made DJango intergrations
yeah I just like to throw everything on stripe so I don't have to worry about all the other stuff
especially security wise
i more question
is there a way to make a qr code specific to a certain organization (say here my django project which will have multiple different objects under it)
But what payment system do I use if stripe isn't available in my country? 
mine also doesn't support stripe lol
😔
cash on delivery lol
My go to's are Stripe, or Braintree
is it possible to use django ctx in jsx react
that way i wont have to be making bunch of http calls
not really
damn, was hoping so
ill give it a try
yeah it didnt work what a bummer
jinja templating wont work either
using ss rending and client side rendering is generally a bad idea
pick one or the other
I just renamed my model, but my terminal says its deleted.
looks like i look all the data
def index(request):
UA = request.META['HTTP_USER_AGENT']
IP = get_client_ip(request)
return render(request, 'index.html'), UA, IP``` Am I passing the UA and IP variables correctly? (django)
can anybody here tell me (or give a link to a tutorial) how to make a sticky navbar onscroll using css and javascript? 😅
Hello! Do you know how to change Login text in span with a var like user.name ?
That my code:
<a href="{{ 'login' }}"><span>Login</span></a>
@app.route('/')
def home():
if not discord.authorized:
return render_template('jonque_home.html', login=login())
print("CONNECTED!")
user = discord.fetch_user()
return render_template('jonque_home.html')
you can do it via bootstrap, that what i always do
anyone work with d.js?
as in discord.js?
what i need to learn to create a website with django?
html and css
to create a basic website,m after learn js, to create a functional website
also python lol
There are many free tutorials on YouTube that will teach you the basics to what is needed to create a website with Django. But if you are unsure where you start on youtube or prefer reading sources, I would recommend you understand some basic core concepts:
- Use the Django Documentation. https://docs.djangoproject.com/en/dev/
- Have a basic understanding of the following programming languages.
a. Python
b. HTML
c. CSS (unless you are using bootstrap) - Lastly, if you are wanting to store data, understanding SQL is a major bonus.
Two video series I would recommend for the very basics are:
https://www.youtube.com/watch?v=Z4D3M-NSN58&list=PLzMcBGfZo4-kQkZp-j9PNyKq7Yw5VYjq9
or
More in depth
https://www.youtube.com/watch?v=B40bteAMM_M&list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi
Welcome to the first python django tutorial on my channel. Django is a full stack web framework that allows for rapid development of websites. In this tutorial I will be showing how to setup and install django and talk about how to navigate between different pages.
Source Code: https://techwithtim.net/tutorials/django/setup/
Playlist: https://...
How to Build a Simple Blog with Python and Django. Creating a blog with Django his pretty easy! In this video series I'll walk you through it step by step.
In this video we'll set up our development environment, create our Django Project and add a blog app to it. We'll create a Django SuperUser for the Admin Area, and then configure our data...
My favourite is the one by Justin
But he uses django 2, even now, so wouldnt reccomemend.
the one in freecodecamp. which is justins own uses django 2. django 3 has been out for some time now
tysm, i hope i can pay you one day.
It's my absolute pleasure to help you.
The greatest thing about programming in my honest opinion is that we are always trying to learn more, while I am by no means close to even being "good" with Django, I am happy to help out where I can, since I have received so much help in the past and I will be needing more help in the future as well.
Hi! I am having a heck of a time with FastAPI getting Sagger to show the parameter descriptions. For example,
@fastApi.get("/run/get/{run_id}", status_code=status.HTTP_200_OK, name="Get Run By Id", description="Gets a run by its run id (it's name generated).")
async def run_get_by_id(run_id: str = Query(..., title="Run ID", description="The run ID/name that we are requesting", example='20210315T135404_fname_lname'),
user: User = Depends(loginManager)):
"""
Gets a run by its run id (aka name).
:param user: The user credentials to know who is getting the run.
:type user: The user that is getting the run.
:param run_id: The run id to get.
:type run_id: str
:return: The run found (rendered to JSON), or an error JSON.
:rtype: Union[dict,DocumentRun]
"""
The "description=" never shows up in swagger, but the rest does?
Hi, anybody available for chat?
Can anyone here help me with rendering multi-widget forms in Django? this code <form method = "post", action = ''> {% csrf_token %} <div> Form should be here. {{form.category}} {{form.widgets}} renders them like this: Form should be here. <django.forms.fields.ChoiceField object at 0x7fd29f0362e0> [<django.forms.fields.ChoiceField object at 0x7fd29e6f3af0>, <django.forms.fields.ChoiceField object at 0x7fd29e6f3640>]
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.
Just use {{ user.name }}
And pass in user or whatever to the template
class RenameContentType(migrations.RunPython):
AttributeError: module 'django.db.migrations' has no attribute 'RunPython'``` I get this when I try to migrate
does anyone know how I would fix this?
For what ever reason I am getting this error:
cross-origin resource sharing error header disallowed preflight response
I am using nginx. Does anyone know the solution?
I highly agree with what @native tide told you but I also wanted you to take a look at corey schafer
https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
or Dennis Ivy (( He's been uploading videos about django until now and it's very useful ))
both are supportive
and my HUGE advice to you is not to learn bootstrap for responsiveness only use it for time, I don't use it myself , Vanilla CSS is much powerful and you've fully responsive using Flexbox or Grid
and I also recommend learning Sass which is better than CSS , it's the same CSS syntax but much organized and powerful if u want to stick with CSS it's fine CSS is still cool too just take a look at Sass
And Learn Typescript instead of Javascript much easier and more powerful
Just wanna say that, You've a promising future!
can typescript run on runtime
Guys is it a good idea, to keep constantly writing to my models
like each time my server is up 24/7 writting to db
well tbh typescript is better than js because it tells u the errors before the runtime which is much easier to find errors and debug
i already switched all my js files to ts
lol thats my queue
Codemy.com youtuber, is making a new serires with django
it would include more concepts
Learn how to use React and TypeScript to create a quiz app project. You will also learn how to use Styled-Components with React.
🔗 What you will make: https://tender-mcnulty-a4a646.netlify.app/
💻 Code: https://github.com/weibenfalk/react-quiz
🎥 Course from Thomas Weibenfalk. Check out his YouTube channel: https://www.youtube.com/user/Weibenfal...
Learn how to start using Typescript in your React code. I go over props, hooks, and render props.
#react #typescript
Snippets: https://gist.github.com/benawad/1e9dd01994f78489306fbfd6f7b01cd3#file-snippets-typescriptreact-json
Code: https://github.com/benawad/react-typescript-example
For more information on this checkout: https://github.com...
a lot more of tutorials
typescript is the future of javascript
believe me
it's like javascript but much easier and powerful
For what ever reason I am getting this error:
cross-origin resource sharing error header disallowed preflight response
I am using nginx. Does anyone know the solution?
All it does u write in ts and it compiles and generates the code into js file so u can add this js file to html or something
microsoft out did themselves
from where u get this error
like always and google as well
is it similar to js? or has some extra concepts involoved
Doing a mock webhook request on discordbotlist.com
it includes advanced js but written in easier way everyone knows that advanced javascript is very complicated but typescript got it solved
are u trying to make a discord.py
it seems with vanilla Typsescript i can get things done, i dont even need to use react or vue
If u know javascript u know Typescript
simple as that
No I am trying to make a webhook system for my discor bot
Made it easier for me lmao
guess you've to go there #discord-bots
theres a discord.py server
oh so idk the error maybe u can wait someone to help you
So basically I need a flask webpage which recieves the webhook fires from the website, but something with CORS is blocking it from recieving it.
oh so you're at the right place , Apologizes wish I could help you but I don't have any knowledge about flask, I know Django
Exactly!
Guys i need help
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
``` What does it mean int argument cant be a string
How to show matplotlib on webstite with flask?
If you all are asking who would answer?
i have the same question too
You'll have the graph as a file (plt.savefig(image_name)) then you can serve this static file to your frontend.
you'd be better off using a JS library for graphs, especially since they are interactive - arguably more "useful" than an image.
have you setup your CORS allowed origins?
I figured it out nvm
cool, what did it turn out to be?
What did you open up?
i have 5 graphs
made by for loop
constantly changing
what about that?
Sure, you're using jinja2 templates right?
ye
Save your graph images, have a list of the graph locations, pass that to your frontend, then have a for loop in your jinja2 template to render the images
how would i save that images?:
plt.savefig(image_name)
and with for loop? because the names cant be same
Yep, generate unique names for each.
and png or jpg
I'm sure you can make that decision for yourself
when users upload files, im just leaving them the same name they are when they get uploaded. im sorting based on user so it doesnt matter quite as much as because most people dont have photos with the same name anyways
but graphs are a different story, lmao i should read the whole message.
maybe this is a dumb question, but can you write from reverse relations. like if i add a row, can i also add a row from the foreign key relation. for example:
Model1:
groud_id: 10
user1: user1
user2: user2
Model2:
groud_ref: ForeignKey(Model1)
other_fields: ...
if i create Model1 and set it to that, can i also do a create for Model2 at the same time from the same request?
So on the creation of the first model you want to tie it to Model2 through a ForeignKey relation?
if you are asking if you can reverse-access a foreign key relation, the answer is yes. Unless you are meaning something else.
Trying to migrate to add a field called balance but it says it's column doesn't exist
LINE 1: ...hter"."nationality", "fighters_fighter"."season", "fighters_...```
no i want to create both in the same post. so i want to create model 1, and give its child data at the same time. so the way im set up is messages are tied to message groups, that way its simpler to pull all the messages between 2 people. so i want to create the message group and send the first message all in one run instead of having to make 2 api calls
i know i can pull from the reverse, but can i create from the reverse.
Why would you not be able to?
im thinking something like this:
class AddGroupAndMessageSerializer(serializers.ModelSerializer):
message_group = ReverseMessageSerializer(many=False)
class Meta:
model = MessageGroups
fields = ('user1', 'user2', 'unique_key', 'message_group')
def create(self, validated_data):
if validated_data['user1'].id < validated_data['user2'].id:
user1 = validated_data['user1']
user2 = validated_data['user2']
else:
user1 = validated_data['user2']
user2 = validated_data['user1']
user_contains = f'id{user1.id}, id{user2.id}'
group_create = MessageGroups.objects.create(
user1=user1,
user2=user2,
unique_key=user_contains,
)
message_create = Messages.objects.create(
sender=validated_data['sender'],
recipient=validated_data['recipient'],
message=validated_data['message'],
msg_group=group_create
)
return group_create
``` and the serializer should pull it, right?
In your one API call you can do as much as you want in your views as you need to.
its 2 separate tables, and in Rest framework, you use serializers. so on post, it deserializes the json, creates the item, then serializes. and im not sure if itll pull the correct serializer for the post.
Ah I havent used the REST framework. I mean outside of the REST framework recreating it seems pretty simple.
thats the tricky issue. im running into problems on my frontend, because this all runs through a websocket. and parsed into react. its not the same as making posts and gets. the changes are passed through the socket. and when i go to a users profile, i want to check if message group exists, just send the message, otherwise create the group and send the message. making 2 api calls and waiting for the response is really counter intuitive and makes something simple take much longer
but if you just click on a send a message and dont send a message, i dont want to create a group because it appears in the chat section for no reason.
@native tide We don't allow requests for paid work here. You might want to check out any freelance platform if you need work done.
try to google it it's not hard or simply ask how to do it we can help rather than paid
hey, I'm trying to make a background behind my text like this
I just simply used <a style="background-color: #3d444a">, but how can I make the "light bar" go beyond the text so they're all the same width? 
I think you'd use a table but there might be a better way
<table>
<tr>
<td class="x" >In collectie sinds: {{ date }}</td>
</tr>
<tr>
<td class="y">Uitgespeeld op: {{ other_date }}</td>
</tr>
<tr>
<td class="x">Local multiplayer: {{ tttt }}</td>
</tr>
</table>
and style either the row (<tr>) or the cell (<td>) and they should all be the same width
that does seem to do the trick
was making a portfolio app using django. The CSS is not loading,even after it is there in the project. Also not showing any error. What could be the problem?
`{% load static %}
<!--
<link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}">
<h1>Hello World</h1>
<img src="{% static 'images/profile.jpg' %}">
-->
<!DOCTYPE html>
<html>
<head>
<title>NETRANJIT BORGOHAIN</title>
<link href="{% static 'css/main.css' %}" rel="stylesheet" type="text/css" >
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body>
<br>
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="card-body"> </div>
</div>
<div class="col-md-9">
<div class="card-body"> </div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<div class="card-body"> </div>
</div>
<div class="col-md-6">
<div class="card-body"> </div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<div class="card-body"> </div>
</div>
<div class="col-md-9">
<div class="card-body"> </div>
</div>
</div>
<br>
</div>
</body>
</html>`
My home.html
I had some questions based off of some syntax and stuff
in python?
Upon python web scraping lol
okay u use selenuim or bs?
Python
bs*
beautiful soup
Yeah I’m using it
tell me your use case and i will suggest accordingly
And request
what are u using it for?
Haven’t heard of it before lol
what kind of project
It was a school work assignment
i know a youtuber who has a course which is really good
To grad all the reviews from a website
This selenium tutorial is designed for beginners to learn how to use the python selenium module to perform web scraping, web testing and create website bots. Selenium is an automation framework that allows you to interact with websites using something called a web driver.
How to Fix Pip: https://www.youtube.com/watch?v=AdUZArA-kZw
Chrome Web-dr...
Grab*
do u want to use it in a web app or just a python program
We r only allowed to use bs
But I’ll be down for learn another library
ya selenium is very helpful
Twt! Everyone’s first choice learning programming stuff
i have used it for many websites
I’ll check that out
What kind of projects did u build with web scraping
I actually just started to learn it from last week
Just being curious
this is a simple project made with selenium
Oh wow. That’s rly cool!
Nice nice
thanks
Got u got u
I was so lost for the syntax
Whether i was supposed to find tag or class to target what I need to grab
okay i understand
The Beautiful Soup module is used for web scraping in Python. Learn how to use the Beautiful Soup and Requests modules in this tutorial. After watching, you will be able to start scraping the web on your own.
💻Code: https://github.com/vprusso/youtube_tutorials/tree/master/web_scraping_and_automation/beautiful_soup
Tutorial from Vincent Russo o...
I’ll check this out too
Thx man
Will that be cool if I ask u any random questions? Some questions that are not speci googleable or checked on stackoverflow lol
Maybe not tonight
guys, I want the message box on the right to be shown when I click the home button on the left by react router
what should I do for that?
anyone?
@ HELPERS ?
Hi, I am using django and this is my code for the edit profile view ```py
def edit_profile(request):
context = {}
creator_profile_form = CreatorProfileForm(instance=request.user.creatorprofile)
context["creator_profile_form"] = creator_profile_form
if request.method == 'POST':
creator_profile_form = CreatorProfileForm(request.POST)
if creator_profile_form.is_valid():
creator_profile_form.creator = request.user
profile = creator_profile_form.save(commit=False)
profile.creator = request.user
profile.save()
messages.success(request, "Updated profile")
return redirect("edit-profile")
return render(request, "registration/edit_profile.html", context)
But when I submit the form I get this error ```powershell
IntegrityError at /accounts/edit-profile/
UNIQUE constraint failed: base_creatorprofile.creator_id```
Thanks
does anyone know how to do a case sensitive SQL query with SQLAlchemy ?
For example I want make a query for the name TEST. I want to return the results with TEST only and not test or Test
found this: https://stackoverflow.com/a/31788828/2449857
I am using sqlalchemy with mysql database. When I am using following query on User object :
session.query(User).filter(User.name == 'admin').all()
I get all the results which have usename as 'Ad...
Thanks @silk trellis , just what I needed
FastAPI or Flask?
do you want a full website or just an api, and do you want to use react/vue/sth similar for the frontend
Frontend-rendering and api
then fastAPI may be easier
I thought that fastapi can do everything what flask can do... But async...
Is it possible to make a website entirely out of Python and it's libraries. (Not only just for the back end, but for the front end as well.)
I do not think so, python can only be used on the server side, you cant run python on the client's computer.
in theory yes, but in practice using html and JS is much easier
really? even a gui?
you can run python on the client side, but it is a bad idea and highly untested
Brython
WOAH
yes some libs can generate html out of python
had no clue that was possible
But I dont think that you should use it.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return """
<h1>Hello, world!</h1>
<p>This was made in Python.<p>
"""
if __name__ == "__main__":
app.run()
Are you trolling right now?
.
How to do (with the math module) to create a program that knows when the square root of a number is impossible to calculate?
For some reason, the highlighted element (it says Hello but only the H is visible) doesn't show completely, even though it has z-index of 9999. What am I doing wrong?
hi guys i have a question, has anyone tried something of "compressing" an image before rendering it out?
i could compress before saving the file, but I already have alot of file uploaded
Anyone played around streaming using SRT technology?
idk about django and flask so anyone give me suggestion which one is best django or flask
Flask ig
what is the main difference between flask and django
?: (urls.E004) Your URL pattern [<URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
i am facing to this error after i made a media url and media root in settings.py
settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py :
static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT),
when a react component has a change in state, lets say a <p> tag inside a header component, will it re-render the entire header component or just the <p> tag?
just the <p> tag. Also, it is not technically "re-rendered", it's just that the content inside that <p> tag changes. The only things that "render" or "mount" are components, the rest is just virtual dom manipulation.
ahhh got it, thank you
if you're fetching images from your backend, I'm pretty sure PIL would solve that for you.
your creator_id field of your model has unique=True constraint. that means each creator_id must be unique (no duplicates). You're trying to input a creator_id which is already in the database and thus no longer unique.
python is just used for the backend, html is an entirely different language. You can serve HTML pages from a python backend (django / flask).
Yea I did a quick google and that seems to be the way to go, but I'll do it manually ( compress images manually before uploading them )
Thanks for the response
you can add it within your clean method (if you're uploading via form) to compress it before uploading/saving to database
?: (urls.E004) Your URL pattern [<URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
i am facing to this error after i made a media url and media root in settings.py in django
settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py :
static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT),
why do you want a media path in urls.py? any specific reason?
hello
I have a general question
I get that we need html and css to make a website
but is it optional to use JavaScript?
like what if i only use Flask?
becuase i face to 404 when i want to view a media file
yes, it's optional to use JS. You can serve plain HTML + CSS but having JS allows your sites to have much more interactivity.
I created a small site using html css and flask to route pages, it's very simple
Interactivity meaning? hovering arrow over certain element kinda of thing?
interactivity?
can flask not be used to do what js does? like making websites more modern/fance?
what is your MEDIA_URL & MEDIA_ROOT?
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
a dir
with HTML / CSS you have no client-side logic it's all server-side, with JS you have React, Vue, jQuery etc, they give the user more ability to interact with your site.
can you give us your url_patterns?
and flask cannot do that? does python only works on server side?
wait i get it
Is this the right section to ask about a crypto trading bot?
python is only installed on server, while each and every device has JavaScript!!!
depends! If you're making a web-interface for the bot (or anything related to the web) then yes. I'm also making a crypto-trading-bot atm 😄
Ah ok nice
Im a newbie sort of
So im having issues finding only the price of BTCUSDT
but javascript is so annoying, i hate learning it
Flask is a backend framework & handles backend logic. JS is mostly used for the frontend and handles frontend logic. That's VERY watered down, and JS has it's own uses which you can't replicate with python. If you want to take your websites to the next level, JS is a must.
JS is must.. i didn't know that. i thought it was related to java and i don't ever want to learn java
At a higher level, you'll start having JS frontends (e.g. React) which communicate with your Flask backend. (backends can also be in JS - I like Django too much to change though)
I don't think it's related to java
If you want JS for the web, learn React (does require knowing a bit of JS before-hand).
i understand that now
make an API call with python's requests module.
Its not that
Im using bybit API
And i am parsing the orderbook
But it has so much information
And i only need price
1 question, is it possible to make dynamic webpages like that of reddit or imgur, using flask but not using javascript???
i think answer is no.. right?
make the API call, serialize json -> dict:
response = requests.get(your_url).json()
then you can find the 'price' key (or whatever it may be) by parsing through:
for key, value in response.items():
if key == "price":
price = value
I also had to parse data, it's not fun but the API shouldn't be so complicated.
with Flask, to bring any updates onto the page you will have to refresh the page. that's not so great for "dynamic" websites. JS (and its frameworks) solves that problem
then
print(price)
well i never liked a language with curly brackets ..... but i guess there's no choice for JS. i have to start learning it properly now
when I was at your stage I also was learning Flask, I hated the idea of learning anything else. I hated Django at the time of learning it, plus I hated JS.
Now, I love the technologies. You'll learn to love it 😉
Sorry to interupt. If anyone is able to help with my django migrations issue I've asked in #help-grapes.
damn bro @opaque rivet . i was trying to avoid it. Thanks for clearing. i guess it will grow on me eventually
any suggestions on how to proceed?
it will... I literally remember going into this discord to say how much I hated to learn other things :D, haha.
right now i understand the basics, but i haven't designed anything
I learnt a bit off codecademy - I joined the Reactiflux discord then just started to do my own projects. I got the hang of it pretty quick. If you already know python then JS is not much different (just a bit different syntax for things).
oh you have no idea, i always switch to writing python syntx in a js script and then correct it again
@opaque rivet so how should i obtain only price?
parse through the data like I showed above
Do i need to include some library?
Also, are there any softwares out there that would make web designing process more easy??
like i don't want to start from scratch,
I don't know the structure of the JSON response you're getting. I wouldn't know how to parse the data from such limited info.
what do you mean by this?
"topic": "orderBookL2_25.BTCUSDT",
"type": "snapshot",
"data": [
{
"price": "2999.00",
"symbol": "BTCUSDT",
"id": 29990000,
"side": "Buy",
"size": 9
},
{
"price": "3001.00",
"symbol": "BTCUSDT",
"id": 30010000,
"side": "Sell",
"size": 10
}
],
"cross_seq": 11518,
"timestamp_e6": 1555647164875373
}```
And i only want it to print out "price"
like any softwares that have a UI to make/drag web elements and give them properties instead of hard coding everything
like wix?
it's cool that you're using websockets. I might have the move to bybit. wow! real-time updates huh? I was just getting JSON data from an API and it wasn't even in-sync that well 😂
anyways, you have your data. You can access the "price" key with:
price = your_data_dict["data"][0]["price"]
you have two events, a buy and a sell, the code above just selects the first one.
you can, e.g. webflow, but then you won't have the valuable skill of knowing how to code.
I'll learn code too, slowly. Any more examples? is wix same thing?
i don't know, I don't use them, I tried webflow just to try to build some quick UIs for my React apps but it didn't transfer across at all.
I would advise staying away from them.
okay good tip,
guess I'll try it once
This is wrong @opaque rivet
What did i do wrong here?
hello, I am looking for help on building pdf to audio converter web app as a final year project
right now i feel am way back in my journey, i need to learn a lot more
I don't know the bybit api. Whereever this dict is, parse through that to get your "price" as shown in a few messages above.
dictionary
Google has an awesome api that converts text into audio
try price = data["data"][0]["price"]
the vision api right?
if this is data, then data["data"][0]["price"] should work.
It doesnt 😦
if not try data["data"], see what that gives you, and continue
then I don't think data is the dictionary you showed me. data is a list (from the error), you showed me a dict.
Maybe turn it into json by dumping it first
It could be json format
But python doesn't know that
so i would say its safer to turn it into json ( just for the sake of it ) before querying any of them
it's not in this format. data is something else (and I do not have a clear idea of what the structure is from the pictures you sent me)
your error implies that data is a list.
Alright
How would i go about doing that?
while True:
data = ws.get_data(...)
data = json.dumps(data)
#what continues here
Then u can just use the data["data"] without this error popping up
print(data["data"]["price"])
If the file is like this, it will be a different case.
1 moment I'm on my.phone
Alright
Can u copy this here
"topic": "orderBookL2_25.BTCUSDT",
"type": "snapshot",
"data": [
{
"price": "2999.00",
"symbol": "BTCUSDT",
"id": 29990000,
"side": "Buy",
"size": 9
},
{
"price": "3001.00",
"symbol": "BTCUSDT",
"id": 30010000,
"side": "Sell",
"size": 10
}
],
"cross_seq": 11518,
"timestamp_e6": 1555647164875373
}```
Give me a min
No worries, no need to rush
hi
i got an question can someone help me
how do i backspace this is my code from selenium import webdriver
from time import sleep
driver = webdriver.Chrome(executable_path="/Users/Tollie Bonker/Downloads/chromedriver")
driver.get("https://www.instagram.com/")
sleep(4)
driver.find_element_by_xpath("//input[@name="username"]")
.send_keys("usrr")
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys("pass")
driver.find_element_by_xpath('//button[@type="submit"]')
.click()
replace json.dumps.to json.loads
its such pain typing code in phone
Ok
can u please help me?
Can u paste this here so i can modify this
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
api_key=None, api_secret=None)
ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
data = ws.get_data("orderBookL2_25.BTCUSDT")
data = json.loads(data)
##price = data["data"][0]["price"]
if data:
print(data["data"]["price"])```
ye rip
wait until im done
okey yes finelly 🙂
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
api_key=None, api_secret=None)
ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
data = str(ws.get_data("orderBookL2_25.BTCUSDT"))
data = json.loads(data)
##price = data["data"][0]["price"]
if data:
print(data["data"]["price"]) 
here ya go try this
Depends, what is your error?
i am an noob and i want to make it like do a backspace so i can type an new password
this is my code
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome(executable_path="/Users/Tollie Bonker/Downloads/chromedriver")
driver.get("https://www.instagram.com/")
sleep(4)
driver.find_element_by_xpath("//input[@name="username"]")
.send_keys("usrr")
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys("pass")
driver.find_element_by_xpath('//button[@type="submit"]')
.click()
but if the pass is wrong i want to backspace it
oof
Not a big fan of selenium haha ;p
F
i just started python like a week
how do i get better?
hmmmm
Id just quickly ctrl + a to select all and del
If you're trying some malicious stuff you should look into apis instead
sry bro thats to hard for my XD
but thanks
Do you know how to fix my error true?
Lets see
Alright, so a quick google and it seems like the error is produced due to a json data not being able to "recognize", and this is due to the fact that it contains single ' instead of "
I assume you are using this data?
Yes
1 moment then
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
api_key=None, api_secret=None)
ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
data = str(ws.get_data("orderBookL2_25.BTCUSDT"))
data = json.loads(json.dumps(data))
##price = data["data"][0]["price"]
if data:
print(data["data"]["price"]) 
@native tide
Hey
if this doesnt work
Try this
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
api_key=None, api_secret=None)
ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
data = ws.get_data("orderBookL2_25.BTCUSDT")
data = json.loads(json.dumps(data))
##price = data["data"][0]["price"]
if data:
print(data["data"]["price"]) 
I'm sure when I'm on pc you'll already finish this problem, but sure
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys("pass")
how can i make its doing it from an txt
your errors are because your data is the wrong datatype. If it is JSON, you have to parse it into a dict and then access the keys of that dict. If you don't know how to do that, you should do a python-based course.
from django.contrib import admin
class articlesAdmin(admin.ModelAdmin) :
list_display = ('title','describtion')
i want title and describtion from model be shown in the admin panel but it doesn't work
did you register it?
admin.site.register(...)
search for the correct usage on this on the docs.
yes
i did
can you show us that line of code?
from django.contrib import admin
from .models import articles
Register your models here.
class articlesAdmin(admin.ModelAdmin) :
list_display = ('title','describtion')
admin.site.register(articles)
the full code
ow i didn't put articlesadmin in the register()
I know how to
When i do it
Some of them are []
Some of them are the data
How would I clear a shopping cart when payment is authorised? I'm using flask sessions
can someone help me with something?
when i click on genres i can see the list
but when i go somewhere else and click again it says #
`<li class="">
<a href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
GENRES
</a>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
{% for cat in category %}
<li class="col-lg-2 col-md-4 "><a class="dropdown-item" href="/genre/{{cat.category}}">{{cat.category}}</a></li>
{% endfor %}
</ul>
</li> `
if driver.find_element_by_class_name("_2Lks6"):
sleep(4)
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys()
how can i backspace at the send keys??
How would I add an authorization header for nginx. I need it for a website
how to use flask as backend of react?
Hi, I do a google search with image:
import json
import time
import requests
import urllib
link_list = []
filePath = "/home/pi/Projet/vilian/image.jpeg"
searchUrl = 'http://www.google.hr/searchbyimage/upload'
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
response = requests.post(searchUrl, files=multipart, allow_redirects=False)
fetchUrl = response.headers['Location']
print(fetchUrl)```
She return a valid url <http://www.google.hr/search?tbs=sbi:AMhZZitnm6Iw1J7QYE5YhyOKmqFuKDQcYl0CUyzb4leuaS9OrtJSm4f613UthjD9tV3vsCbjOOY0XRFFMobEU1WDrgJRKS3OFNIibNGd5UV_17jlozB5NOGr_1dqWKhKq-e6tJCLHUbPHCckgPdmRXI-kKgTzQSFW3SDPMqWBPi-WLmHq6N2kcVlTPzdSVrHrxQo7lQHBXWMe3GNHnNslv3KiKdgL2oa0kMsvhOqc38FwKHil57ccYAQz1lGlfeTenjVBq_16H7CvwtJUHjsQy5GHulMGBVweYk1eQl-dKs-L81z2B4JQLms_1EMredscyagQzPgfloTyjIV>
```py
response=urllib.request.urlopen(fetchUrl)
html = response.read()
print(html)```
But when I download the page (for see resutl), she don't return the corect result. You know how I can get the right elements?
use it as an API
anyone know anything about using selenium and 2capcha that can help me with a project. I’m not asking just to ask but I don’t know anyone that really knows much about it so yk 🙂
If someone can and has the time — can anyone help me get Django + VueJS installed? I've tried doing things through NPM in the past, but for whatever reason it broke literally ALL my other Django projects..... I'm pretty bummed about it and have not touched it since. I just got asked to do something and I need to make sure I'm able to get this installed
I haven't even been able to get Vue going to do all that yet
I need to at least get the library installed
Is the site done?
I can do whatever else from there
The Django install is and it has its environment
I don't have Vue in and connected to it though
For Vue?
does someone know how does react link works? it's redirect without refreshing page, but how does that happen? it makes no requests at all...
Don't we need them installed and configured in the JSON?
import { Link } from 'react-router-dom' this thing
This is the part that's messing me up
Vue is going to handle the responsive stuff as well as the shopping cart
If push comes to shove, I'll just stick with jQuery. I just don't like using it anymore
no
you have the vue on yoyr main site since I assume it has everything ready ( link, router, etc )
then you will have Vue fetch the stuff and get post requests to your django backend
which will be hosted on another domain, sub domain, sub directory, etc.
hey there. I've been running into an issue with Flask while following up a book on building REST APIs with Flask and all of that. The issue is: TypeError: 'method' object is not iterable, and I just do not understand it, been reading up and down the whole code to try and see something, been looking over search results, stackoverflow, nothing really on that, and as I'm trying to learn about it, I can't get exactly what the error means...
so, if somebody would be likely to help me, I ask you to not only give me an answer, but also to tell me why and how xD
here's the endpoint code for the get method (which I believe is related only because of the word 'method' right there, if needed full code, I can send it tho)
@app.route('/authors', methods = ['GET'])
def index():
get_authors = Author.query.all
author_schema = AuthorSchema(many=True)
authors, error = author_schema.dump(get_authors)
return make_response(jsonify({'authors': authors}))
if __name__ == '__main__':
app.run(debug=True)
oh! and please, the discord is full of spamming messages, tag me up if you're trying to help me, please
is it a bad idea to deploy my api backend when im still developing/ working on the front end?
@fallen spoke if you have an ssl certificate you would ideally want to deploy an external app once its ready and secure, then work on the backend to avoid the hassle of switching from http to https or ws to wss etc, but be sure the api is secure
Ideally you want your front-end app to be served the backend to avoid configuring subdomains etc, do this only once everything is done tho, when developing its best to have the 2 run independently
@wooden ruin thank you, I was thinking of deploying the backend on api.mydomain.com and the frontend on mydomain.com since I am not sure how to serve a react project using django. is this a bad idea/ is it hard to set up subdomains? also, where do I get an ssl certificate? I have seen a few websites like cloudflare and godaddy but some of them have tiers and idk which one I need
Its easy to configure subdomains, but it depends on whether you want your api to be public and used by others, or only accessed when you say so (i.e. fetch, axios, etc). Also, you can compile your app to be served from anywhere, simply by loading the html file. On vue this command is npm run build, but it may vary. Find the option that best suits your needs and work from there
thank you so much
im running into a few issues with django. would anyone mind me pm'ing them for help?
Or you can just ask the question
why is my template not showing up, why is my css file not showing up, why is my url pathing giving me weird results?
<link href="./bootstrap.css" rel="stylesheet">
Not sure how to get the file location when the html template is in the same directory as the css file, which all the combinations I've tried didn't work.
the url patterns and views are as follow (this is app urls, not root):
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name=''),
path('about/', views.about, name='about'),
]
now root urls:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Blog.urls')),
path('about/', include('Blog.urls')),
]
and my views:
from django.shortcuts import render
def home(request):
return render(request, 'Blog/base.html')
def about(request):
return render(request, 'Blog/base_about.html')
i can see two about pages and only one index and one admin, which is weird because i would assume if im getting two abouts, i should get two indexes. (the '') but when i try to actually view them i get errors
when I click blog on my page:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/base.html
also no template loading up
c44g
what is the best way to implement single string match search in django
when I googled I got to know about haystack . but for the server what is the best one , whoosh or elastic search .Does Anybody implemented this before !!
okay now my links are working, just my templates aren't rendering still
What is your templates path? Where is the html located
And is there any error you can share?
guys this is a very tough question to find a solution to, I am trying to follow discord's architecture with django. can someone please help me here?
https://stackoverflow.com/questions/66686187/drf-discord-like-role-permissions-checking
Hey
with flask im making a Rest api, How would i get the requests json? (when you make request like requests.get(url, json={}).)
there no such things as "best"
It really depends on what your use is
for example SQLite is good for small or demo bapplications
And mangodb?
And Mongodb is NoSQL database so it really depends whether you wanna work with a SQL or NoSQL database
:c
Hello is there anyone here who previously used Node and ExpressJS and suddenly switch to flask or django
how easy is it to use compare to two of that I'm using ReactJS in Front-End I can't easily grasp the idea on node and express :/
How would I add an authorization header for nginx?
how to debug 405 error i get for post: requests.post(url, data=json, headers=headers) ? thanks!
that means POST not allowed
on that url
thanks! is there a way to check what methods are allowed?
If you have documentation of APIs, that is where I would look first
But doing OPTIONS on url should return Allow Header
The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (*) to refer to the entire server.
unfortunately don't have tha pi docs. i will check options thanks a lot!
oh, great, it shows me only PUT is allowed
thank you @fallow void !
@lapis stratus What is specifically that youu don't grasp?
making this in nodejs and express
Something like that
I can only wrote few data on the tutorial I'm following
How i can insert video in column using for statement ?(django)
<h1 style="align-content: center;color: aliceblue;font-weight: 900;text-decoration: underline;">Python Lectures</h1>
{%for v in vide%}
<p style="font-family: monospace;color: bisque;font-size: x-large;">{{ v.video_name}}</p>
{% video v.video "small"%}
{% endfor %}```----> This is code
@lapis stratus I am afraid you have to elaborate your question a bit more, I don't get if you're struggling with:
- Getting data out of the db
- Parsing that data into the JSON structure to be returned
- Something else
How would I add an authorization header for nginx?
@strong torrent Did you check this (https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-subrequest-authentication/) section of nginx docs?
Um no
can clear my doubt?
I will try
You want to make each item in the loop display in it's own column?
Yes
It's my second account
Are there any good non-blocking ODM DBs using MongoDB that work well with Django?
idk why you want non-blocking and Django
All of Django's orm and database infa is blocking
You can use a table, make the entire loop within a <tr> and each item within a <td>
Ah, I was hoping to use Django as a testbed for using a nonblocking ODM for Discord.py as well but that's fine, what are the best packages for MongoDB integration in Django?
I remember using Djongo but ran into issues after a while with unusual behavior, not sure
Converting to "int" failed for parameter "pep_number".
hey guys
i don't manage to install whirlpool on a linux server, i need it for a flask web app
this is the error
solved
gunicorn ucp:app -b http://serveraddress.it:8000
guys what am i doing wrong? trying to run gunicorn
it says "serveraddress" isn't a valid port number, but if i use the numeric ip it works fine, but it isn't on the alphanumeric address
because you're trying to use a domain name instead of the host machine ip
when you're running a server you're either running on localhost or exposing the ip to the whole network
anything like domain etc... isnt the responsibility of the webserver
you either bind to 0.0.0.0 (publicly exposed across the network) or 127.0.0.1/localhost
the hostname resolution is the job of your DNS and nameserver
oh i see, i'm not working on the server, i just made a flask app for a guy who is working on the server
so he should either bind the address.ip on 0.0.0.0 or localhost?
yes
gotcha thanks!
Hi, does someone for which reason do I hac this error? Here are my model and form files :
from django.contrib.auth.models import User
from .validation_taille import validate_file_extension
# Create your models here.
class Videos(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE,null=True)
caption=models.CharField(max_length=100)
Video=models.FileField(upload_to='video/%y',validators=[validate_file_extension])
def __str__(self):
return self.caption
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Videos
class UserRegisterForm(UserCreationForm):
class Meta:
model=User
fields=['username','password1','password2']
class AuthenticationForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'username','placeholder':''}),
label='Utilisateur')
password = forms.CharField(widget=forms.PasswordInput(
attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':''}),
label='Mot de Passe')
class Meta:
model=User
fields = ['username', 'password']
class Video_Form(forms.ModelForm):
class Meta:
model=Videos
fields=('caption','Video')```
I don't see a user_id item in either class.
hey ,
I am having a serializer relation defined in my serializer class like below
class OptionsSerializer(MongoSerializer.DocumentSerializer):
modifiers = ModifierSerializer(many=True, read_only=True)
class Meta:
model = Options
fields = [
"id",
"name",
"description",
"price",
"modifiers",
"type"
]
Here's my models.py
class ModOptions(EmbeddedDocument):
name = StringField(max_length=100, required=True)
price = FloatField(required=True)
class Modifiers(Document):
name = StringField(max_length=1024, required=True)
options = ListField(EmbeddedDocumentField('ModOptions'))
is_used = BooleanField(default=False)
is_used_counter = IntField(default=0)
class Options(Document):
name = StringField(max_length=100, required=True)
description = StringField(max_length=1000, blank=True)
price = FloatField(required=True)
modifiers = ListField(ReferenceField('Modifiers'))
type = StringField(max_length=100, blank=False)
is_used = BooleanField(default=False)
is_used_counter = IntField(default=0)
I am using django rest framework mongoengine.
If remove my serializer relations, The api works fine, But with the serializer relation I am unable to create or update document.
I need some help with this 😮
how to handle ? in flask url
order/payment/complete/bulS83v********/?token=157*********&PayerID=C*******3AG
@order_bp.route('/order/payment/complete/<string:order_id>/<string:token>/<string:payer_id>', methods=['GET'])
if I remove the question mark, the route loads fine, however if I don't, then it just returns a 404
A question mark starts a set of query params, you might need code to look for the query params in the dict that flask should construct for you... it shouldn't automatically return 404, that's odd.
You're kind of asking "should I choose Javascript or should I choose Python" here. Simple or complex is going to be determined by the language you use.
yeah I got it sorted now, the url I had paypal redirect to had an additional '/' so it was expecting something else instead of query params
hmm.. but i suppose in terms of features? if you had to choose one between express or flask? leaving out django cuz i think its a bigger framework out of those 2.
If I had to choose express or flask I would choose flask because this is the Python Discord. 😂 But also, python is the language I know better. Express and flask are fairly similar in terms of direct features, but they sit on top of completely different languages. Choose your language first, then choose what's best for that language.
ahh i see, thanks 😄
i was curious cuz im learning react and trying to choose a suitable backend for it. I am fairly good with flask since ive built several projects with it
What is the best package to integrate MongoDB in Django?
Hi, how can i use javascript variables inside a php file?
anyone have experience deploying flask apps?
just use a script tag and put the js inside the script body
<script>console.log('it works!')</script>
this a python channel tho... codeing den has a javascript sub
guys i'm trying to run this flask app with gunicorn on a domain
the domain is done with plesk obsidian
i can't change the ip of the domain in order to make it local or 0.0.0.0
it has its own ip and although i'm using it for running gunicorn, it works with the numeric ip but not the domain name, probably i'm failing the port, but i don't know what port it has
Thank for the response, let me give you a brief description of what I'm trying to accomplish,
A user checks a check box => JavaScript asks for location permission and then console.log(location),
Now this is what i want to do next with location variable,
Location variable should go to php file (test.php) and then test.php should echo location variable.
I'm a little confused how it can be done, JSON? Ajax ? I don't know, please guide me
That server is full of newbies and teens 😂 I've never got any useful help from that server
read the docs man... u sound like a noob too... developer.mozilla.org
we all gotta learn... no matter how experienced... youre asking really basic questions that can b answered in the docs tho...
Read the docs of what? I didn't expected that sort of answer here,
Nevermind, someone else would help me.
@opaque rivet what you're upto?
Wherever you instantiate OptionsSerializer, could you see if it's returning any errors?(OptionsSerializer.errors)
From the surface, I can't see any errors. Are you providing a list for your modifiers?
never tried PHP, but if you're working on the backend you can make an API, and then make a request from your JS script (including the data you'd like to send) which can then be accessed by your PHP backend.
Oh okay, not the exact answer i was looking for but thanks
what was the answer you were looking for?
hello who know well django ?
https://dontasktoask.com/, ask the question and more people will be able to help you
ok sorry friend
i have this error but i dont understand wht
personne is link to user
it means that the class from which you are trying to access first_name does not exist, it is a NoneType.
It looks like you're trying to access the user from request.user, or similar, right?
user.personne.last_name
the error means that user.personne does not exist
class Personne(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="personne")
chartes = models.ManyToManyField(Charte, through='CharteSignature')
def __str__(self):
personne = self.user.first_name
return personne
@opaque rivet now you can see
okay, and your view?
is the admin panel friend
not a view
well it looks like your Personne instance is not linked to a user.
yes but this ?
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="personne")
having a field on a model does not mean it's populated, that's your job. user is null.
you say the table is null
i have two user
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="personne")
The user field of your Personne instance is null
you need to assign a user to your Personne instance. But yes, you should make null=False if you need each Personne to have a user (which you have to assign yourself).
i have already make signals @opaque rivet
but when i want to migrate i have error with admin_interface
ModuleNotFoundError: No module named 'admin_interface'
def get_access_token(code):
payload = {
"client_id" : Oauth.client_id,
"client_secret" : Oauth.client_secret,
"grant_type" : "authorization_code",
"code" : code,
"redirect_uri" : Oauth.redirect_uri,
"scope" : Oauth.scope
}
access_token = requests.post(url = Oauth.discord_token_url, data=payload).json()
print(access_token.get("access_token"))
my access token returns null but i dont know why
im working off of discords api
Hi, how do i make table generator. I mean, when something happen, it will generate new table to site with new stats, and the old ones will remain
I'm trying to go start a new DB but when i try to make migrations from scratch on it it keeps saying django.db.utils.ProgrammingError: relation "fighters_fighter" does not exist
o ty
Hi, have been struggling with getting test data into Django from csvs, for weeks now 😄 I am trying to import test data into the car inspection django model, I attempted via django admin and csv import, and also via python scripts but since tables are all related, one to many, many to many, I struggle to get the test data that is also been related imported to the django model (in sqllite). Doesn't make sense!
help would be awesome!
Can i write html into html? like ```py
file = open("sample.html","w")
file_to_add = open("adding_html.html", "w")
file.write(file_to_add)
file.close()
the new one?
its just a clean DB
its an empty db
well i actually think ive solved it, I had a certain migration i probably did incorrectly somewhere
i pulled my inital git version and redid the migrations one commit at a time and now its.. working ;-;
well for now, ill continue to keep pulling and migrating
hoping it doesnt break
thanks for the help anyways!
dammit
I went commit by commit making clean fresh migrations
and it worked on that db
I started a new db to test, and when i try to python manage.py migrate on that DB i get the same problem
anyone?
try delete all your migrations, and retry
did you delete your db also?
where could I get linux help ?
what is the difference between using a custom view template in django and a "generic view"
I've a problem. I need to parse the site via request. When program parse, site sends a page with error 414. I suppose, it's antiparsing system. How i can get around this system?
hiii guys any good apis to test and play around with?
Hi, can you suggest some good free services to host my django
web app?, thanks
heroku, vercel
Doesn't heroku reset the environment after a certain amount of time?
dont think so
yes
but why does that matter
@toxic flame dog api! free, easy to use and understand. Good practice for using fetch, axios etc
won't the db reset and the users will need to register again?
I wouldn’t run something where you are having users signup and save data like that on a platform like heroku