#web-development
2 messages · Page 65 of 1
Okay
and as a backend developer its a must
@nova storm Do you understand the django basics?
Django docs has its own poll tutorial on their website you should follow. Two other great resources are
https://www.youtube.com/watch?v=UmljXZIypDc&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
and
https://tutorial.djangogirls.org/en/
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/Core...
When I try to open my view I get an Unauthorized error, this is my view function
class UserProfileView(MethodView):
def get(self, user_id):
user = models.User.query.get_or_404(user_id)
return render_template('users/user_profile.html', title=f'{user.username} Profile', user=user)
nvm
I fiund out the reason
I really should be more careful
hi
my html form
is not POSTing
im using django
but its not on django's side
its on the template side
https://pastebin.com/yK0cbRU3 my template
@terse surge doesn't the method in the form tag need to be:
method="POST"
in caps?
iirc caps are important.
Anyone in here who want to help out with creating a fast-api boilerplate? I've added the basic building blocks at https://github.com/nymann/fast-api-template :-)
nice! If you wanted, you could probably make it into a cookiecutter, which has a decently sized community around it https://github.com/cookiecutter/cookiecutter
@cold anchor I really dislike cookiecutter, maybe it's cus of ignorance but the main features is replaceable via a shell script? 🤷♂️
#!/usr/bin/env sh
rename_to=${1:?"Specify what the project should be renamed to."}
rename_from=${2:-boilerplate}
git grep -lz $rename_from | xargs -0 sed -i '' -e "s/$rename_from/$rename_to/g"
mv $rename_from $rename_to
I just find that it destroys imports and makes testing harder? Maybe I am doing something wrong though.
@terse surge doesn't the method in the form tag need to be:
method="POST"
in caps?
@abstract python no, i have another version of a working form and i use method="post" and works fine, ive tried it, no results.. i did some investigation and it posts the data but doesnt executes code
ah, fair enough then. I've always used "POST" and figured there was a reason for that but I couldn't remember what it was haha.
obviously just personal preference on the part of whoever taught me
@buyer_bp.route('/dashboard/<username>', methods=['GET'])
I have this route. I want to know if it possible to hide URL parameters on the front-end ? So lets say the user goes to /dashboard/oy, it would only render /dashboard on the front end
The reason I want to know if I can do this is I have Buyer & Seller, but I want both of them to have access to their own /dashboard but I can't have two routes with the same URL, so I have resorted to adding /username to both routes. But I only want /dashboard in the URL
@past cipher I don't exactly know how (I'm still quite new to Django) but couldn't you use the same dashboard, and then display different content on it depending on whether the user is a buyer or a seller?
Like, if User's Group = Buyer, show this content block:
elif User's Group = Seller, show this content block:
Then all you'd need to do is make sure the user was in the correct group.
Hello guys!
I need some help.
I am trying to create a nested route for my DetailView that would return a random instance of a nestedField in my model instance, and I am not sure how to do it exactly.
Here is my code:
parser_classes = (FormParser, MultiPartParser)
queryset = Breed.objects.all()
serializer_class = BreedSerializer
pagination_class = None
class BreedDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Breed.objects.all()
serializer_class = BreedSerializer
pagination_class = None
class BreedDetailRandom(generics.RetrieveUpdateDestroyAPIView):
serializer_class = BreedSerializerRandom
def get_queryset(self):
return Breed.objects.order_by('?')[0]
from django.urls import path
from Breed import views
urlpatterns = [
path('breeds/', views.BreedList.as_view()),
path('breeds/<int:pk>/', views.BreedDetail.as_view()),
path('breeds/<int:pk>/random', views.BreedDetailRandom.as_view()),
]```
Does anyone here know how to activate the key enter or return in selenium.
If so could you please dm me.
hi, im gonna scrap a website but for details i want to get from website i have to log in to the website, how can i do that with beautifulsoup
you cant login to sites using bs4
@native tide You have to analyze how the authentication works with the site. bs4 is a XML/HTML parser, it won't help you there. Authentication is more about forming your network requests as the site expects them to be. By exemple, you would have to provide username and password, to receive a token and then provide token to each request through the headers of the request. But that entirely depends on how the website implements authentication.
Looking at the previous messages about this 'site' it seems very clear that it does not want people automating logins
soup.find("p",attrs={"dir":"ltr"}).select("img") how can i get img src ?
Guys what is good flask module for showing videos?
Ummm that's my question too but in django
xD
hello
ive identified the error
but
dont know the fix
im using jquery to hide specific fields for specific options chosen
meaning that
it will send empty post data for these options
how exactly can i fix it without removing my js code?
found a solution
default data
how can i download the full web page with py?
@abstract python yeah thats why I did, thanks
Anyone here pretty good at flask/working with jinja templates and dictionaries?
I need help with setting up PaypalRestSDK. I understand what it does but I just dont know how to use it properly. I have used the examples given. How do I add this to my site (I am using Flask).
Guys any idea how I can achieve this:
Seller creates a service. They list the information, the available "Services" with the price. I now want to include a calendar with time frames. So the seller can choose what days (mon-fri) they will offer the service, with 1 hour time slots. If a customer purchaes, it will remove that timeslot.
I am using WT-Forms - I just don't know how to achieve this using form element
i cant help u directly but
put on ur favourite music
without images because it will ruin ur focus
break it down
ask yourself how it will work
and u could make it yourself
yeah good idea, will try break it down step by step
thats what i usually do and end up with it being better than i thought
Assuming I'm new to django, and reasonably new to working with databases, is it worth trying to learn SQLite, or should I install something different before I get to involved with it? Is it the kind of thing I'll have to re-learn entirely if I switch to PostgreSQL (which everyone else seems to use) or MySQL (the only one I've got any personal experience with)
or is it one of those "for now just stick with what comes in the box and learn others later" kind of things? I'm guessing SQLite will have zero real-world use.
I have a select field for a searchjng category, queries differ based on the category, should I use if loops or is there a better way?
Hello everyone,
I was wondering if someone know why my field for uploading pictures is like this? I can't select new pictures from my computer to upload, only ones already uploaded in the model instances through my Admin panel. It looks this way on my all of my routes.
For some unknown reason to me, my form is not getting saved at all?
The server sees the POST request and it's status code is 200?
Views:
from django.shortcuts import render
from .models import Post
from .forms import NewPostForm
import logging
logger = logging.getLogger(__name__)
def index(request):
posts = Post.objects.order_by('id')
return render(request, 'home.html', {'posts': posts})
def addPostView(request):
form = NewPostForm(request.POST or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, 'new_post.html', context)
Forms:
from django import forms
from .models import Post
class NewPostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['age', 'gender', 'content', 'image']
Model:
from django.db import models
from django.utils.translation import gettext_lazy as _
class Post(models.Model):
class Gender(models.TextChoices):
FEMALE = 'F', _('Female')
MALE = 'M', _('Male')
OTHER = 'O', _('Other')
id = models.IntegerField(primary_key=True, auto_created=True)
age = models.IntegerField()
gender = models.CharField(
max_length=1,
choices=Gender.choices, null=True, default=None)
image = models.ImageField(upload_to="posts/")
content = models.TextField()
ip_addr = models.GenericIPAddressField()
timestamp = models.DateTimeField(auto_now=True, null=True)
@limber laurel do they click the button and then it searches the DB, or do they click it > submit form > then you return results ?
if its the first, you could do a fetch function onclick
Is web-design similar to front-end development? I'm studying Django for half a dozen hours a day, JavaScript for another couple, and I'd like to start squeezing in HTML/CSS (Though I've picked up a good amount just from making templates)
I found a book titled "Learning Web Design" that seems to teach HTML/CSS.
From my understanding, webdesign was just the design of a site, then you pass that to the developers. I'm sure you need to know SOME HTML/CSS/JS, but not much.
If im interested in doing mainly backend work, should I bother with a 1000pg book on webdesign?
web-design and web development are not the same
you should probably know html/css even if you are back-end though
That's the plan. I want to know enough to make presentable/mockup templates.
Think I'll look for a book that teaches HTML/CSS from the developer perspective then. Thanks!
I prefer working with the back-end, although i do know HTML/CSS/little bit of JS. I recommend freecodecamp if you're completely new to HTML/CSS
also coles bootcamp on udemy
if you're wanting to build quick mockups, you could also use bootstrap
@past cipher I mean I query it in a function in my form, I currently use if loops to check what was the input for the dropdwon menu
As I have 3 different dropdowns each resulting ina different query
can i see some code
class ProductSearchForm(FlaskForm):
search_name = StringField('Search Product', validators=[DataRequired()])
search_type = SelectField('Select a Category',
choices=[('seller', 'Seller'), ('product_name', 'Product name'), ('id', 'Product Id')],
validators=[DataRequired()])
def get_results(self, search_name, search_type):
if search_type == 'seller':
return Product.query.filter(Product.seller_username.contains(search_name))
elif search_type == 'product_name':
return Product.query.filter(Product.product_name.contains(search_name))
elif search_type == 'id':
return Product.query.filter(Product.id_product == search_name)
else:
return CoreException('Invalid Input Selected')
Ok, this is my current solution @past cipher
def calculateWeight(self, a, b):
pointA = Point.objects.get(account=self.account, latitude=a[0], longitude=a[1])
pointB = Point.objects.get(account=self.account, latitude=b[0], longitude=b[1])
if Distance.objects.all().filter(account=self.account, pointA=pointA, pointB=pointB).exists():
return Distance.objects.get(account=self.account, pointA=pointA, pointB=pointB).distance
distance = sqrt((int(pointB.latitude) - int(pointA.latitude))**2 + (int(pointB.longitude) - int(pointB.longitude))**2)
Distance(account=self.account, pointA=pointA, pointB=pointB, distance=distance).save()
return distance
Any idea why this is causing me this error:
Point.models.Point.DoesNotExist: Point matching query does not exist.
@hollow flower For function-based-views, I always use the if request.method == 'POST': approach
@login_required
def v_create_image_form(request):
""" Display a form to create a new image or process a POST form """
if request.method == 'POST':
form = ImageCreationForm(data=request.POST)
if form.is_valid():
cd = form.cleaned_data
# The custom form.save() method that will also download the image
new_image = form.save(commit=False)
# Assign the current user to the Image object
new_image.m_user = request.user
new_image.save()
create_action(request.user, 'bookmarked', new_image)
messages.success(request, 'Image added successfully')
# redirect to the newly created item
return redirect(new_image.get_absolute_url())
else:
# Build form with data provided by the bookmarklet via GET
form = ImageCreationForm(data=request.GET)
context = {'current_section': 'images', 'image_form': form}
return render(request, 'images_app/image/image_create.html', context)```
I think trying to do it in a single line when creating a form instance is probably messing with you
I did try that approach, but it didn't work either but I can try that again if that does it.
A few messages up is my problem. @honest dock
For function-based-views, I always use the
if request.method == 'POST':approach@login_required def v_create_image_form(request): """ Display a form to create a new image or process a POST form """ if request.method == 'POST': form = ImageCreationForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data # The custom form.save() method that will also download the image new_image = form.save(commit=False) # Assign the current user to the Image object new_image.m_user = request.user new_image.save() create_action(request.user, 'bookmarked', new_image) messages.success(request, 'Image added successfully') # redirect to the newly created item return redirect(new_image.get_absolute_url()) else: # Build form with data provided by the bookmarklet via GET form = ImageCreationForm(data=request.GET) context = {'current_section': 'images', 'image_form': form} return render(request, 'images_app/image/image_create.html', context)```
@molten quarry Yup, that approach does not change anything. It still gives me HTTP status code 200, but no entry in db.
Assuming I'm new to django, and reasonably new to working with databases, is it worth trying to learn SQLite, or should I install something different before I get to involved with it? Is it the kind of thing I'll have to re-learn entirely if I switch to PostgreSQL (which everyone else seems to use) or MySQL (the only one I've got any personal experience with)
@abstract python if youre planning using like remote databases, or sqlite, u dont really need that db knowledge, u just do py manage.py makemigrations & migrate
What's your template and urlpattern look like?
There's the view template.
{% extends "base.html" %}
{% block description %}Find New Friends | Löydä uusia kavereita{% endblock %}
{% block title %}{% include "_brandname.html" %} :: Uusi postaus{% endblock %}
{% load crispy_forms_tags %}
{% block container %}
<div class="container">
<section>
<div class="row">
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit">Post</button>
</form>
</div>
</section>
</div><!-- /.container -->
{% endblock %}
What do you mean by urlpattern? urls.py?
Yup
The patterns.
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include, path
from . import views
# Personalized admin site settings like title and header
admin.site.site_title = "TheFriendships Site Admin"
admin.site.site_header = "TheFriendships Administration"
urlpatterns = [
path("", views.index, name="index"),
path("new-post", views.addPostView, name="post_view"),
path('<int:id>/', views.single, name="single"),
path("admin/", admin.site.urls),
]
# User-uploaded files like profile pics need to be served in development
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Include django debug toolbar if DEBUG is on
if settings.DEBUG:
import debug_toolbar
urlpatterns += [path("__debug__/", include(debug_toolbar.urls))]
And I'm currently using sqlite if that matters.
Well everything looks fine to me. Only issue that I see would be it not passing the is_valid() check. Though it should notify you. You tried removing it and seeing what happens?
Getting rid of the validation check, I get an error related to it.
The Post could not be created because the data didn't validate.
Hmm. Have you tried using the shell to create an object? I'm assuming you already checked there to see if it was created.
I tried to create it in Django admin and it does get created on the admin site, but not though the form.
OH, it might be my little IP_Address field that's not getting populated so it's not validating.
I need to save the poster's IP with a hidden field was my idea.
Yeah, It's not it.
I was able to create the object in Django console and save to db.
Does anyone know how i can secure my python flask site (on Heroku). So people aren’t be able to mirror my site.
I can't find a guide ANYWHERE that goes over how to setup Apache/Varnish CDN or Apache/Apache Traffic CDN (or any other DIY CDN)
I did find a single guide each on YouTube but one is like 4 years old & really shitty, & the other uses AWS & all of its features (which I'm trying to avoid)
I know BunnyCDN, MaxCDN, etc. exists but I rather learn & create one myself for future use/knowledge
Anyone got any suggestions/resources? Or am I SOL?
@fickle fox check the value. if your radio button has a name of 'radio-btn' then do:
if request.form.get('radio-btn') == None:
print('radio btn has no value')
You could also add a required validator in your form
@molten quarry you should really have get/post in different routes
np
Is there a good way to pass a dictionary from a jinja template to a flask view?
{% for a in apps | sort(attribute='title') %}
<tr onclick="window.location.href = '{{ url_for('apps.app_info', app_id=a.name) }}';">
<td>{{ a.title }}</td>
<td>{{ a.description }}</td>
<td>{{ a.categories }}</td>
<td>{{ a.platform }}</td>
</tr>
{% endfor %}
I'd like to pass the dictionary object that is a back through into the next view.
With Django is it better to convert a csv file to where it's in a sqllite database or just continue using the csv file instead?
how are you using the csv file?
What are you guys using for virtual enviornments? I started by using the built-in venv, then switched over to pipenv. However, I just finished a chapter in my book, and when I went to duplicate the files for the next chapter, I saw that nothing got written to my pipfile. Haven't been able to fix the issue. Seems the new release crapped me out. I could roll-back, but I had other issues with the prior release. So now I just wanna switch out entirely.
@cold anchor It's a kaggle of every movie/tv show on netflix. I'm grabbing data from the kaggle (title, runtime, genre, date added to netflix,) to display on the web app itself as seen here https://themoviematcher.herokuapp.com/
Just that that link isn't django, or the current version I am working on now
Im working on making it add the movies/shows that are liked to a users profile so not sure if using a database or just the csv like I currently am is better for that
For storing and later displaying user data, you definitely want to use a databse.
Well time to learn sqllite tonight LOL
You don't really need to learn SQL for Django. Django uses its own special code to interact with the database.
Not even sure if there's an option to use SQL within Django
Though knowing some SQL has definitely helped me make sense of what Django is doing.
If you're going to learn SQL, might as-well learn it using PostgreSQL.
I'd definitely recommend learning the basics, queries, insert, update, delete, indexes and leaning on Django's ORM like fishy mentioned
it's hard to make sense of a SQL ORM if you don't know SQL
has anyone used Permissions with Django before?
class EmailNotUsed(permissions.BasePermission):
message = "Email is already in use"
def has_permission(self, request, view):
return not Account.objects.all().filter(email=request.data['email']).exists()
It works, but the message I'm getting is:
{
"detail": "Authentication credentials were not provided."
}
Alright so I'm trying to setup my own custom CDN using Varnish
This is the following setup I have planned
The following assumes:
- The Varnish Origin server is on the same server as the web server (Apache in this case)
- You have 2 Varnish Cache Servers, one in NA, & one in EU
NA Client --> Varnish Origin Server --> NA Varnish Cache Server --> If result NOT IN cache --> Return Origin Server results --> Input request data into NA Varnish Cache Server
EU Client --> Varnish Origin Server --> EU Varnish Cache Server --> If result IN cache --> Return EU Varnish Cache results
Any suggestions? And where would I insert Nginx/HAProxy in order to terminate SSL, since Varnish doesn't accept HTTPs?
OK guys, what are Jinja2 variables???
@vivid rose Legit just do . for the key
if i have
context = {'bob': {'age': 16, 'name': 'bobby}} -> bob.age would give -> 16
Hey guys I have a question, how would I change the value of a session variable?
E.g I want to change the value of session['channelname']
Sorry forgot to mention this is flask
What if Im trying to assign it the value of a variable
Can I just do = x?
Because thats what I did and it reverts back to the first value
yes you can do that @noble plinth
show some code, i will try check why it reverts back
1 sec
@app.route("/channels/<string:current_channel>")
def channel(current_channel):
try:
channellist = User(session.get('username'),allusers).getUserChannel()
if current_channel in channellist:
session['channelname'] = current_channel
return render_template('chat.html',username = session.get('username'),current_channel= current_channel,allchannels=channels, userChannels=channellist,messages=channels[current_channel]['messages'] )
return render_template('chat.html', username = session.get('username'),current_channel = 'Main',allchannels=channels, userChannels=channellist,messages=channels[current_channel]['messages'])
except KeyError:
print(channels)
return redirect('/')
when I check inside here the session['channelname'] was changed no issue
@vivid rose Legit just do
.for the key
@quick cargo
That's not what I was trying to do. I would up being able to use a hidden form for it but thank you.
@socketio.on('isTyping')
def isTyping(value):
print(value)
emit('isTypingReceiver', {'user': value['user'], 'channel': session.get('channelname'), broadcast=True)
when I try here session.get
it gives me a either a null or the previous one
are you defining channelname session in any other route
no
that is the only one
I tried declaring it in a function
from flask import Flask, session
class User():
def __init__(self, username, allusers):
self.username = username
self.allusers = allusers
def userlogin(self):
if self.username in self.allusers:
session['username'] = self.username
return self.username
self.allusers[self.username] = {
'username': self.username,
'channels': ['main']
}
session['username'] = self.username
session['channelname'] = "main"
return self.username
def getUserChannel(self):
return self.allusers[self.username]['channels']
if I do this it will stay stuck as a main
if you print session['channelname'] does it return the correct value after setting session
if I don't it returns me a null
I don't know much about websockets, but could it be that the socket is created before the channelname gets changed ?
if you print
session['channelname']does it return the correct value after setting session
@past cipher do you mean after the session['channelname'] = current_channel? if that's what you mean yes it returns correct
I don't know much about websockets, but could it be that the socket is created before the channelname gets changed ?
@bleak bobcat that shouldn't be the issue because the top one works fine, but the istyping is not
right
it's still a route actually yea
if I were to declare it empty at the top would that be a solution?
like just in the pyfile session['channelname']
= ''
When do you start the websocket connection ?
I've not used websockets before, this is called using your JS file right ?
I can't see any issue in your route
yea
that is at the end of body right, so it loads after page is rendered
the js file doesn't seem to be the issue either
yup
only issue is the session['channelname'] keep reverting back
don't really understand why
is assigning a value inside a function the issue?
like it becomes a "temporary" changed variable inside the function
try what you suggested making it an empty session first, but I'm not sure why that would work when you're setting the new session anyway
to check if its an error with your websocket, simply call the session variable inside jinja to see if it displays correctly
Well yea actually, where is that "session" variable coming from ?
from his user class
It comes from Flask directly on his user class, where does it come from on the view/controller ?
Do you have a from flask import session on the same file you have the app.route ?
yes I do
my other session works fine
I have another session variable other than that
Try adding session.modified = True in your app.route after you set the new channelname
@app.route("/channels/<string:current_channel>")
def channel(current_channel):
try:
channellist = User(session.get('username'),allusers).getUserChannel()
if current_channel in channellist:
session.modified = True
session['channelname'] = current_channel
return render_template('chat.html',username = session.get('username'),current_channel= current_channel,allchannels=channels, userChannels=channellist,messages=channels[current_channel]['messages'] )
return render_template('chat.html', username = session.get('username'),current_channel = 'Main',allchannels=channels, userChannels=channellist,messages=channels[current_channel]['messages'])
except KeyError:
print(channels)
return redirect('/')
like this you mean?
From what I looked up this is supposed to force the session to update
Hi guys!
where can i learn how to create production level API for social media
That depends on the rates etc...
How much throughput you needs
If you can live with slightly high MS response time async would be a good way to go with something like Sanic or Quart
which gives a massive amount of throughput per process
Sync systems tend to have slightly lower latency per request but need more processes for the same throughput
and depends on design of your API, sometimes you can scale horizontally
In Django, if I create a new model (Profile) and I want all existing users to have one, how do I bulk create each user their own Profile?
I would do it in the migration file
So would I do makemigrations, modify the file, and then migrate?
Yea
Cool, I'll give it a go. Thank you
hello , i am trying to write a graphql interface with graphene base and failing hard.
i want the query syntax like
{
"id"(1): {
name
desc
}
}
i am trying with interfaces but failing so far. anyone with graphene experience ?
its just a ex
hi, i have a little Question to Python selenium, I am trying to write a Programe which reades the Innerhtml from a Website, but the Problem is, the Errorcode AttributeError: 'NoneType' object has no attribute arise
Here is the Code: driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get ('https://gutscheine.chip.de/gutscheine/adidas-shop')
driver.implicitly_wait(5)
gutschein = driver.find_element_by_xpath('//*[@id="item-890974"]/div[1]/div[3]/div[1]/div[2]/div/span[1]')
gutschein.click()
driver.implicitly_wait(3)
code_element = driver.find_element_by_xpath('/html/body/div[6]/div/div[1]/div[1]/div[2]/span[2]/span')
code = code_element.get_attribute('innerHTML')
print(f"Code:{code}")
I am thinking of paginating with a show_more button, my current idea is to bacially have instead of the page being changed using the variable, have it so the amount that gets queried would be 20*page_num
Example
.paginate(1, 20*page_num)
instead of
.paginate(page_num, 20)
I am wondering, maybe there is a better way
Hi, i wrote this code using the requests library and when it runs, the exception that is caught (e) says 'tuple' object has no attribute 'get'
Does anyone know whats wrong with my code? Thanks!
r = None
try:
r = requests.get(url, headers=h, proxies=proxy)
except Exception as e:
print(e)
print('connection error..')
finally:
self.csrftoken = r.json()["config"]["csrf_token"]
self.ig_did = r.json()["device_id"]
print(self.csrftoken +"\n" + self.ig_did)
return True
how are you importing requests?
how can i have this server's template please
If I remove a Django model that has data, how do I safely remove or migrate the data?
I've read some documentation on migrations but I'm still a bit lost
what do you mean safely? @celest torrent like save the data somewhere else?
@crisp saddle The data is in the sqlite database, if I understand it right. Can I edit the database to copy/paste the data and/or remove it or is there a safer way to do that?
It's 2 different things, removing it or backing it up. Which one do you want?
is there a way to include a functional app within another app's template?
I've got two apps on my test site; the blog from the Django Girls tutorial and the poll app from the Django docs tutorial. Both of which I've messed about with and changed a bit. The poll app now has a "latest questions" box on the right side which is it's own template that I've {% include %}'d into the base template. It works a charm.
I now want to include that same sidebar in my blog app.
I've done:
{% include "polls/questions.html" %}
and it does display the page correctly, however the app doesn't work; it's showing the 'no questions' message even though there are questions.
I guess this is because I've only included the actual template, and none of the inner workings of the app. What I thought I was doing was making a little 'window' into the polls app so you could see it from the blog. All I've actually done is copied some HTML. How would I go about making it work?
ohh, wait... I need to import stuff from the polls app in the blog's views.py don't I?
How can I scale a Flask app to hundreds of requests at once?
If I use Gunicorn or something will I be limited by the number of my cpu threads?
have it do less stuff per request?
Can't lol
I have ML models in there
you sent it an image, does some ML stuff, returns the base64 back
but if theres 8 things being done at once, the gpu will barely get to like 10% capacity
Kali, Gunicorn
hello
does anyone use Django ?
i have small project...
giving me some errors
need help
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
Normally you can do request.form which returns a dict essentially
django models
im not sure how to go over this, i have two options for getting images: one through upload and one through links, i only need one of the two to proceed
class template(models.Model):
template_img = models.ImageField(...)
template_url = models.URLField()
Normally you can do request.form which returns a dict essentially
@quick cargo i asked about query string parameters in url
The same way you get the 'something' value from POST except you replace POST with GET.
Hi, I am having an issue with my Flask application. I am trying to add a search engine to it so that even if only part of a title is typed the search will still find a match.
I am using psql for Database and have been successfully been pulling and pushing data into it from the Website.
I have been struggling with getting the data input through the search form to query on the database. I just tried as shown in the picture and all of a sudden. I am getting an error that DATABASE_URL is not set. although it has been working up until that point
Any help would be much appreciated
Or if someone knows a better method of creating the search engine
Ok, I recopied the database link from the site and it worked. Idk why, but yeah. So now I just have to sort out syntax bugs etc
Guys I need some help with my Django3 project.
Here is the situation:
Here is my project structure:
Here is the file giving the issue - the views.py in the home app (line 2).
try from .seamless.models import Item
also, why do you have an app inside an app(not come across such a strucure before, so just wanna know)
also, why do you have an app inside an app(not come across such a strucure before, so just wanna know)
@marsh canyon should I keep my applications in the root folder rather than in an apps folder?
Keep ur applications Independent, in ur case, u have an application inside the home application, u might want to move the seamless app to the apps dir
Keep ur applications Independent, in ur case, u have an application inside the home application, u might want to move the seamless app to the apps dir
@marsh canyon damn I did not even notice that! Yeah that is wrong. Thanks a mil.
I know its not web development but Does anyone know anything about mobile app development in python (kivy etc.) ?
(Don't really know if this is the right channel to ask this, sorry.)
Do I need to pay money to a hosting site or something in order to have access to a domain? I mean I have an apache2 web server running on a vps but the address is the vps' IP. Can I change that and have a domain instead of that somehow or do I need to pay money for that domain? I don't really know how this works domain stuff works
trying to make a todo app, I have priorities a user can select of "high" "medium" and "low", how would I go about putting those inside a model?
using Flask SQLAlchemy
@native tide You need to buy a domain name yes
Namecheap offers cheap domain names with the most reliable service. Buy domain names with Namecheap and see why over 2 million customers trust us with over 10 million domains!
@distant trout you could use a string field and use SQLAlchemy’s Enum field
(And directly put priority as a field on the Todo item model itself)
hello anyone has any idea what i am doing wrong
i'm trying to start my first django project
have you looked at the official django documentation?
yes i also updated it using git command
you should create a virtual env where your project folder is located
turn on the venv
then reinstall django
then run command
Hi. I'm working on a Django website. How do I pass form data to success_url? I have a form with a field name.
In my views.py I have:
class HomeView(FormView):
template_name = 'frontpage/home.html'
form_class = ContactForm
success_url = '/thanks/'
def form_valid(self, form):
form.seng_grid_go()
return super().form_valid(form)
class ContactSuccessView(generic.TemplateView):
template_name = 'frontpage/thanks.html'
In thanks.html I want to display 'Thanks, {{ name }}.' after the user submits the form.
How can I pass cleaned data to thanks.html?
Which third party token auth I should use with django rest framework?
whats library is best to use for web devlopment?
Can anyone help me with Flask? Im trying to run a python webscraper constantly while the flask server is running but I cant figure out how to do that or update my sql database?
I'm learning Django on windows and my textbook is teaching me about Memcached.
Problem is that it's not officially supported on windows. Can't switch to Linux right now because I have some windows programs I need to use throughout the day, so I'm looking for a solution.
I think dockers may be the answer, but I have no experience with them. After a brief youtube video explaining them, they definitely sound like something I want to use, regardless of if they work for this or not. I'm working my way through a tutorial right now, but just wanna get an idea of what I'll have to do to make this work. Will I need 3 containers (Django/python, Postgres, Memcached)?
Yeah, you'll need 3 containers.
Keep in mind that a virtual machine is also an option. A VM is probably more approachable than Docker.
Docker is useful to learn, but it might be too much to tackle at once when you're focused on learning about Django and memcached.
Got it, thanks for the clarification! I need to learn about VM's too, which I've never used, so if that's more straight-forward I'll probably just do that so I could, like you said, focus on the original goal; Memcahed
Hi everyone
I recently started learning javascript from The Definitive Guide by David Flanagan, as I came across the exception handling section I found out that I am actually learning the whole javascript with nodejs, and not what I really needed.
I came across this which says that prompt() and alert() are not part of node:
https://stackoverflow.com/questions/11618456/node-js-alert-causes-crash
What I am really looking for is some JS guide or book that focuses only on web development, not nodejs, I have python and flask for backend.
Now before I get another book, does anyone have any solid advice on what book should I follow for JS and the Web?
I am really confused, should I really learn JavaScript, the only place I wanna use it is as part of front-end dev since I am going for full-stack, what should I do?
Book buddies!
If it's not part of node, then it seems like you're already in the right spot. prompt() works in the browser, which is what we're going for (though the command is mostly obsolete since it can't be edited to match the stylesheet).
If you're going for full-stack, then yes you need JS. Front-end is mostly HTML/CSS/JS (JS being the only real programming language). You can't expect to do front-end work with no JS
Right @molten quarry , but do I need to learn the entire language?
It took me nearly a year to learn python, JS has a crazy syntax
I believe that this industry is too big for you to ever stop learning. You can spend your entire life studying and getting ready, but you'll die before you learn it all. Therefore, you should focus on learning things that will make you a more valuable and relevant asset.
Only knowing 1 language really limits your options and makes you easily replaceable.
And if you're going to work in web-development, especially full-stack, you need to learn the languages to do the job.
Right, thanks, I will continue the book now.
Honestly, it's a great book. I knew some JS before I started reading it, and everything you learn is very much applicable. It's just a little weird because JS only runs in the browser or in Node.
node is a tool that lets you run JS on your system (like python) instead of in your browsers console (which would suck for learning since you can't use a text editor)
js should only be used for scripting on webpages never for backend stuff change my mind
I mean... you ain't wrong... +1
In my mind, some JS fangirls just couldn't live without JS running on their system, and that's how we got node!
yeah imo node can go die in a ditch together with electron
like, i get it
js works for website stuff
but anything else becomes a hassle
learning a new programming language was not something I was prepared to do but I will try my best, I hope MySQL would be easier...
Once you the get the basic syntax of JS, you should try making a userscript with Tampermonkey. You'll be able to apply what you learned and see how useful it can be.
This was one of my first little scripts with JS...
It's a little script that parses a Steam game page and adds little youtube links for quick searching.
Simple, but its been very handy. I've made other things like it for my favorite sites. All in JS.
Sure, I noted it down, will try to create it, I got to know JS from capture the flag games, back there I could read it properly until I got into real javascript programming, I think I am learning the language from the bottom up.
Could be a long long journey before I actually create my website
Flask vs Django vs Express(NodeJS) for a web api with mysql: Thoughts?
Postgres > mysql
Personally prefer Flask of Django because of the lower level control you get out of the box
And it's less heavy compared to Django
Postgres > mysql
@quick cargo yeah was just an example
i prefer nosql a little more but yeah
sql is good as well anyways
Yeah I've been using mongo quite alot as of recent
Does anyone have good knowledge of socketio
DudeBro, FastAPI
How to append many items in a localstorage
And when it is used, all the items should be displayed
Flask vs Django vs Express(NodeJS) for a web api with mysql: Thoughts?
@peak bronze I've used Flask and now I'm learning Django. I've also used Starlette (FastAPI is built on this) on a larger personal project. What I've noticed through using Flask and Starlette and now learning Django is that in some cases I've almost reinvented the wheel in implementing features that are provided out-of-the-box and battle-tested by Django. In short, Flask focusses on offering a selection of features which is sufficient for smaller applications. It can be extended with other packages. For larger production-ready apps Django can save you time and offer you reliability in providing features like database migration and in-built security (I'm still learning Django so I'm sure people can add to this list)
lol yea
@peak bronze do you know how to use localstorage
okay
sorry fam
i dont know anybody specifically man, but i think there are a lot of people on this server itself who know how to use localstorage
ohh okay
check a ~~javascript ~~discord server as well
uh oh ive uttered the unholy word
in the python server
it was great knowing you PD
Is it possible to use form.ModelMultipleChoiceField with a list instead of a model/queryset?
The goal is creating checkbox multi-select with a list.
You would create a MultipleChoiceField and give it a checkbox widget iirc
ModelMultipleChoiceField implies the data comes from the model
Hey, so I'm using Flask for the first time on repl.it (since I'm on a school computor I cant install Flask) and I'm having an error with this code
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, main page <h1> Man </h1>"
if __name__ == "__main__":
app.run()
I get this address: Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
but when I paste this into google or edge http://127.0.0.1:5000/ It dosent work
What can I do?
Is it possible to send a Websocket message from a Django view? I’m using Django channels 🙂
Hey, so I'm using Flask for the first time on repl.it (since I'm on a school computor I cant install Flask) and I'm having an error with this code
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, main page <h1> Man </h1>" if __name__ == "__main__": app.run()I get this address:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
but when I paste this into google or edgehttp://127.0.0.1:5000/It dosent work
@woeful fable try running from the command line
python file.py
@peak bronze because its running on repl.it not your local host
127.0.0.1 is local host
you need to put "0.0.0.0" in run() to expose it to other requests and then to go to the site go to your repl share link
yeah
exactly
you need to set it to bind to the repl address
and to go the site you need todo go somthing like
https://<project-name>--<username here>.repl.co
It worked! Thanks a lot
you need to put
"0.0.0.0"in run() to expose it to other requests and then to go to the site go to your repl share link
@quick cargo
👍
in flask, how do u make an if...else if....else statement?
hey, I'm working on developping a website using Django and was wondering if anyone knows how I could deploy it using AWS (there's not too much info out on the web about this). Thanks
sure, I can help, how do you usually deploy a website? (how have you done it in the past?)
Can we use Celery/Redis with Dash ?
@gilded geyser you can use an elastic beanstalk instance to almost immediately have it online
in the past I've used aws lightsail and with wordpress deployed it that way, but now I want to deploy a machine learning algorithym on the website so I'm turning to django
If you are planning on doing calculations you might as well use AWS Lambda
Oh okay, so do I build the site locally and then transfer it over to AWS?
Or is there a way to build it through that service
through lambda?
Yeah
Lambda is a serverless solution
Take a look at this
It will help you greatly!~
Okay, thanks!
don't do ML on lambda
it's not going to be fun
I'd recommend getting your ML to run in a docker container and deploying that via AWS ECS
following situation: I have a JSON endpoint of an API (with bearer auth), but the bearer token does change weekly. When i visit the corresponding html page in a browser, i can open dev tools and see the JSON endpoint under XHR and manually copy the current bearer token. is it possible to automate that? I tried using requests but I didnt find anything useful in the returned response object
"I'd recommend getting your ML to run in a docker container and deploying that via AWS ECS"
That's what we are doing and it works wonder !
Anyone have a clue why doesnt my flask_wtf accept the csrf thats inside the headers
it's 2020 why are you using forms out of free will?
Im using vue.js on front end
Ok thanks for the advice!
@wind escarp I forgot to mention. The book you're using is a lot like reading the documentation. Very solid info, but not really hands-on.
If you want a more hands-on approach with exercises, might wanna look into the book "The JavaScript Workshop"
I'm about to watch a Django tutorial on youtube [1] but they use Python 3.6 and Django 2.2. Would I have a ton of issues following along if I use Python 3.8 & Django 3.0, or should I just install the specific versions he's using to be safe?
Python 3.8 will cause no problems, and 3.0 should be OK I think
Core Django functionality hasn't changed. You'll be good.
Holy crap that's a long video! When it comes to videos, I can't even focus long enough to watch a movie. That's commitment right there!
Django 3.x is grand, I've used 2.x videos as reference points, and they've been fine
Hello anyone is able to help with an import problem? I'm trying to import tensorflow but its sketchy on Repl.it so I tried it on my desktop, however, whenever I do "pip insstall tensorflow" on Command Prompt, it keeps showing an error message saying it can't find the version the install. I tried specifying the version to Tensorflow 2.2.0 since I'm running Python 3.8 but it doesn't work still.
I highly recommend the book "Django 3 by Example". I'm 90% of the way through it and its been amazing. I got my feet wet with another book (Python Crash Course) but this book just takes everything to a whole new level. Excellent job of showing you the many things you can do in Django (Also gives you experience with tools like celery, redis, memcached, jquery, etc)
@wind escarp I forgot to mention. The book you're using is a lot like reading the documentation. Very solid info, but not really hands-on.
If you want a more hands-on approach with exercises, might wanna look into the book "The JavaScript Workshop"
@molten quarry Thanks, sometimes the author doesn't say what to do, how to use functions but I figured them out so far.
it's 2020 why are you using forms out of free will?
@crisp saddle what's wrong with that? lmao
When ur using a static frontend a form is perfectly fine
Can anyone link to to some resources on authentication with flask? Thanks in advance!
hi friends i am trying to make a steam hour bot. I'm running this bot on my ubuntu system like this on "screen -S idle python3 xxx.py" . What I want to do is to close the screen when I enter a game on my computer, I want the bot to close itself.. The code I use is below.
https://paste.ubuntu.com/p/BVv76PbXF2/
library documentation i use; https://steam.readthedocs.io/en/latest/api/steam.client.html#steam.client.SteamClient.set_credential_location
When I enter the game from steam on my own computer, it catches my connection and continues to scirpt I want it to close.
how to host discord bot with cogs on paid VPS example.: Google Cloud Platform?
Hey my dear Pythonistas! I am confident that many of the members of this channel are versatile developers and know other languages as well. I am briefly wondering since I have never worked with any frameworks but Pythons own built-in library:
Using Django is as I understand a fully featured server-side web framework. Now, what are its limitations? If someone here knows PHP using Laravel, when is it better to use PHP as its purpose is server-side scripting?
I know PHP, JS and C# as well but only at university level. No work experience yet so I cannot really compare these in a professional fashion.
I am trying to make a session permanent so that next time when a user comes to the webpage (who has previously logged in) he/she would be redirected to the chat page instead of the login page
But it doesn't seem to work
Does anybody know why @peak bronze @tacit grove@cold anchor
@native tide It's preference, honestly. Both Laravel and Django are good. Personally, I feel like I'm faster with Django so that's the one I use mostly
@native tide It's preference, honestly. Both Laravel and Django are good. Personally, I feel like I'm faster with Django so that's the one I use mostly
@bleak bobcat Probably right. I think also for beginners it is easier since you don't have to learn an additional language such as PHP
Well you gotta learn python though ^^
small django question, when a form fails form.is_valid() is there a way to display what errored
in console
I believe form.errors
yeah i just found it, thanks
my tests don't behave the same alone or if i launch them in groups >:c
can you show your code and the error @blissful shuttle
no, i use apache2
hi good day how can i make the exactly same website
which tecnology should i use
is the javascript enough
Is it possible to make discord dadhboarda?
Hey so I was wondering if anyone has experience with deploying with the Sanic framework to help me out here.
I have this set up
https://cdn.discordapp.com/attachments/587375768556797982/723526934893690950/unknown.png
I get this error
The certificate is from cloudflare
hey guys, i was wondering what web framework should i start with? i am a complete beginner
ok, but you're familiar with python and coding concepts in general?
yessir
flask is a great microframework to get a web server up and running, but django introduces you to a lot of the common web dev topics
both have great tutorials and wide community support, can't go wrong with either one
what domain is the certificate for?
@cold anchor No domain. Just the IP. Its for an API for my frontend to make requests to. I had to ssl the backend as well since the frontend can't make requests to it bc its not ssl.
you're accessing the API via localhost in your browser but the certificate is signed for an IP address
so you're getting an SSL error
Uhhh so I should run it on a forwarded port on my ip right?
I'm a little confused, did you get a cert signed for your computer's IP address?
right, the cert is invalid
why is this a concern? https://discordapp.com/channels/267624335836053506/366673702533988363/723537412323672099
failing SSL on localhost
Well if you see my frontend can't make requests to it.
I guess I'm confused because it seems like you're asking about something, but providing evidence of something else
you're asking why your API on the VPS won't allow SSL connections but showing evidence of local development having that problem
right, I understand your frontend can't make requests to it
No i was just trying out different things
Here lets start from scratch lol
What do you want me to provide
ok so the specific problem, then, is that you're getting a CERT INVALID error when trying to hit your API?
what do you mean by hit?
successfully make an http request
yeah I am getting it when my frontend tries to make an http request
which is expected behavior
;-;
you need a valid certificate or instruct requests to ignore cert errors
tbh I've never seen a cert signed for an ip alone
so I'm not sure if some nuance there could cause this
it's not allowed from Public Certificate authorities
it's pretty frowned on in general
SO seems to suggest it will be respected by some providers, but not all
ctx = ssl.create_default_context()
tx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urllib.request.urlopen(uri, timeout=60, context=ctx)```
to ignore certificates checking in URLLIB
So cloudflare is not good? cuz its what I use on the frontend server (I use nuxt for the frontend, and sanic for my backend)
cloudflare should give a public cert (or you should upload one)
no, cloudflare is good
I think the practice of putting a cert on a specific IP is not good
Any idea why flask through postman file upload runs the code, then redirects. But in the browser is skips the code and errors out looking for a view to render?
the practice of putting a cert on specific IP is BAD
I think the practice of putting a cert on a specific IP is not good
@cold anchor So i should put the backend on a domain/subdomain?
💯
yes
yes
Im so scared of tryna do that again. First time setting up the domain and nginx for my frontend took 24 hours of none stop work to get it lmao
if you separate backend and frontend to be served differently it's typical to make api.mydomain.com point to the backend
cors schmors
right hand side request routing is generally better
I mean it's not great to have to do CORS, but it's not terrible
(and more expensive)
yep
uhh
though cloud LB are pretty cheap these days
either way, put your API behind a domain, not just an IP
they're cheap for companies, but maybe not so much for personal use
cheers 🍻
Anyone good with Flask? I know i'm missing something simple. The file uploader URL works in postman, but throws error in browser looking to return view first.
I've had some experience with that specific problem
what's the browser error?
(unfortunately, I can't remember exactly what the problem/fix was)
I think the files are not being uploaded from the browser, the form and fields submit, and the file field shows in the form fields. But the request.files is not showing any objects.
just plain forms
yea that's what it is, the file name seems to be sent without the file. I think this is because file upload url need to be independent if I remember correctly.
Tho I could be wrong,.
<div class="group">
<input type="text" id="firstName" name="first-name" placeholder=" " autocomplete="off" required>
<label for="first-name">Name</label>
<span class="border"></span>
</div>
<div class="group">
<input type="email" name="email" placeholder=" " autocomplete="off" required>
<label for="email">Email</label>
<span class="border"></span>
</div>
<div class="group">
<input type="textbox" name="texter" placeholder=" " autocomplete="off" required>
<label for="texter">Texter</label>
<span class="border"></span>
</div>
<div class="group">
<input type="file" name="fileToUpload" id="fileToUpload">
<label for="fileToUpload">File</label>
<span class="border"></span>
</div>
<button type="submit" class="button">We are one world</button>
</form> ```
little long sorry
action should be the URL path you want to POST to
not a relative path to something on the file system
it's a relative path of the url of the site
Hello guys,
I need a little help with Django-Rest-Framework: https://stackoverflow.com/questions/62472173/this-field-is-required-even-though-i-am-uploading-my-file
If anyone could help me, thank you.
as long as it works I guess it's fine ¯_(ツ)_/¯
action url submits, so I don't think that is the issue. The issue is it doesn't upload the file.
also (looking at this tutorial https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/) add enctype=multipart/form-data to your <form ...> element
happy to help 👍
Can someone explain me how I can send data payload with post requests to a https website and than save this input
@silver pasture
import requests
data = {'foo': 'bar'}
resp = requests.post('http://example.com', data=data)
Do I need the api from the website when I want to do this on a https website or do I find it in the sourcecode?
@shrewd moss keep me posted on any responses to your question, please. I am interested in that as well.
@silver pasture It depends on what exactly you want to do. Can you give more details? To what URL you want to post? What you wanna do?
@icy wasp ok i will do so
@blissful shuttle tough to troubleshoot but you have to make sure paths are visible, scripts are within the same directory (or not), etc. see here: https://realpython.com/absolute-vs-relative-python-imports/
here is another link with video: https://realpython.com/lessons/absolute-vs-relative-imports-python-overview/
@cold anchor thanks for the advice
from django.shortcuts import render
from django.http import HttpResponse
f = open("blog/file.txt", 'r')
arg = f.read()
def home(request):
try:
return HttpResponse(f'<h1>{arg}</h1>')
except:
return
im working with django
and im wondering how when i update a file, it updates in my browser
wait
i just had to put it in the function
duh
not sure if this is the spot for this, but im doing some plotly data visualizations and running into the issue of a slider I implemented not being displayed at all. Is anyone familiar with plotly / networkX and would willing to assist me for a bit. Thanks!
\
@mellow wadi Help with web technologies such as Flask, Django, HTML, CSS, and JS. please know what your talking about next time thanks
oh nevermind, i thought you were talking to me, sorry
you're good
not sure if this is the spot for this, but im doing some plotly data visualizations and running into the issue of a slider I implemented not being displayed at all. Is anyone familiar with plotly / networkX and would willing to assist me for a bit. Thanks!
❤️
does someone know how I can put a little black fade over an image? I want my white text to pop out a little more
cuz the image is too bright 😦
not my website, but something like this so the text can stand out and the picture is kind of darkend
@distant trout something like this?
img {
filter: brightness(50%);
}
@opaque vigil I know I'm like 9 hours late, but Django has their own server thats decently active
I'd suggest joining it
@distant trout I hate front end work, I wish you luck btw
How can i run flask with discord.py
er-
shouldnt you ask this in #discord-bots ?
i guess he did
anyway
i have a question
i want to get all the sub-classes of a class, and then get data on that sub-class (basically only text, which for i can use [subclass_name].text()), but i have 0 idea how
i believe selenium isnt the right choice, but bs4 is pretty new to me
notice the "conversations" class, and the subclass of either "conversation-row from-me" or (not shown here) "conversation-row from-other different-sender"
@native tide can you dm me an invite to the Django server? I didn't see one on the search sites I know of
Are web scraping (BS4) q's valid here >.< or do I make my own help?
@native tide u can use multithreading or use Quart which is an async flask wrapper
Then u can run them in the same loop concurrently
Seems a better way since my current way IS SO BAD
Should i just run the app.run and client.run in different threads?
@rustic pebble i can run bot on a thread but flask says signal only works in main thread/Got it
Actually got it
I don’t advise hosting a server and a dpy bot at the same instance though
hii
Hey guys
We have started a community which can be joined by anyone. We are trying to have a group of students of all domains so that we can imrove our connection and collectively work on projects with the help of each other and improve our coding skills. You can even add these projects in your portfolio.
Hope to see and work with you soon in our community. Feel free to ask any query.✌🏼
Join here
http://stackers-thinktank.000webhostapp.com
@winged prairie why dont u get a domain tho
How to run the bot then?
You will need a second process
Wdym
you need one scripting running a webserver the other running the bot
But how can then those Send stuff across
through requests
Optimally the discordpy bot should only request data and not provide
Then you need to refactor your bot
Optimally the bot should serve as a client to the webserver
Wdym
I want to apologize in advance for not knowing which discussion room to ask in but here we go!
I have a solid grasp of Javascript however not so much with Django as opposed to Pythons core library. I'd like to know which is the most popular and best database in general?
I heard that a combination of NoSQL and SQL are very popular in large projects across organisations. How does this actually work out? SQL for certain things and NoSQL for other purposes?
Why did I state my Javascript skills? Well, I want to make a larger project for my portfolio as I am close to have my Bachelor's Degree in Cyber Security and Software Testing here in Sweden. I'd like to create some project which involves GPS real-time tracking and A.I thus Javascript is obviously essential. For instance I know that Google Maps uses A LOT of Javascript.
Do you guys have any recommendations or inputs to my questions/statements? Would appreciate it very much.
Also what API's are suited for GPS tracking? I realize that real-time tracking is very expensive and difficult, I am referring to those used on big ships, airplanes, military, etc. The ones we have in our smartphones aren't really "real-time" since there are delays and not as accurate as the ones stated.
@native tide
The modern web app architecture is a backend Rest API (or possibly GraphQL), and a frontend JS library like React/Svelte/Ember/Vue/Angular.
The front end is pretty irellevant for building the backend, so that part doesn't matter specifically when it comes to databases. The most common model for the database with Django specifically is to just use one database specifically for the ORM+your models, a very good choice for that is PostgreSQL. When it comes to mixing SQL/NoSQL - usually the NoSQL gets used for some specific aspects, I'm not entirely sure on exactly what honestly - I know Redis gets used for things like short term cacheing, and that Mongo is allegedly good as a document store.
For what you want, Django+Django-Rest-Framework+a frontend library is probably the way to go. You'll need some mapsy stuff both on the backend and the frontend, I've done real time tracking with planes in google maps - and it's not too difficult to get started with.
I'm not entirely sure what you mean by what apis are suited for GPS tracking? do you mean stuff like Flightaware where you can track plan/ship locations live? If so - ADSBExchange is your best bet for planes, not sure about ships.
A common SQL + NoSQL pattern is to use SQL as the primary store and spin up ElasticSearch for searching documents in your db that you put into ES from SQL
How would you suggest filtering in a django template? Would you update querysets in the backend with a POST or query once and then just use some kind of JS/JQ filtering to just filter what's already on the page?
Hi
WHy do i get this error ```py
Traceback (most recent call last):
File "app.py", line 7, in <module>
sys.path.append('/home/pi/Python/Discord')
NameError: name 'sys' is not defined
(venv) pi@Russel:~/Python/Discord/New_Folder $ python3 app.py
- Serving Flask app "app" (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: off
- Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/asyncio/unix_events.py", line 92, in add_signal_handler
signal.set_wakeup_fd(self._csock.fileno())
ValueError: set_wakeup_fd only works in main thread
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "app.py", line 61, in bot_run
client.run(bot_token.token)
File "/home/pi/Python/Discord/New_Folder/venv/lib/python3.7/site-packages/discord/client.py", line 614, in run
loop.add_signal_handler(signal.SIGINT, lambda: loop.stop())
File "/usr/lib/python3.7/asyncio/unix_events.py", line 94, in add_signal_handler
raise RuntimeError(str(exc))
RuntimeError: set_wakeup_fd only works in main thread
it seems you're trying to use flask together with asyncio/discord.py? I don't think that's going to work, since flask is not an async library
you'd need to run flask in a seperate thread
which is a really bad way of doing just btw
or, if you try to add a web interface for your discord bot, maybe use aiohttp server
which comes with discord.py anyway
wouldnt even do that
there's not much point in trying to link the two instances
it just causes issues
the problem is, if you have your flask app on one thread, and your discord bot on another thread, and you try to execute some discord commands from the flask thread, you'll run into issues like you have above. asyncio is generally not very thread safe, since it's expected to be run from a single thread, or at least having one independent event loop per thread.
it means: avoid using threads and asyncio together
Dunno. You could use aiohttp webservers like I suggested. which gets rid of all the threads. https://docs.aiohttp.org/en/stable/web_quickstart.html
or simply don't try to use webserver and discord bot in the same app. make two different apps or something.
I currently got this thing https://gyazo.com/02d10235d12c2346bdb619e72a355ad9
It works
well, you got the error above, so apparently it doesn't work in all cases.
can't help you with that, since I don't have your laptop
I assume your error is due to the mentioned incompatibility between asyncio and threads in general
kiwi?
ye
i see
If I understand correctly, Kiwi also suggested to not combine a webserver and discord bot in the same app:
I don’t advise hosting a server and a dpy bot at the same instance though
ye
I'm not sure how I would do it.
I would definitely use a separate flask app, independent from the bot, if the website is going to be more complex.
and either use a database for some rudimentary communication, or the bot itself is going to have a simplified API to trigger updates done through the flask app.
yea, that's one approach
if you don't want that, you could have a very simple aiohttp webserver in your discord bot that only is there to trigger an update
Check if guild has updates
and the flask app sends a request to that endpoint, basically to tell the bot "please look in the db"
like I wrote, yes
aiohttp comes with discord.py, so you don't need to install it
I have never used it like that myself though
I have no idea how to use it even 😄
Anyone has idea to how add audio/vidao live stream in django app ?
like zoom or any good methods
feedback on authentication method?
can someone tell me how to set a media query
so anything ipad and lower
will hide content
Please does anyone know I can use django with svelteJs
Can I ask some scraping/bs4 questions here?
it shouldn't be any different from saving a .xlsx file in certain folder using python
figure out how to do it with python first
what are the best cloud hosting options for python?
Try heroku
its only good for very simple apps
Yes
mine is complex
digital Ocean
Yeah
I never used any. I cant answer properly
Hey guys, I'm trying to figure out the best way to deploy a django web application to AWS EC2. Just wondering if anyone has any resources they could share so I could learn the best way to do this, as there is very little info I can find on the web. Thanks!
Did you create an EC2 instance yet?
feedback on authentication method?
@rustic pebble which tools are used ??
ohhhhhhhhhhhh
nice @rustic pebble do you want to build that or you built it already ??
Is tornado is good @rustic pebble ??
i guess
but what's the secret about that amazing style @rustic pebble
i have designers
@rustic pebble Do you work as collaborate ?
or is that paid project also what side you are working on it ??
and also what tools your designers are used
sorry for my curiosity LOL
thank you so much @rustic pebble
np
Oh wow that does look beautiful. Makes me wanna learn some web design, but I've always had trouble creating art. I'm more of a replicator.
Yes I have created an EC2 instance.
and configured ssh access into it?
Then ssh into it, and update it first, then install all the dependencies as you normally would on a development machine
https://i.mattboy.live/R9nJR1S.png
How could i make certain things not effect the position of elements
First message in flask socketio dont working.
In localhost all works fine. In production (vps, nignx, centos 7) first message just don't sending.
I using gunicorn
first message error
Hey how do I make a notification that has animation and disappears within an amount of time?
Hey guys, I have a question about web servers handling concurrent requests. Here's my use case:
- I have a DB that gets updated with the result of a job every half an hour or so. When the update happens around 3000 lines get populated in the DB.
- When the update occurs, I get the unique IDs that were updated (usually around 2500). I then need to run another job for each of these IDs.
- This job involves a DB lookup and some time series processing, then writing results to a bucket. It takes about 5 seconds to run.
After thinking about the problem, to me it sounds like it could be handled by a web server like flask or aiohttp. I don't have much experience writing these in python (I come from node), and I was wondering:
- If I were to make a flask app that can handle requests per job ID, how can I rate limit what goes into the flask service so that it doesn't fall over with 2500 requests all at once?
Something like, backlog of 2500 jobs -> send them to the flask app as fast as possible without it falling over until done
I believe you could use a redis worker for this. It basically does job queueing afaik. I don't have experience with it but there are some YouTube videos on it @lean marten
Thanks, will look into it. Also if I run 4 workers with gunicorn with flask, does that mean i'll be able to process at most 4 jobs at a time?
Ya'll what does Django compile to when you set it up? Does it get transpiled to JavaScrpit for the frontend, or asm or something else?
@lean marten I'm not sure. I haven't worked with gunicorn before. Sorry.
Can someone give me a rough estimate of how much per month/year it costs to host a small static site?
I know a guy who makes... products... and sells them privately. His site looks like it's from the 90's. So, I was thinking about bartering; One of his products in exchange for a modern site.
He needs a better site and I need a resume. Figured it's a win-win. I know quite a few small business owners with no site that I can also approach. I haven't gotten to the part in my textbook that teaches me how to launch, so I'm kinda just browsing for info. In my previous book I used the free Heroku service to launch a tutorial site, which is my only experience.
The services I'd be using are; Django, postgres, redis, and perhaps celery/RabbitMQ for giggles.
that would be pretty cheap from my understanding
u can host that on like a random vps
and it would prob work
I'd like to use some cheap $10 private server, but I've heard that the setup is very complicated if it's not through a hosting service like Heroku. I still plan to learn how, but I am intimidated by the process... Don't know what that process is, but it sounds complex since I got all these services running.
@molten quarry I've had a lot of success with digitalocean, they have great tutorials for setting up ubuntu servers from scratch
heroku is extremely easy to setup
i have a idscord bot running on it with mongodb and some other services
it works fine
Hey @molten quarry
I went through chapter 9 which is about classes in js, I can say that this book is pretty hard and want to leave it.
Is that book you suggested really really worth it?
Heroku also for me really simple
If you're only going for a static site, netlify is a great service for that. You can then pair it up with a site generator like jekyll if you'd ever want to setup a blog
When I designen a website with Adobe XD how can use python on it
@silver pasture Adobe XD is for designing and prototyping. It's only the 'look' of the website. To use Python on a website you'd have to use a web framework like Django
guyz I have a running web server on a remote vps on debian, and I can't seem to connect with it from my local machine. Browser just goes to an endless loading stage then timeouts. I already have ACCEPT rule on iptables on the specific tcp port I'm using, I even tried taking down all my firewall rules still can't conncet through it. What can I be missing on here? thanks!
@rich hamlet you don't "use python", you just serve the documents and base your backend in python
@rich hamlet or Flask >.<
or a banjillion of other web frameworks lol @native tide
@native tide mostly just backend. Funny that you asked. I have client right now and they want SEO as well and I'm not sure how to handle it
does anyone know why my html code would work locally but not online, im using cloudfront and s3
That's exactly why I've asked
I am a full stack developer, I deliver full fledged websites
I also have a client that wants SEO from me :))
@rustic pebble but have you ever done SEO? What is a must when deploying a website with SEO in mind?
@rustic pebble it's mostly how you phrase the texts in your pages and about keywords right? Haven't researched yet
i guess something from Google
I code in react and an async framework, my SEO skills aint the best
whatever, my client wants me to index his website on the first pages
so wish me luck
rip
@native tide omg, the same here. I don't know how I'm going to do it. Advertising on Google is another option. but the client has to cover the costs
Idk..maybe google ads / facebook campaigns / seo / blog system
@rich hamlet yeah i use django for the website but how can i get the Adobe XD code to use it on the website
@molten quarry Just got the book about 1 hour ago, it's pretty well written and the author is making every page interesting. thanks again 🙂
@silver pasture I think Adobe XD doesn't support export to HTML, but there is a plugin for that https://www.guidingtech.com/export-adobe-xd-html/
is html the best way to export or are there other ways that I can use
@rich hamlet that is extremely misleading, you don't get final product, everything is exported as an object and cannot be interactable by backend technologies or javascript in no shape or form, you will need to hand write it using frontend technologies
@wind escarp I haven't actually worked through it myself but it looked good. I also left the rhino book and went back to Eloquent JavaScript. Rhino book had way too much detail for what I needed. I'm gonna use it as a reference book, and probably go back to it in the future, but for now Eloquent JavaScript is teaching me a lot... But it is hard as hell...
Is there currently a best practice for having a button to add fields to a wtform using flask? I've got dynamic fields based on data provided to the field but want to have a button users can press if there wasn't one defined.
Were could I find information on "when to just use socket or to use web server like with flask?"
Or simply see the differences etcc
@rich hamlet you don't "use python", you just serve the documents and base your backend in python
@rustic pebble hello, it's possible
http://brython.info/
Brython
lol
all i see is js
transpiled by python
brython is very bad and cant be used with any modern technologies
Tbh it really doesnt take that long to get comfortable with browser JS
true
Shit gets tough when you want to make complex apps
not plain element manipulation
frameworks make it a bit easier
well
depends
if you are making a small website using frameworks other than Vue is like shooting your leg
But then again, if you are making a larger scale website using frontend frameworks implies that both your design skills and ability to create coherent and well-coded apps is extremely good
else you are like me who can do almost anything frontend wise, everything backend wise but just hire devs for the frontend part
ye cause u are not going large scale
i should get better at react tbh
try getting good at both react and backend
for 1000$
lmao
I am making a dashboard for online services and I have hired someone to do the frontend for them
I have already been developing backend for a week and I am nowhere close to even having a functional unit, imagine if I had to do frontend as well
personally prefer backend overall
I am fullstack
For the right price I do everything
lmao
I would rather focus on backend since that is what rly matters in larget scale apps
@molten quarry
A friend of mine suggested that book and learning TypeScript, it's similar to js, kinda easier to read and compiles to js code, seems like something I wanna learn next
are you doing contracting kind of work Kiwi?
Type script is just strongly typed JS
as
For the right price I do everything
does not sound like full time company work 🙂
Coffee script is another one which transpiles
I am a uni student
oh i see
I have a service here in discord for the sneaker community niche
Which one is easy but includes ES6 specs?
Huge $$
both of them really
But you gotta be good enough to deliver and maintain an abundance of projects
oh, infamous sneakers xD
Yup
I usually build dashboards/desktop apps that are binded with a discord bot (that is where most sneaker groups are based on) and usually use a payment processor like Stripe
I am currently creating a resellable dashboard that groups can rent for $X/month and they can custom brand it. It will follow a general paradigm but upon purchase they will be able to fully customize all the branding aspects to their own group
Using kubernetes I will launch a new cluser, using a wildcard dns record they will be able to get their own domain
micro k8s lul
sounds nice, looks like you got yourself some good source of income
these are demo screenshots
@grim onyx Well yeah
I am trying to expand out of the sneaker niche and actually build an agency rather than a freelancer service
I have around 5-6 designers for websites and UIs, 3 logo designers and branding managers, 3 frontend devs and 2 more fullstack
That's good, keep the grind
I am just stacking projects for me resume
While making good money as well
well that's already sounds like you have a group of people around to start building a kind of small agency
Yup
Ive just started building up a portfolio and stuff xD
I started this with no portfolio
I just literally had basic discordpy knowledge
not even OOP
I made 3-4 barely functioning bots
got some credit in my name
and started taking bigger orders
Yup that is good
Do you know desktop languages as well?
other than js with electron ofc
oh native lang sorta stuff?
ya
I started doing alot more work in Rust as of recently
Rust is really good
Its my Secondary language to python
But for microsystems
I use C++ for microsystems, usually transactions between client-server
If I were you I would start learning Swift, it is really popular amongst today's standards for native apps, you can build apps for 3 different ecosystems macOs, ipadOS, iOS
I just hope the nightly build with some more of async will be released soon for rust
Tokio is alright but the standard version seems alot better
rather than tokio which can be a bit odd at times
I haven't used rust a lot
or Kotlin for Android?
never heard that one
If you already know React you can go with React Native
Flutter is based on Dart
It is also async
if rust got better async support i'd probably work on some sorta webserver for it to merge with python
No point really
Too much work for too little compensation
It would be best if you tried to enhance your scaling skills than trying to get 50ms of faster response times
Tends to be how i roll normally
I used to be like that, everything for that performance maximization but only now have I realized that I missed out on more important things like kubernetes, mass scaling, CI/CD
I don't know about Dart as well 😂 given that, I don't really need anyitgn but python for now heh
maybe Scala eventaully
I had to learn K8s fairly early when scaling the bots lol
Statefulsets man
basically upon confirmed payment i need to create a new instance of: the dashboard, a discord bot and a database
with some things preconfigured like the branding of the website
how do you do the bot tokens and work that then?
@grim onyx I have seen you active on async channel tho, seems like you are more advanced than many
I will have an interface for the user to enter their bot key
along with a very detailed guide on how to make one
well I am actually in Data Science 🙂 But async is something wihch a) interests me b) can be usefull here and there (like that small case I told about in asnyc)
I love async
async is so nice actually
I remember when I first saw async code
Only thing I remember reading is very close to @quick cargo's name
hehe I was lucky to never have to deal with pre async/await async
when I started too look into python and all things py3.7 with its asyncio.run() and modern syntax was already a thing
I learnt async through aiohttp lmao
Using async on javascript is so different than on python as well
yeah
async is just syntactic sugar for promises there
Js's system is a bit weird
Nah I like it
tho js didnt get it till not to long ago
yup
Typescript is the new elite
Many people know it, only a few use it correctly
I am trying to commercialize it but I am steal hesitant
never tried typescript tbh
probably try it at some point
Feels more like a real language than a mess
Not as much of a mess as mySQL
Its taken it along time to catch upto postgres again
I only use MySQL and rarely mongo
I am planning to pick up a firebase - angular - node stack
Firebase is quite good
I tend to work with Postgres or mongo
tho async mongo is pretty shit
since angular and node are now written in typescript
depends
firebase has many similarities with mongo
But it also has cloud functions
yeah ik
Which adds immense functionalities to your potential app
like push notifcations on mobile app
Exactly
something our devs trying to figure out now
there are free unlim features thp
but yeah everything with google/GCP can ramp up in $$a lot
all things google tho
hence our emails/servers etc are on local clouds
I am just trying to rack up projects though
so
everything is good even if its not in use
I am 19 and I have around 25 full fledged websites with dashboards and discordbot companions
I should be in fucking MIT
Most of the time with stuff i work on any db stuff i just make a load of functions for the db so i can just treat them like mongo querys lol
