#web-development
2 messages · Page 107 of 1
This is in your template correct?
@swift sky What exactly are you trying to do? Generate a xls from a query set? With you object info or something?
I have a query, and my goal right now is to turn that into a file that I can download
though in the future I'd have to take that same data and also make a graph out of it in my webapp
so give the user the option to graph or download
Your best bet is just creating an excel file an filling it out how you want it. There might be a package out there to do it but I would personally make my own function to do something like this. It should not be hard and I could help you out if you need further guidance.
Anyone know what the best API is for putting pins on a map based on longitude and latitude?
ive heard of it
By best I mean least expensive
@devout coral Yeah Google Maps was the obvious choice but I'm wondering if it charges for each pin I place. Does it count as a request?
@cold socket How are you planning on displaying said map?
@devout coral Just on your average html page
@swift sky I would use openpyxl, create a workbook in memory, edit it then return it to the user
how would i return as a download file
@cold socket Yeah I get that but how will you render the map?
Ouch, I thought I could access dicts in Django just as I would in python. Guess not.
@devout coral https://github.com/flask-extensions/Flask-GoogleMaps
I was thinking of using this Flask extension
@swift sky Changing the contenttype of your return so it downloads
@cold socket Ok... by the title it looks like it uses google maps.
Why does Django go through all that trouble.
@haughty turtle What trouble?
Literally this. But I am not sure if each of these markers is considered a request.
@swift sky Did you want me to give you an example?
if you have one that would be nice
@swift sky
@login_required
@permission_required('employees.can_export_counseling_history', raise_exception=True)
def export_counseling_history(request, employee_id):
employee = Employee.objects.get(employee_id=employee_id)
pretty_filename = f'{employee.first_name} {employee.last_name} Counseling History.pdf'
try:
response = HttpResponse(employee.create_counseling_history_document(), content_type='application/vnd.ms-excel')
response['Content-Disposition'] = f'attachment;filename="{pretty_filename}"'
return response
except:
messages.add_message(request, messages.ERROR, 'No File to Download')
return redirect('employee-account', employee_id)
@haughty turtle Limited code usage?
thanks
You know HTML is not meant for coding, just be glad we have things like Templating Languages now
@swift sky This is the import for that you need from django.http import HttpResponse
it's flask
@swift sky Oh awkward.
So how can I access a nested dict in the Django Template in HTML
I mean why go through all that trouble if Django can read the code why not just interpret it into Python ?
i have pandas experience, and yeah... I just am not too sure how to covert the dataframe to a download file
@swift sky from flask import Response I think you can replace httpresponse in my code with this
@haughty turtle The template language can read the dict though... What do you have and what problems are your running into? I am sure you are just doing something wrong.
{% for i in context %} <div class="product_category" id={{i}}> {% for p in context[i] %}
@haughty turtle
It's giving me an error in the second loop as I try to access a nested dict
what is context?
A dictionary.
Hi guys. I have a React frontend and Django backend w/ token auth. To log in a user, via login/, I'm thinking of just having that view return a cookie which contains a token to authenticate the user, so they can move on. Is that the same thing as logging in?
@haughty turtle You access the contents of a dictionary as if they were properties in a object. Like context.item1
@haughty turtle What you should probably be doing is the following>
{% for key, value in context.items %}
<div class="product_category" id={{ key }}>
{% for item in value %}
{{ item }}
{% endfor %}
{% endfor %}
Thanks, so long to figure out that normal python doesn't work in Django Templates haha
@haughty turtle Did you not read the Django documentation?
@native tide Why not use the built in authentication?
@native tide Oh so you are using cookies instead of sessions?
I do not understand what you are asking...
Token auth yes, stored as cookies
Oh ok
I think I've answered my own question though. Which is yes
Also, out of curiosity why use cookies and not sessions?
Because I've got a React frontend which just communicates with the Django backend via API calls.
And sessions was a pain for me
Or better put why use ONLY cookies
Ok cool
Using only cookies though is not more limiting?
You cannot store as much info no?
I don't think so. What extra info would I need to store? Each user has a token identifier which can identify if they have the permissions to view a page. So I think that's enough.
I can always add extra cookies depending on what info I want to gather too
But I don't know what extra info I'd need to store about them
@native tide IDK really, I just thought django designed their sessions framework intentionally to be more secure and not just store all the data needed inside cookies.
Well I'm using DRF and there's multiple auth methods, session, token, etc. Token is absolutely fine, I only need to store the user's identifier on the clientside. The rest of the info is serverside
Ok cool
I have not messed too much with sessions or cookies myself. That is currently on my low priority to-do list.
Cool cool thanks, I am not getting any errors now. python <div class="product_categories"> {% for key, value in context.items %} <div class="product_category" id={{key}}> {% if value|length != 0 %} {% for p in value %} <div class="product_name" id={{p.product_name}}> <span class="product_price" id={{p.product_price}}></span> <span class="product_description" id={{p.product_description}}></span> <span class="product_photo" id={{p.product_photo}}></span> <span class="product_gener" id={{p.gender}}></span> </div> {% endfor %} {% endif %} </div> {% endfor %} </div>
It creates <div class="product_categories"> but nothing else inside of it, the div is just blank
@devout coral
hey guys wanna ask if u dont know why is that middle text on middle i have it in class "right_section" same as bottom right text. i think it should looks same but idk why is it on middle
this is what code looks like
is there a special built in django enums or constants for status codes that i could use?
@vivid canopy your containers you are not placing a marging left or right you only have absolute and top styles
u mean like whole section to set left or right?
Yes, place the container where you want adjust the pixel left or right wise, then just add margins between the text and image
@vivid canopy
gonna try ty
but for that text where we are from it anyways doesnt work
cant be it bcs of image or something like that?
you shouldnt be using top or left for your images, you should be using margin-left or margin-right for your images
top or left is for your container in terms of how much spacing left of right should be from the screen
and then even then the way you are using top is so confusing, you should be using top and bottom for your first and last containers, any other containers should be using margin-top and margin-bottom in between
your div containers should not need to have all those unique classes with top 20%, 60%, 140% and so on, the top should be left for ids, ids are unqiues, your class should be left_container, middle_container or left_container
classes are repeatable between divs
aha thanks appriciate it
even then you would not need to place your margin-top between your containers in a unique id as they should all be equal from each other eather way properly speaking, so all expect the first and last containers should have a margin-top of 20%
Hi, im new to django and I am adding a Nav Bar via Bootstrap. It is supposed to look like this. But instead it looks like this.
how do I fix this
here is the code:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
<a class="nav-link" href="#">Features</a>
<a class="nav-link" href="#">Pricing</a>
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</div>
</div>
</nav>
it is in the index.html file
it seems as your not linking correctly to your bootstrap or styling @summer wyvern
how are you linking to it
<div class="product_categories">
{% for key, value in context.items %}
<div class="product_category" id={{key}}>
{% if value|length != 0 %}
{% for p in value %}
<div class="product_name" id={{p.product_name}}>
<span class="product_price" id={{p.product_price}}></span>
<span class="product_description" id={{p.product_description}}></span>
<span class="product_photo" id={{p.product_photo}}></span>
<span class="product_gener" id={{p.gender}}></span>
</div>
{% endfor %}
{% endif %}
</div>
{% endfor %}
</div>``` any idea why none of my tags inside of my loops are printing into my html file only `<div class="product_categories">` is printing and this is outside of my loops, I imagine at least `<div class="product_category" id={{key}}>` would print but not even that is printing @stable kite @devout coral @warm igloo
I am building a chat application, how to get all the active users on the website??
@haughty turtle So, likely your conditional is never met, so look over your if code again to make sure.
if value OR length IS NOT EQUAL to 0 is that what you mean?
er, wait
<div class="product_category" id={{key}}> is outside of my if statement
ah, true
which should at least be printing into my html document
are you confident context.items has ... well, items?
yeah django was showing them to me
{'Accesories': <QuerySet []>,
'Clothing': <QuerySet [<Product: Test 1>]>,
'Textiles': <QuerySet []>}```
and you're sure, in the template, that context.items is full of that data? Meaning that context.items is making it there for looping? I don't know Django, but in general if you're trying to loop something and nothing is showing, you probably aren't actually loop through a collection like you think you are
or it is empty accidentally
yeah that is what django was showing me that context had.
trust, but verify
run debugger, set a breakpoint OR add in some print statements like say to see the number of items in the collection, or the key/value pairs explicitly, or heck print out the type of context.items to verify
Ah yeaup it is empty
weird, Django said it was in the logs
context = {"products": Product.objects.all()} I even did this the Django log shows that it logged context
{'products': <QuerySet [<Product: Test 1>]>}
Why does it have to be so dificult just to loop through a dictionary... frustrating
only thing I could think of is that my html is not grabbing the right context var located in my views, but why would this be happening
Has anyone got any portfolio website that I can take a look at?
You will find them easily on Google, Github and Youtube @native tide
come on, python {% if context %} <span>{{ context|length }}</span> {% endif %}
its not even finding context
why does this even print the context length without the if statement but with it it doesnt I assume it would need to find a context for it to print its length.
Realllyyy
why does this have to be so annoying, @vestal hound
@haughty turtle I am guessing you are still having the same issue? If so could you please provide me with your return in the view
Just the code that is in views
@devout coral ```python
from django.shortcuts import render
from .models import Product, Category
def index(request):
context = {"products": Product.objects.all()}
return render(request, 'product/index.html', context)```
I even tried something this simple, my context is not being registered in my html file
@haughty turtle There is your issue the variable name is products not context....
What is the best way to make a graph of a python dictionary and display in flask?
@fast lagoon probably matplotlib not really 100% sure
that worked, why does django have to be so weird.... come on.... python {% for key, value in context.items %} <div class="product_category" id= {{ key }}> then why does this snippet that you gave me not work on python def index(request): context = {} categories = Category.objects.all() for i in categories: Prod = Product.objects.filter(category=i) context[i.category_name] = Prod return render(request, 'product/index.html', context)
@devout coral
@haughty turtle Well it is documented properly... Just gotta read it lol.
That is definitely not what I sent you lol. I could however help you solve the issue
@haughty turtle What you should probably be doing is the following>
{% for key, value in context.items %} <div class="product_category" id={{ key }}> {% for item in value %} {{ item }} {% endfor %} {% endfor %}
@devout coral
This is so annoying I followed how you said to iterate through dicts, followed how Django Docs said to do it, and it turns out the only way I got something was by calling products when its not even the dict name
No your issue is not how you are iterating it. The issue is how you are passing the variable. It is not named context
context = {}
Why make a Django library built on python to have it be so unpythonic
like I am learning a whole new language
Context is the dictionary you pass to the template. The contents of that dictionary is what actually become variables. For example if you pass the dictionary.
context = {
'item1': 1,
'item2': 2,
}
In your templates you wouldaccess it the follwoing way.
{{ item1 }}
{{ item2 }}
@haughty turtle No it is very pythonic I think. You are misinterpreting it.
In the docs, no time does it state that the contents automatically becomes variables...
...
The keys of the dictionary you pass become variables and the values of those keys become the value of the variable
but how is this pythonic, I never encountered this in my regular usage of python
Why make a Django library built on python to have it be so unpythonic
The template language is also designed for webpage designers who may not understand Python at all
TBH web designers should not be touching the template language
The idea is to keep it simple in the templates and the python scripts provide the necessary info
@haughty turtle If you read the docs you probably ran into that little snippet right? So not sure why you are frustrated.
TBH web designers should not be touching the template language
Well unfortunately Python script writers may not be good at designing visuals
You're basically giving a designer a dict and say, "here are the values and their corresponding names you can use; go design a webpage"
Because that snippet was like so long before I got into the template that I did not understand it would be troublesome, Simplicity would have been to keep it as it would be in Python, you have to know Python to use Django, why make it easier for those in different backgrounds when they still have to learn Python first, me having to take so long to learn how to iterate over a dictionary in the Django template is so absurd, and what do web designers and the Django Template have in relation
But that designer would still have to learn the Django Template Language rules
Django template rules is actually quite different from Python
Sure it has some influence from Python
It's also quite stripped-down
Yeah I had to understand that the hard way, but either way someone from a new background would have to go and spend time learning the Django Template rules then
Lol bro, not sure what complaining about the DTL help you. Learn it, apply it, be happy
Or better, make your own framework XD
Have you used Jinja before? It basically like Jinja
Or any other template language
You probably have never used one and expected it to be like Python, which it is not python.
Thats exactly what I expected, but now I understand its not finally
Lol it is ok. It is actually quite intuitive one's you wrap your head around it.
@haughty turtle Did you finally get that thing working now?
well I am trying to get a way to gather all the keys-vars from context
so that I can actually know what my vars are then
def index(request):
context = {}
categories = Category.objects.all()
for i in categories:
Prod = Product.objects.filter(category=i)
context[i.category_name] = Prod
return render(request, 'product/index.html', {'context': context})
That should work
Then your loop will work
would that not be the same as
def index(request):
context = {container: {}}
categories = Category.objects.all()
for i in categories:
Prod = Product.objects.filter(category=i)
context[container][i.category_name] = Prod
return render(request, 'product/index.html', context)```
Also, I would like to point out that you are going to query your database for as many categories you have which I do not this it is good.
But does ojects.all() not grab all items in one go
also I tried the code above, for some reason it does not work, would this not be the same as yours I mean
@haughty turtle I am not even going to bother to see if yours accomplishes the same thing because it looks way too complex
No need to make a nested dict and iterate through it to pass it. It is simpler to make one dictionary add everything you need then just pass the dictionary
You are making this all complex
it should theoretically be the same as the one you just gave me, instead I nested the dict beforehand
@haughty turtle Yes objects.all() is fine. It only does one query but then you loop through each item from that and query with Product.objects.filter(category=i)
@haughty turtle Why though... Just making it harder to read. If I am honest I saw the nested dict and decided not to read it.
Was trying so before you gave me yours, but I find it weird that mines does not work and yours did as its technically the same thing
Yeah, prob going to look into the solution that @bleak bobcat suggested to me before, the regroup solution. but going to continue as so for now and then change it later on
@haughty turtle Did you try the solution I posted?
The one with just one loop
Yes
@haughty turtle try my solution it will work
Nope, I will take a look at it later so that I can take the time to understand the difference, just going to move onto the next thing so I can refresh my mind, and get rid of this frustation
@stable kite Can I see your solution? I missed it.
sure
def index(request):
context = {}
categories = Category.objects.all()
for i in categories:
Prod = Product.objects.filter(category=i)
context[i.category_name] = Prod
return render(request, 'product/index.html', {"context":context})```
@stable kite Yeah that is what he is using. I told him it is not ideal because that queries the database for every category there is. So if there are 100 categories that is 100 queries.
@devout coral @haughty turtle is directly passing the context varible to template
That is not the issue. Look at your loop. You are calling filter on the Product every iteration.
Cant even do a while loop in the template, now I have to do it in JS
Why do you need a while loop?
ya use for loop
I want to print out a default container 3 times
not iterate over a item
But got to do what I have to do I guess
@haughty turtle Could you show an example? If you want three containers then why not just have three containers in the html, what is the need for the loop?
@devout coral Javascript makes it really simple to do what I need to do
<div class="product_category" id= Clothing>
<div class="product_name" id=Test 1>```
my ids arent wrapped around strings though any reason why
@haughty turtle did you just ditch using the DTL?
No
I still need to get my items from the the database which is what I am doing with the DTL, but the items I brought in are not presented as a string
same code as before
So just make a filter to display it how you want.
Making custom filters is easy, and you do it with regular python code
heyy
why isnt my extends base.html working
@devout coral
can you help mei pls
Sure, can I see your code
i am using django
yea yeah sure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BT | Real Estate</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
{% extends 'base.html'% }
{% block content %}
<h1>About</h1>
{% endblock %}
this is the index page
and this gives an error
Can I see the error plz.
Ok, can you send me your project tree. As in how the files are organized plz.
So in Django, you templates go in a directory inside of your app called templates. Then in that directory you need another directory with the same name as the app. Then you put all your html templates inside the folder.
That is a continuing explanation
No wait I saw it wrong
and i have created the templates in the root
Just add pages before base.html to the string next to extend
Sorry driving one sec
{% extends 'pages/base.html'% }
{% block content %}
<h1>About</h1>
{% endblock %}
Try that
ohh okay
That’s the directory it is in right?
Nice
Haha thanks
You understand why that works right?
wait my file tree is shit
templates
pages
this is my tree
and my templates are inside tht pages inside templates
Yeah, that’s fine tbh. What I do is have a template folder for each app. Just so everything for one app is contained inside the app.
But you can do it either way
oh okay so should i do tht way ?
Whatever you prefer
should i add tht templates directory inside pages
and if i do so
then how should i name tht
like templates
then inside templates again pages
tht is it right ?
Well the convention is to have a template folder and inse that folder a folder with the same name as the app then all your html in there
Yes what you wrote
That’s what I do. But it’s a preference
how should i correct this now ?
like if i put it inside my pages then
should i do it like pages/templates ?
yeah okay i fixed it
thanks a lot
You welcome
Well theres an <img> and then a <p>
Alright do me a favor and pastbin your code.
Otherwise I cannot help you much
Because there could be multiple things adding the space and multiple ways to get rid of it.
Sure. In my current project I have a app called main which holds everything that all users would share. Like home page (base.html), some shared views/forms etc.
Up to you
ohh okay i will keep tht inside my templates itself
Yeah, my templates folder I use it for my different error templates and django admin templates
oh okay
thanks a lot mahn you saved an hour or so cause i wasn't finding the correct solution for tht on google
😄
If a partner knows databases well and I’m using django, just let them handle the database right? Rather than me trying to use SQLite and learning as I go
If a partner knows databases well and I’m using django, just let them handle the database right? Rather than me trying to use SQLite and learning as I go
@plucky tapir confused
can you elaborate
you need to know basic SQL to use Django's ORM properly IMO
@vestal hound https://docs.djangoproject.com/en/3.1/topics/db/queries/ I’ve done up to getting objects from the database
And setting up a foreign key
it goes beyond that
like
it's very easy to run into N+1 query problems
and like understanding how joins are abstracted away is important
do first()
is there anyway to remove QuerySet when displayed a query?
@toxic flame what do you mean?
For example in django
i do
Post.lines_set.all()
when i print it, it shows
QUERYSET: 1, 2, 3, 4
I'd like it to remove the queryset and just leave it with 1234
I'd use a forloop but that breaks the current thing I'm doing
', '.join(element.pk for element in queryset)?
@devout coral Created a custom template tag, custom template tags will definetly make my life easier using Django, I do not think I will be using any pre built ones from Django anymore....
@haughty turtle That is good, but do not re-invent the rule now.
@vestal hound do i replace 'element' with "stock"?
coz thsi is what it says
changed to this
ok
ok this worked
As far as my Django template goes I will prob do just that, I do not like their pre built functions, rather rebuild everything from scratch to my own liking
If i'm using docker-swarm and have gunicorn setup, should docker-compose just be running 1 replica
@haughty turtle There are some nice filters like length
Have anyone worked with swagger codegen
I'm trying to load some data off a website that apparently loads this data in using thousands of lines of javascript, i think using jquery. It's not a publicly accessable website, else i would just link it. Does someone have some pointers for me on how to figure this out? I'm not that familiar with modern web technologies. Is there maybe a good tool to figure out the exact web technologies used on a site etc? So far just stumbling thru it with chrome dev tools.
@grave heart does this website allowed you to scrape it content in it's robots.txt ?
no clue!
@grave heart you can go to domain_name.com/robots.txt to check it out
they don't have one
oh really? most site should have it
well it 404's
well if you want to scrape javascript content you probably need a headless browser to generate the content and scrap the page
which tool you using? scrapy ? selenium?
uhm none?
i'm building a little website that shows battle statistics for an online gaming clan, to track progress. i can get some data of the official API the game developers offer, but some data is only shown if you log into your account on their website, and then you can check previous battles one-by-one to get part of the information, which i then can use to query the api to get the total picture. so far all i have done is use google chrome dev tools to inspect the site, and there i found javascript files of several thousand lines of code with a jquery license comment in it. that's all i got so far and i'm quite confused. for my little website i use flask so far, and fetching the data from API, i used urlopen. so yeah, python requests. i looked at phantom js briefly.
Doesn't their API have an authentication option?
You can perform authentication using requests and then query the restricted stuff in the same session
sure, but thru the documented api, you can't get the info i want. they only display it as a website to you
there is undocumented api which is publicly accessable which some other people used to build similar tools/websites i'm trying to build already
and this weird website.
i found the robots.txt btw, i don't see a relevant disallow
like, they have stuff like this just out in the open: http://vortex.worldofwarships.eu/api/accounts/557809543/
the game uses this to display (public) player profiles
and if you dig thru the website you will find that in places as well wrapped in some html
If i'm using docker-swarm and have gunicorn setup, should docker-compose just be running 1 replica
hello guys can anyone help me with my Django issue?
I want to use a scheduler I don't know how to use celery or cron.
import schedule
import time
I want to run a task every day but how do i get the user i am running the task for when am not getting a request object
from .models import Deposit, My_Account
def interest_today(||request||):
active_deposit = Deposit.objects.filter(user=||request||.user.id, status=True)
interest_today = 0.0
if active_deposit:
for item in active_deposit:
if item.plan == "Basic":
interest_today += float(item.amount) * 5/100
if item.plan == "Business":
interest_today += float(item.amount) * 6/100
if item.plan == "Index":
interest_today += item.amount * 8/100
if item.plan == "Dynamic":
interest_today += float(item.amount) * 15/100
my_account = My_Account.objects.get(user=request.user.id)
my_account.interest_today = float(interest_today)
my_account.interest_this_month += float(interest_today)
my_account.save()
return print("Job Done for Today")
def mature_job (||request||):
list = Deposit.objects.filter(user=||request||.user.id)
for item in list:
if item.mature_date <= timezone.now():
item.matured = True
item.active = False
item.save()
time_do = "6:00"
schedule.every().day.at(time_do).do(interest_today)
schedule.every(8).hour.do(mature_job)
while True:
schedule.run_pending()
time.sleep(1)
I want to run these functions but the issue now is "request"
Help pls
Hello, wanted to know whats difference between flask_sslify and flask_talisman? or no difference?
Can anyone gimme a good idea for a school project? I'm supposed to be using Django and MySQL, and I don't wanna go with xyz management systems.
@nimble epoch from their description
flask_sslify
This is a simple Flask extension that configures your Flask application to redirect all incoming requests to https.
flask_talisman
Talisman is a small Flask extension that handles setting HTTP headers that can help protect against a few common web application security issues.
they are different
you shouldn't use flask_sslify because it haven't been updated since 2015 and still using python2
Hello @gaunt marlin
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
Thanks, though any personal recommendation?
@rapid bramble maybe a website that provide weather from api maybe
just a suggestion
One of my classmate is already doing that and we need to pick unique topics.
oh well
Thing is I can build but I suck at having ideas 😅
@rapid bramble another cool one is building chat web app with python socket
i built mine with nodejs socket it's javascript but it should work the same @rapid bramble https://basic-v3-chat-app.herokuapp.com/
you can push it to heroku (it's free hosting online)
like mine
Yeah that's alright, hosting isn't a big deal got VPSes of my own, I'll try building it
that a plus
😄
Hello @gaunt marlin and @rapid bramble can you help me out?
What's it?
@twin sable you can post question here, either me or other people will help
hello guys can anyone help me with my Django issue?
@twin sable I want to run a task on an interval. but i don't know how to work out these functions i want to run on schedule.
import schedule
import time
@twin sable imports
what is the error?
from .models import Deposit, My_Account
def interest_today(||request||):
active_deposit = Deposit.objects.filter(user=||request||.user.id, status=True)
interest_today = 0.0
if active_deposit:
for item in active_deposit:
if item.plan == "Basic":
interest_today += float(item.amount) * 5/100
if item.plan == "Business":
interest_today += float(item.amount) * 6/100
if item.plan == "Index":
interest_today += item.amount * 8/100
if item.plan == "Dynamic":
interest_today += float(item.amount) * 15/100
my_account = My_Account.objects.get(user=request.user.id)
my_account.interest_today = float(interest_today)
my_account.interest_this_month += float(interest_today)
my_account.save()
return print("Job Done for Today")
def mature_job (||request||):
list = Deposit.objects.filter(user=||request||.user.id)
for item in list:
if item.mature_date <= timezone.now():
item.matured = True
item.active = False
item.save()
time_do = "6:00"
schedule.every().day.at(time_do).do(interest_today)
schedule.every(8).hour.do(mature_job)
while True:
schedule.run_pending()
time.sleep(1)
@twin sable the function i want to run
Since it's going to be running on an interval, there would be no request.. so i cant do the updates accordingly
why would you take request as an input ?
can you explain the flow of the function ?
This is a views.py function but I want to take it out and run the function on an interval. query db and do some updates.
that is why the request.
call API ?
@gaunt marlin No
so what is the request for ?
@gaunt marlin normal request in django view
@gaunt marlin thanks
Hello, How do i run this schedule together with my django app ```py
import schedule
import time
from django.utils import timezone
from finance.models import Deposit
def interest_today():
Deposits = Deposit.objects.filter(status = True)
for deposit in Deposit:
if deposit.plan == "Basic":
deposit.interest_today = float(deposit.amount) * 5/100
deposit.save()
if deposit.plan == "Business":
deposit.interest_today = float(deposit.amount) * 6/100
deposit.save()
if deposit.plan == "Index":
deposit.interest_today = float(deposit.amount) * 8/100
deposit.save()
if deposit.plan == "Dynamic":
deposit.interest_today = float(deposit.amount) * 15/100
deposit.save()
return print("Interest Updated")
def mature_job ():
list = Deposit.objects.all()
for item in list:
if item.mature_date <= timezone.now():
item.matured = True
item.active = False
item.save()
return print("Job completed")
schedule.every().day.do(interest_today)
schedule.every(8).seconds.do(mature_job)
while True:
schedule.run_pending()
time.sleep(1)
do we talk about html,css and js here
do we talk about html,css and js here
@full steppe yes
ok thx
Lol here I thought you had a question
oh
how can i actually have my user download a file, which contains data from an sql query?
like they put in some parameters in my flask app, the db gets queried and the file gets downloaded
i was messing around with send_file
from what ive seen, send_file is mostly for static content
so
i kinda did that
but i dont think having each query dataset stored in the dir is a good idea
this does a few things ```python
@app.route("/surveyreports", methods=["GET", "POST"])
@login_required
def survey_results():
error = None
connection = db_connection()
cursor = connection.cursor()
phone_survey = PhoneResults()
start_date = request.form.get('start_date')
end_date = request.form.get('end_date')
if request.method == "POST":
get_results = "SELECT upload_timestamp, terminal_number, was_this_a_pandemic_related_call,what_was_the_call, was_the_inquiry_resolved FROM phone_survey WHERE upload_timestamp BETWEEN %s AND %s"
cursor.execute(get_results, (start_date, end_date))
query_resolution = cursor.fetchall()
#pandas_sql_query = pd.read_sql_query()
df = pd.DataFrame(query_resolution, columns=['upload_timestamp', 'terminal_number', 'was_this_a_pandemic_related_call',
'what_was_the_call', 'was_the_inquiry_resolved'])
data_in_excel = df.to_excel('output.xlsx', index=False)
send_file(data_in_excel, attachment_filename="output1.xls", as_attachment=True)
return render_template("survey_reports.xhtml", form=phone_survey, error=error)```
this is the traceback, i think there's an encoding issue? I don't really understand send_file that well
file = open(filename, "rb")
TypeError: expected str, bytes or os.PathLike object, not NoneType
also, it does actually send this file to my dir data_in_excel = df.to_excel('output.xlsx', index=False)
hello, i new to flask i follow this tutorial to create flask app https://www.digitalocean.com/community/tutorials/build-a-crud-web-app-with-python-and-flask-part-one and i finish the blueprints part, and when i run the app i got this error
flask.cli.NoAppException flask.cli.NoAppException: While importing "run", an ImportError was raised: Traceback (most recent call last): File "c:\users\sayahafidz\appdata\local\programs\python\python38-32\lib\site-packages\flask\cli.py", line 240, in locate_app __import__(module_name) File "D:\Python Project\Dream Team\run.py", line 5, in <module> from app import create_app File "D:\Python Project\Dream Team\app\__init__.py", line 4, in <module> from . import views ImportError: cannot import name 'views' from partially initialized module 'app' (most likely due to a circular import) (D:\Python Project\Dream Team\app\__init__.py)i have searched the error but cant fix it,can you help me..
sorry for my bad english.
@swift sky So your first issue is you are not generating the excel file right?
It seems you are not using the to_excel function properly
Ok... So you have the generated excel file correct?
And you can confirm it is anding in some directory?
@swift sky
Experienced devs here looking to upgrade your portfolios, what are you building? I'll take an idea or two to start building. My mind's not helping so much. But I can build
Which framework is best for app development and backend
@honest current I suggest you just try building something to solve a business need. How much experience do you have and what is your end goal?
@candid ermine It really depends on what you are looking to accomplish and I am guessing you mean a web app?
Yeah
@candid ermine Flask and Django are probably the two big Frameworks to use. Depending if you want a free to choose anything you want experience with slower development time or a batteries included approach with faster development time.
@devout coral which framework is easy to learn
@honest current I suggest you just try building something to solve a business need. How much experience do you have and what is your end goal?
@devout coral I have 4 years experience and have built multiple solutions for my organisation using Python and Javascript. I want something that makes me look like I'm a serious dev(LOL). But seriously something that demonstrates advanced knowledge in Python. Preferrably fullstack applications.
I mean, they both have complexities I prefer django
I too
I too
@candid ermine Use django. They'll have a structure and a default database set up already. You'll just focus on implementing your application.
@honest current Ok so build a full stack application. Not sure what the struggle is.
@honest current What industry do you currently work in?
@honest current What industry do you currently work in?
@devout coral Currently in Sales and supply chain management. We have built an ERP system to support the business functions like monitoring production of products, inventory management, analytics and reporting and many more.
You built that?
You built that?
@devout coral together with a team, yes. We also have APIs to integrate with front end apps and android apps and have integrated with third party systems like NetSuite and NuOrder. It's too much to list since it's feature rich.
@honest current So why can't you use that to show you are a serious dev?
I have signed NDA's and Non-compete. I have just read the documents and have a high level understanding of what it says. I'm looking to build something different so as not so get sued or something of that sort.
Ah
I see
The good news is you have all the experience I guess. My suggestion would be do some research (in your industry, your job, maybe pitfalls your current system has) to find a business need. Then seek to solve that issue with a web application
Okay.. I'll look for ideas. I'm thinking of a more efficient micro-financing system. Microfinance is a big thing in my country at the moment.
Where are you from?
Also, note that if you are wanting to make an app then sell it your best bet would go into a industry that does not have as much competition as finance.
anyone know how to use the paypal api?
https://www.paypal.com/cgi-bin/webscr
Hi, does anyone have a good tutorial for creating forms in Django and connecting them to functions
and saving the inputs in variables
hello. i want to use flask_restful but does it have any advantages over normal flask class based views?
ive read about it and i guess the conclusion was flask_restful but i want hear it from someone who has the real exprience using it?
@nimble epoch I was using flask_restful in my recent project and I am using flask class based views now. For me there is not much of a difference in it. There is small difference when accessing the sent parameters, i think
what is a good framework if I one day desire to make a native app and desktop version of my site?
react or angular?
Why would you make a desktop version of your app? That is a lot of overhead
For the organization that makes it I mean.
You would need an entire team dedicated to maintain it
it would be more like an electron app
not truly a native apop
just something that people think is native like discord
but I also need it to work on the web
electron is just for apps based on chrome isn't it?
@left jungle ok thanks
I have a website and yesterday everything worked just fine, but today the <input type="submit"> just isn't clickable anymore.
You know why that could be the case?
it is in a form elm btw
hi there, I want to use postgres ArrayField with django, but idk how to get rid of the warning 003 (arrayfield default should be a callable)
I tried this:
def get_default_email():
return 'Noticias, Promociones, Pagos, Compras'.split(', ')
communications = ArrayField(models.CharField(max_length=200), default=get_default_email())
But no luck
docs say: If you give the field a default, ensure it’s a callable such as list (for an empty default) or a callable that returns a list (such as a function). Incorrectly using default=[] creates a mutable default that is shared between all instances of ArrayField.
I have
<form>
<input type="submit">
</form>
</div>```
(just an example)
and the the form is somehow not working because it is in the div, but why and how can I counter that?
If I have the form elm outside the div, it works
try to add names to the form elements
<div id="comment_section">
{% for comment in comments%}
<div class="comment">
<h6 style="color:rgb(25, 89, 173);display:inline-block;">{{comment.author}}</h6>
<p id="comment_style">{{comment.text_content}}</p>
{%if request.user.is_staff or comment.author_id == request.user.id %}
<form action="" method="post">{% csrf_token %}
<input type="submit" name="delete_comment" value="del" style="right: 20px;position: absolute;top: 7px;"><!--style="right: 20px;position: absolute;top: 7px;"-->
<input type="hidden" name="comment_id" value="{{comment.primary_key}}">
</form>
{% endif %}
</div>
{% endfor %}
</div>
this is the real code
hey everyone! I am creating an app in flask! I had done something like this about a year back, but I left after I got frustrated with not being able to get a DB working. I literally had a revelation (At night in my bed) a year after I had abonded the project as to why it wouldn't work (lol that is kinda weird) so I am at it again.:)
Anyways, I was wondering if anyone here knows how to select every <li> in a <ul> from the python app? So basically, I want to know how to append every list item from a specific <ul> into a python list. Can anyone help me? Should I move the to a help channel?
Thanks a lot!
@surreal zodiac are you scraping webpage to get data?
@vapid acorn what do you mean by clickable, because when you put the code you provided into an web based html code tester it gives a del button that can be clicked
Another question from a non-web developer: what is the purpose of /siteapp/static/js/main.js?
Generally speaking
And are the javascript calls vulnerable to javascript hijacking
Does anyone else give their divs background colors when aligning them?
@surreal zodiac something like this should get you every li tag in ul tag and appending it to a python list ```
from bs4 import BeautifulSoup
data_list = []
soup = BeautifulSoup(html_source, "html.parser")
ul = soup.find_all("ul")
for x in ul:
li = x.find_all("li")
for y in li:
try:
data_list.append(y.get_text(separator=','))
except:
pass
Does anyone have experience with Django/React routing? Will I need to use webpack for such a combo?
I am storing some api keys in a database, and I can't just hash them since I need to know the values when I accept payments. I have been told I need to encrypt the keys in the database, then decrypt them using a secret key on my server - is this HMAC ?
Is there a free webhosting service to practise my django/flask?
without credit card info
Hello is it usual that browsers dont change code by making PUT or DELETE request and it just shows the arguments in the url? or im doing something wrong?
@tame thorn You do not need to host it to practice
Django: if I have four databases, all linked by the foreign key of the logged in user; I should be able to display a list of the posts created by that user?
Using class based views so far
Django: if I have four databases, all linked by the foreign key of the logged in user; I should be able to display a list of the posts created by that user?
@plucky tapir ...yes?
you mean 4 tables, right
Tables yes excuse me @vestal hound
@plucky tapir so what's your question
Can I just use a class based views generic list and display all the information.
I’d display the info according to if the inputs have a certain foreign key that matches the logged in user right?
@surreal zodiac something like this should get you every li tag in ul tag and appending it to a python list ```
thanks alot!.....
but I already knew that.
I want to get it from my own website
the one I am building with flask
Can I just use a class based views generic list and display all the information.
I’d display the info according to if the inputs have a certain foreign key that matches the logged in user right?
@plucky tapir yes...I think?
if you're asking what I think you're asking
but why do you have 4 tables
which of them is the post
Anyone have any suggestions/preferences for an ajax library when working with Django?
I suppose I want to pull information from the tables to display, the only way I’m able to do that now is right after I create something, it’ll send the primary key to a details page. @vestal hound
Is it difficult to implement a rest api into a django project?
How would I handle URL routing with Django & React?
@native tide are you making frontend & backend different?
How would I handle URL routing with Django & React?
@native tide can you elaborate?
@plucky tapir not really
@toxic flame thanks I’ll look into it then
@toxic flame thanks I’ll look into it then
@plucky tapir you're usingdjango-rest-framework, right
Yep @vestal hound
if you wanna go truly RESTful it might be difficult
since it's a bit of a weird style
but yeah, just play around with it and see how it goes
Charts.js seems the most popular way guys
that’s the django standard?
I need help in a quick task.. it'll require a bit of Django/flask (I don't know really).
I've got a python programme which takes 2 input and give one output string. I need to integrate it with HTML form such that two input can be taken from html form input field, and output should be sent to a div in html.
Please PM me if you can help!!
Hello I am trying to build an app that basically captures frames of a window and host those frames onto a webserver, currently all I have is a method that returns the frame of a application. Does Django support a way I can do a live feed to the server or would I need some other framework along side of django? Also what do I need to turn my frames into? A video? if so how would I do that? thanks for reading
Please @swift heron any replies, thanks!
@stable kite what do you mean by "making frontend & backend different"
@vestal hound Yeah so say on my /shop/ route I want to render a new React page. I don't know how I would handle that routing
@celest parcel You can do that with either Django or flask (infact it would be easier to just do it with JS). If you use a backend framework it'll be done via templates
@vestal hound Yeah so say on my
/shop/route I want to render a new React page. I don't know how I would handle that routing
@native tide do you want like a single SPA?
okay, actually the answer is the same
you want to host your React app as static files
Could you elaborate on that? Would that need something like webpack?
I'm not really an expert on this
but
you can check out whitenoise and django-spa
Webpack is what you'd use on the JS end
but right now the question is, given the files, how you tell Django to make them available at a particular route
Or I could handle routing on the client side with react-router but that has it's own issues and its mainly suited for SPAs
when using django with react you should let React handle the route and only use Django as an API
internal routing, yes, but you need to actually host the entry point as a static file
well, you could do it some other way I guess
@stable kite what do you mean by "making frontend & backend different"
@native tide i mean that if your react application is linked with django application using templates or not
@stable kite you can link your django app with react via templates?
@native tide yes
@native tide just get the the build of your react app & tell django where it is
hello everyone ! i am new to python and i am trying to build a web app for my portofolio, what do i need to build web?
Hello @uneven wadi you need languages like HTML, CSS, Bootstrap or Javascript for front-end and if you want to use python for backend you should learn Flask, Django, Pyramid or ...
and of course you can use javascript for your backend too. and if i were you i would choose just javascript instead of javascript and python.
@nimble epoch I was using flask_restful in my recent project and I am using flask class based views now. For me there is not much of a difference in it. There is small difference when accessing the sent parameters, i think
@left jungle, You said "There is small difference when accessing the sent parameters" you mean something like this => /post/int:id/?
@stable kite do you know of any articles about this? I can't find what you're talking abut
and of course you can use javascript for your backend too. and if i were you i would choose just javascript instead of javascript and python.
@nimble epoch why i should choose javascript?
as backend?
yes
because ive read that expressjs(framework) is even more popular than the others.
even django
I think Django is more popular than express js
But the most popular is node.js I thought
@native tide idk but ive read it in some places that its more popular because its javascript
But the most popular is node.js I thought
@native tide yeah of course and you gotta use express for routes and middlewares if im right...!
i dont have nough info
idk man😆 not my concern i dont use javascript
but i think javascript is better even in backend if you dont need to use python
@uneven wadi for more info check this out... It's a web framework that let's you structure a web application to handle multiple different http requests at a specific url. Express is a minimal, open source and flexible Node. js web app framework designed to make developing websites, web apps, & API's much easier. or.. Express.js uses many Node.js features to call functions anywhere. Many multifaceted tasks that take numerous lines of code and hours of ...
or... Node.js is a library for execution of JavaScript applications external to the browser. It comes to use when you want to create server-side programs or network a web application. Its elementary modules are inscribed in JavaScript. Node.js provides many frameworks to use e.g. koa, hapi etc. One of such frameworks is Express.js. It is more useful and popular than other frameworks of Node.js.
@stable kite also if you have the React components in a html template from Django, do they have to be written in JS? I use JSX, so will it have to be compiled?
or I think webpack handles that
I need a bit help.. Again 
I'm facing some bugs in deploying a flask app to shared hosting.
The app is functioning perfect in localhost, The main page of app is loading perfectly on webhosting as well but when I proceeds to another page instead of routing it send to main directory of domain in a directory view(showing all folders and all), Can anyone please help me out?
@stable kite also if you have the React components in a html template from Django, do they have to be written in JS? I use JSX, so will it have to be compiled?
@native tide you will need to link complied code of react
@native tide are you using create react app?
yea
Hello I am trying to build an app that basically captures frames of a window and host those frames onto a webserver, currently all I have is a method that returns the frame of a application. Does Django support a way I can do a live feed to the server or would I need some other framework along side of django? Also what do I need to turn my frames into? A video? if so how would I do that? thanks for reading please @swift heron any responses
Hello you all,
I'm trying to build a website with Flask and with MySQL Server Connection. I was planning to deploy this website on Heroku. As I searched and watched few videos on YouTube and came to know that you need to enter Credit/Debit Card details for using Database extension. I don't wanna enter Card details cause I own no card (Lol). Can anyone suggest some hosting website that'll allow me add Database for free ?
I came across a similar problem.
I'll make sure and inform
can i fix it?
I didn't understand, will you please explain in brief ?> can i fix it?
@hoary marten
Yaaa
Yeah, how do i fix it?
I'm searching it rn
🤦♂️
you think i havent searched the entire web already, it's not helpful that there's almost no information on bottle on the web in the first place...
🤦♂️
im having a cookie problem with bottlepy, can anyone help?
so i have this if request.forms.get('key') == key: response.set_cookie("authKey", key) redirect('/') it works but then:if not request.get_cookie("authKey") == key: redirect('login/key') and it just keeps taking me back to the login page, as if i never made and saved a cookie!?
Hello you all,
I'm trying to build a website with Flask and with MySQL Server Connection. I was planning to deploy this website on Heroku. As I searched and watched few videos on YouTube and came to know that you need to enter Credit/Debit Card details for using Database extension. I don't wanna enter Card details cause I own no card (Lol). Can anyone suggest some hosting website that'll allow me add Database for free ?
You could always put in something like a visa gift card but I can’t think of any free ones on top of my head, maybe webhost0.0.0.0 I think it is called something like that
Best of luck
Absolutely free web hosting with cPanel, PHP & MySQL for a stunning blogging start. Get free website hosting together with a free domain name at no cost at all!
how can one live without a bank account
Hello I am trying to build an app that basically captures frames of a window and host those frames onto a webserver, currently all I have is a method that returns the frame of a application. Does Django support a way I can do a live feed to the server or would I need some other framework along side of django? Also what do I need to turn my frames into? A video? if so how would I do that? thanks for reading please @swift heron any responses
how can one live without a bank account
Real question? or kidding?
Good Morning Everyone, What sort of projects is everyone working on today?
@hard spear For testing why don't you do it all locally?
I'm testing sites on Localhost for almost 2 3 months now. I wanna learn things about deployment. That's why I'm trying to do on Heroku
Thanks for all of the Replies.
This was Informative.
Good Morning Everyone, What sort of projects is everyone working on today?
@devout coral a self-hosted, password-protected order-of-service list.
@surreal zodiac Cool, making like a web app for that?
Lol, are you using a framework for the back end like flask or django?
flask
Cool
I am trying to write data to a file, but since I have to call file.write() inside a function (route), I can't call file.close() to save it, since I want to reload the file later.
and I can't append
disregard that last comment, it is non-relevant
@hard spear If you want some experience with deployment how companies would normally do it you would probably want a vps or some rented server. Also if you have a old computer lying around turn that into your server.
@hard spear If you want some experience with deployment how companies would normally do it you would probably want a vps or some rented server. Also if you have a old computer lying around turn that into your server.
@devout coral I have deployed a few time to AWS and to heroku
and this is actually going to be on a rPi cluster
Actually, AWS has a free tier
@devout coral I have deployed a few time to AWS and to heroku
@surreal zodiac Okay I'll definitely look up to it
@surreal zodiac Okay I'll definitely look up to it
@hard spear ???
Yeah I would say do ubuntu on a aws free tier and you should be good.
Sorry, I was trying to reply to a diff message
I doubt your app is big enough to need more resources than their free tier.
Yeah I would say do ubuntu on a aws free tier and you should be good.
@devout coral Ohh, Okay
I doubt your app is big enough to need more resources than their free tier.
@devout coral Yeah it's a small app with almost 20 Webpages, and some JS and Flask as a server
That's so insightful brother, Thanks for the help :)
You are welcome
@devout coral I actually am quite experienced with AWS. I created something like https://restream.io/ except.... free.... and it can stream to as many platforms as you like (except obviously that might cost money if you put too many servers)
@surreal zodiac Oh that is cool, I myself am not extremely familiar with it. I have only deployed 2 things on it and one was just storage.
is the purple text a background image?
ooh ok thanks
how can i move the span from there down to where i've drawn a square?
@strange ocean just add some top margin
yep waiting for @nimble epoch
just have them in divs? With the image above?
thanks
ok @strange ocean you can add margin 😅 but you can do it => add an height to your content and add the display to flex and set align and justify to center
lmaoo thanks
yw but margin one is easier sorry about wasting time😁
i just wanted to tell you because i myself prefer the second one
what url should I put the backend of website on? (example.com/what/what?)
the second what is the arg?
Im just wondering what args I should use in the url
im using a backend api and im not sure what url I should put it on, I dont want people to just be able to guess the url
I also dont want to put authentication on it either
there gotta be no difference between flask and django if its like "url/what/?what=val" its /url/what/<what>
you mean this?
Your not understanding the question but thats ok, ill figure it out myself thx
yw 😆
hey guys question
i have a span with the background color
i need to increase the size of the background of the span
.code {
color: lightblue;
background-color: grey;
border-radius: 3px;
}
this is the css of my span
When creating a APP, do you CD into anything first? I had a problem with the access of when I’m importing things, and it dosnt find it correctly because of the layout
@nimble epoch ?
@strange ocean You would have to make the element bigger.
I am trying to put a Django program onto a public domain would I use something like MySQL to do that?
@torpid pecan It depends. According to SQLite3they say their database is ready for production. The only problem with it is the fact that only one operation can be done on the database at any one time.
I use MySQL in my production environments and I would recommend you do as well. It is not hard to set up.
when i run my html code on chrome, the image shows up
however in the case of microsoft edge, with the exact same code, it doesn't
additionally the javascript in order to copy text from the screen which i wrote doesn't work
could anyone help?
Is there a way to mark a Django block as "required"? i.e., all templates that extends this must have this block filled
@spiral smelt Why do you need that functionality?
Just to make sure that a developer don't forget to override the default
@strange ocean Different versions and browsers support different things. You would need to do some research.
I'd want to override the content of <title> tag
I have a base html to extend from
But I want to make sure all extensions change the title
You want to change the title based on the template?
This is what I do in my base.html
{% if title %}
<title>{{ title }} - Division 12 Management System</title>
{% else %}
<title>Division 12 Management System</title>
{% endif %}
Then if I want a title I just pass it in the view
Not rendering
Say in base.html I have this:
<title>{% block title %}{% endblock title %}</title>
I have another.html
{% extends 'base.html' %}
I want to make sure another.html cannot be rendered without a {% block title %}
Yes, I understand you want to have multiple pages to have different tittles but as far as I am concern you cannot have a block required.
Okie thanks
Yeah I can't provide a default or pass the title as parameter
I'll see what I can do. Thank you for your help!
Hey, maybe someone else here has a better idea? But I really do not think template languages provide such functionality
I'm looking into creating a custom linter that nags the developer if they don't have {% block title %} 😆 They'll probably hate me but whatevs
Interesting.
I can tell you I added that title functionality to my page but I have yet to pass title in any of my views lol
I mean that'll require the developer to remember to pass the title in the view
Just kicking the problem down the road I think
Also I kinda want to front-end to be able to change it without dealing with too much code (Python code)
Thanks for your input!
Hi I'm looking for some help with Django. Everythings kind of hacked together lol but anyway I'm trying to render a form and model data to a generic listview but the issue is when the form renders to the template the for loop in my template iterating over object_list doesn't appear. If I comment out the form code it appears. Anyone have any ideas on what I might be missing or doing wrong?
@strange ocean sorry man i wasnt maybe next time.
@strange ocean what happened?
I am looking for a wtf forms alternative that supports type checking and preferably plays nice with flask and flask slqalchemy
posted and self answered right away
@lucid kite What about WTForms doesn't support what you want?
oke another similar question, relating recommended aproach for API endpoint:
So Discord guild can have suggestions from members, this is currently my plan for endpoint to get all suggestions from specific guild:
path('private/guilds/<int:guild_id>/suggestions/', SuggestionDataView.as_view()),
My question is which is better from below:
Get specific suggestion
1 path('private/guilds/<int:guild_id>/suggestions/<int:suggestion_id>', SuggestionDataView.as_view()),
2 path('private/guilds/suggestions/<int:suggestion_id>', SuggestionDataView.as_view()),
3 path('private/suggestions/<int:suggestion_id>', SuggestionDataView.as_view()),
I don't like 1 because to get specific suggestion there is no need to know guild id as all suggestion IDs are unique.
I think I like option 3 the most, but is it okay to create endpoint like that just for one thing?
This is more of a recommended aproach question.
uh some sites say to avoid nested aproach some say it's good 
well KISS so I'll go with 3d 
altho then it isn't self-explanatory, suggestions for what? maybe 2 is best, but then that might conflict with the way all suggestions are fetched becase it uses guild_id and option 2 does not
Yeah Id love some, here it is @devout coral
{% block content %}
<h2>Places Searched For</h2>
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Search</button>
</form>
<ul>
{% for users in object_list %}
<li>{{ users.raw_user_input }}</li>
{% endfor %}
</ul>
{% endblock content %}
So I've been looking into creating a method for get_context_data but I'm not sure if I'm on the right track lol
@warm igloo wtf forms doesn't yet support type checking ( eg : by mypy )
I could use some help with a Django project. I am trying to write some docs for my group so they can clone my code and start working on it with me but whenever I clone the project to a new directory and run any of the manage.py commands it fails with error django.db.utils.OperationalError: no such table: oracle_category. If I comment out my apps urls in urls.py run manage.py migrate and then uncomment the command and run the server it works just fine. Is there a configuration setting I am missing or did I .gitignore too many files?
How did you add files to .gitignore? @simple oxide And what are your database settings?
I typically use: https://www.toptal.com/developers/gitignore/api/django and have no problems
Okay that matches what I have mostly.
My database settings are the default right now.
I would like to dockerize the project and switch to an external db but I am having trouble with just running the project on another computer
Yeah docker is great, that's what I'm currently running. Hmm. Does the error provide other information?
I'll grab the stack trace one sec
I could use some help with a Django project. I am trying to write some docs for my group so they can clone my code and start working on it with me but whenever I clone the project to a new directory and run any of the manage.py commands it fails with error
django.db.utils.OperationalError: no such table: oracle_category. If I comment out my apps urls inurls.pyrunmanage.py migrateand then uncomment the command and run the server it works just fine. Is there a configuration setting I am missing or did I .gitignore too many files?
@simple oxide before running the server you need to migrate your databases
^
Even the migrate command doesn't work
Even the migrate command doesn't work
@simple oxide show error
or do you mean it runs with no errors
oh okay never mind I get what you mean
what was the last thing you did
before this started happening
I am not sure what the last thing I did that caused this. This is the first time I have tried to run the app from anywhere but the place I created it
If you run the app in the original directory does it still work?
Hey, so I am trying to use a bot to post my server member count on my website, using flask and discord.py. Here is my code: ```py
from flask import Flask, render_template
import discord
from discord.ext import tasks
from functools import partial
from flask import Flask
from threading import Thread
client = discord.Client()
app = Flask(name)
members = 0
@client.event
async def on_ready():
print('Ready!')
@app.route("/")
def index():
global members
guild = client.get_guild(id)
members = guild.member_count
channels = len(guild.channels)
print(members)
return render_template('index.html', members=members, channels=channels)
if name == "main":
partial_run = partial(app.run, host="0.0.0.0", port=80, debug=True, use_reloader=False)
t = Thread(target=partial_run)
t.start()
client.run('token')``` When I type flask run in terminal, it works completley fine. But since that is just a developement server, I installed gunicorn and then typed gunicorn app:app in terminal. Then it went into a big loop of starting and crashing. It eventually gave the error: RuntimeError: Event loop stopped before Future completed. but that was probably because I stopped the code. Any ideas on running this?
If you run the app in the original directory does it still work?
@worn basin Yes
Hey @simple oxide!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
DM me
k
Does python manage.py makemigrations return the same result?
yes
I see the part 'category': forms.Select(choices=Category.objects.all(), attrs={'class': 'form-control'}), It's part of a forms.Modelform that is has a forms.Select widget. My guess is I am using it wrong by populating it with a table that may be empty
modify migrations manually?
@vestal hound no
is your database empty?
Yes
So delete the db.sqlite3 file and my migrations except __init__.pi
is your app called oracle, incidentally
Yes
Same error after deleting db and migrations
So when you comment out all your local app urls can you narrow it down to a specific app that breaks something(is it just one)?
I only have the one
Same error after deleting db and migrations
@simple oxide did youmakemigrations
like delete database and migrations, then makemigrations and migrate
Yes
!?
show your initial migration file
0001_initial.py
that's not right
wait so just checking
you also clone the DB file right
I have 5 migrations do you want to see them all or just the one?
No I don't clone the db file
That is in the .gitignore
you have to
I believe
because otherwise your migration state will be inconsistent with your DB state
It's in the common .gitignore
your app expects that all those tables exist
but if you don't clone the DB they don't
Shouldn't migrate take care of that
Isnt migrate for moving model changes over to the db?
yes
but if you migrate
then from the perspective of Django, the DB has been updated
right?
but it's a different DB
okay actually
I'm not sure how Django handles migration state on SQLite
wait, go back
do you share your migrations?
hm
Maybe. If you're thinking of switching over to docker why not just try that?
If you look at the initial trace somewhere in the middle it complains about a widget one of my forms.
so it seems that the problem is
If you look at the initial trace somewhere in the middle it complains about a widget one of my forms.
@simple oxide yes
but only because it's looking for a category table
that was you right? lol
which doesn't exist
as opposed to being empty
which would work, just that your select field would have no options
How else should I populate it?
This is the form https://paste.pythondiscord.com/aneyawajef.py
no, it's fine
as in what I'm saying is that
your migration state is weird and I'm not sure why
try cloning your DB file
and see if it works?
Okay
Cloning the db works
Maybe. If you're thinking of switching over to docker why not just try that?
@worn basin I would love to go this route but all the guides I follow cause the same errors for me because it has to create a new db
yeah it's definitely something to do with DB state
Cloning the db works
@simple oxide where are you running it?
like the place you cloned to
adn
when you clone
do you delete
the DB file there?
before running makemigrations
i.e.
delete -> clone -> makemigrations
When I delete the db file I get the errors from before. When I don't delete it it's there and there are no migrations for it to run
anyway
you should clone the DB file
because
in a real situation
you'd have a separate database
which every instance would connect
Right
to
so you get consistent state
since you're using SQLite
you don't have that
therefore to achieve the same thing you need to clone the DB
But what about when working with different stages like dev to prod
But what about when working with different stages like dev to prod
@simple oxide can you elaborate
you mean like a staging DB
and a production DB?
Right
If I were to deploy this app I would have to run this app in an environment that didn't have a db yet and it would have to create it from the migrations I have so far
right
yeah, so you'd have a database server
and you'd run your migrations while connected to it
But I can't even run the migrations. That's my point
yes
with a proper database server
you would.
because migration state is stored in the database too
Even when I make the switch to postgresSQL I have the same problems
Even when I make the switch to postgresSQL I have the same problems
@simple oxide you did?
how did you do it
I followed this guide to set it up https://docs.docker.com/compose/django/
@vestal hound @worn basin The problem was the form.
Because I was using a forms.ModelForm I thought I had to manually set the widgets for my fields
Glad you figured it out!
Me too. It was driving me nuts. Hopefully this mean I can migrate to docker and postgres a little easier now. Thanks for all you help
@worn basin you ever get that weird issue figured out?
No, Im guessing Im doing something obviously wrong though lol
Alright, and the problem is when you have form as p it does not do whatever the rest of the template has?
correct, the view is a generic.ListView
Im also using a modelform so that might have somnething to do with it
Ok, so removing the line {{ form.as_p }} makes it work though? With no further modifications?
80% sure let me double check one second
All forms are handled the same way so it should not matter.
Also, you are not receiving any errors in the console right? Like any 500 or 400 errors.
well it was but I changed something earlier before I took a break and now nothing is showing, let me figure that out first
Lol ok
I wasnt no
Let me know once you test
Oh okay so I broke it in the same way again lol. So when I comment out both the corresponding code for forms in views.py and my template itll display
Which isn't what I'm trying to achieve so Im not even sure if Im going in the right direction with using a generic.ListView or I misunderstand how forms work maybe, I'm not certain
Have a page with a form input alongside previous form entries
I don’t really bother with class based views.
Yeah I was strongly considering just using function views
Wanted to learn about class views though
They are easy, but restricting.
have one question I wnt to make private api I wnt to know can I host it with EC2 I mean same like my bot?
I wnt to use django
You’d probably want to make your own subclass of the generic view clas
Alright, Ill look into that. Thank you
Hey guys, looking for some resources to help me integrate a GitHub Code repo into my current Django project.
Not looking for answers just wanting to get my hands on something I can read (other than the Django documents)
im trying to do something like a CI thing in flask, and these are what i understand:
- my config.py file will have ProdConfig, DevConfig, TestConfig
- in my
create_appfunction i would haveif app.config.from_object["ENV"] == "production":#useProdConfig - in heroku config vars i would have
FLASK_ENV = "production" - and then configure github actions (to be learned)
is that how is it done?
What is your question?
is my understanding correct? i cant really test it right now
Not sure where the best place for this would be but I'm looking to hire a developer or two to help me restart and finish my website here-- https://morning-crag-98867.herokuapp.com/
Trying to create each feature one at a time to be modular and implemented into some other related projects
Contracted pay and equity split are both options and I can discuss the projects further in DMs
does anyone know how to make it so it saves to a google spreadsheet after clicking a button
im like making a sign up thing
├───btre_project
│ ├───static
│ │ ├───css
│ │ ├───img
│ │ │ └───lightbox
│ │ ├───js
│ │ └───webfonts
│ └───pycache
├───pages
│ ├───migrations
│ │ └───pycache
│ ├───templates
│ │ └───pages
│ │ └───partials
│ └───pycache
└───static
├───admin
│ ├───css
│ │ └───vendor
│ │ └───select2
│ ├───fonts
│ ├───img
│ │ └───gis
│ └───js
│ ├───admin
│ └───vendor
│ ├───jquery
│ ├───select2
│ │ └───i18n
│ └───xregexp
├───css
├───img
│ └───lightbox
├───js
└───webfonts
hey iss this filestructure correct
i have static at 2 places
@winter spindle post your code of settings & urls
Hey @winter spindle!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
because people forget the settings &adding url for statics in urls
no i have added all tht
i dnt know like there is someproblem with my structure
actually the thing is tht i am following a tutorial and like ig i fucked up in between
so yeah its like .. messed up now
What is the naeme of a proxy you dont do all your internet traffic over, but you send like just one package of data to and also pass an ip of the receiver
*working with python sockets, not http
@winter spindle try this,
STATICFILES_DIRS = [ os.path.join(BASE_DIR , 'btre_project/static'),
os.path.join(BASE_DIR , 'static'),
]
ohh okay
also remove STATIC_ROOT
oh okay i will try
actually like the problem isnt here
my file structure is fucked upp
like which is a better way
no you did mistakes in settings
like the tutorial which i was following created a new app
no no
my css and bootstrap was rendering fine
my images werent rendering
like they were given in html
that because they were in different locations
and tht file location was wrong
yea yeah
tht was the problem
i am gonna delete every thing and start again
like i am pretty new to all this
what should i do bro ?
@stable kite
i am new to django
just see django docs & django official tutorial
no first do tutorial &then docs it will be easy
