#web-development
2 messages ยท Page 188 of 1
if JWT Token will be not decoded back with your secret key, then it was tampered or expired
You can delete his cookie immediately with request sent to server about room deleting
u a welcome
xD, the problem was solved with just having stuff client side
no delay between requests = no problem
there will be still micro delay though, since stuff in client browser is launched in async mode
but that should be not an issue
<form id="LoginForm" method="POST">
{% csrf_token %}
{{form}}
<button type="submit" class="btn">Login</button>
<a href="{% url 'users:register' %}">Have an account?Login</a>
</form>
why im not getting the input type n all stuff by django
@eternal blade waiting for u lord
Show your code
html code?
<div class="account-page">
<div class="container">
<div class="row">
<div class="col-2">
{% load static %}
<img src="{% static 'login.png'%}" width="100%">
</div>
<div class="col-2">
<div class="form-container">
<div class="form-btn">
<span onclick="login()">Login</span>
<span onclick="register()">Register</span>
<hr id="Indicator">
</div>
<form id="LoginForm" method="POST">
{% csrf_token %}
{{form}}
<button type="submit" class="btn">Login</button>
<a href="{% url 'users:register' %}">Have an account?Login</a>
</form>
<form id="RegForm" method="POST">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="password" name="confirm_password" placeholder="Confirm Password">
<button type="submit" class="btn">Register</button>```
showed so much to tell
using js in this too
and this page by js combines 2 form
main is
<form id="LoginForm" method="POST">
{% csrf_token %}
{{form}}
<button type="submit" class="btn">Login</button>
<a href="{% url 'users:register' %}">Have an account?Login</a>
</form>
<form id="RegForm" method="POST">
{% csrf_token %}
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="password" name="confirm_password" placeholder="Confirm Password">
<button type="submit" class="btn">Register</button>```
Hi can anyone help me to make a simple register and login system?
I made a registering one but im not sure if it's correct pls check You always help me please help me now too
how do you disable validation for an input field? (only one input field not the whole form)
yo do you have good sources to learn django? and backend web dev? Im learning https://developer.mozilla.org/fr/docs/Learn/Server-side/First_steps/Web_frameworks but i would like other sources too
I'm creating kind of Roadmap site so I will first ask usersome question's what he wanted to learn then will give result according to what he want to learn how can I do it on web (using Django in web) @eternal blade
Hi guys I'm new to django and I have to add an excel file upload to my web app, can anyone help me with that?
is there anyone good with Fastapi ? i have some bug with alembic and postgreSQL connection
A guide for how to ask good questions in our community.
Any suggestions on a good hosting provider? (To host django api or app)
AWS
But ive saw some reviews complain s that its hard to setup
hmm same but i dont mind a bit of tutorials to show my way round cause i heard its really good
Okay thanks for the suggestion!
no problem
You will have to save the user input and iterate over it in the html and display the data
@rotund perch asc wr wb
?
@rotund perch do you just need a RDP?
is that a hosting method? Whats the diff between it and the other hosting methods
No diff
I mean like performance
Anyways if thats a good method, I dont mind suggesting me some providers
I use AWS but if you just want an RDP there are cheaper providers
Like hetzner or DO
Okay, Thanks !
Do u have some Code I just wanna copy paste that ezz
@dusk portal that's the opposite of learning...
i think thats against the rules
Hello guys. So I changed my html file to have a lot of blocks to make it easy to read. But the only thing that's running is the loading screen in an infinite loop. What's surprising is the fact that even when I comment out the loading screen div the only thing that appears is the loading screen and not the actual webpage.
{% load static %}
{% block title %}
Rhitam's Website
{% endblock %}
{% block content %}
{% include 'welcome-content.html' %}
{% endblock %}
<!-- {% block container %}
<div class="loader-wrapper">
<div class="loader">
<div class="image">
<i class="fa fa-dumbbell"></i>
</div>
<span></span>
</div>
</div>
{% endblock %} -->
{% block javascript %}
<script src="{% static 'main/welcome/base.js' %}"></script>
{% endblock %}```
base.html doesn't even have the javascript
even when I comment out the entire js the same thing happens
Any help is appreciated! I'm having to put repetitive html codes on every webpage because of this.
base.html doesn't have JS but you're extending it and adding JS to it:
{% block javascript %}
<script src="{% static 'main/welcome/base.js' %}"></script>
{% endblock %}
Yeah even when I comment this out I get the same output :/
maybe the webpage is cached then?
no used a diff browser and the same thing happens
does welcome-content.html have any JS
Hello, will the SEO be impacted with a .ps domain name ? (I want to name my site comicu.ps, which stands for ComicUps)
i have 20 hrs , and they have said u can copy paste + i have decided to learn that for sure after this work
@opaque rivet How did the design changes work out? What did you end up with?
Two additional questions. Did you do a hard-reset of the cache? (ctrl+F5)
Did you try incognito/private mode?
Just questions to rule out caching absolutely.
@ionic raft ended up having black buttons on large viewports and light blue buttons on mobile. Now animating the site and trying to get a draggable grid (and it's a pain)
Ooo....interesting. Good luck. ๐
Hello @dusk portal I can try ๐
u know web scraping
Very little. I worked briefly with Beautiful Soul and Selenium about 3-4 months ago. I am very rusty and would be surprised if I could help with complex troubleshooting.
I wanna scrape Udemy Courses by some data which user will enter in my form
Well, I would start by checking their terms of service for such scraping. When a paid service doesn't have an API, going to web scraping can be legally problematic.
That said, if you are looking to scrape what courses are available, my sense would be that Selenium may be a good starting point.
IIRC you can also check the URL with the path robot (specifics for you to research) to see what scraping Udemy allows.
Anyone here familiar with the Pyramid framework and it's official Quick Tutorial? I've reached a step in the tutorial where suddenly none of my code runs, with the last error in the traceback being: ModuleNotFoundError: No module named 'tutorial'. This after successfully completing each step of the tutorial up until my PC crashed. Now none of my tutorial code runs, and I'm hoping that someone knows the tutorial because otherwise it's one hell of a lot of coding to show here
What are you looking for? What type of data?
Their API provides a decent bit of information
Also, scraping them Udemy is a violation of their robots.txt: https://www.udemy.com/robots.txt. They only allow things like that on their /api-2.0/ route, which you'd be better off just using through traditional REST API interaction methods.
That is not surprising at all.
OMG... ๐
So, you know when you've been trying to find out why you can't get the pk from the get_context_data function in the view, and then a couple of hours later you realize you built the url for the CreateView WITHOUT passing a pk over?
Yeah...that.
๐
so i cant scrape courses link with title to give like a roadmap as it's our hackathon task
does anyone know how to fix this probblem im trying to run a flask server but it seems to not working have all requirements installed
Hi i am working in django
I have a html form with hidden field.
I tried to get the data as
If request.method== "POST":
data = request.POST.get("field nsme")
But i am getting nothing.
anyone knows how to make firefox in dark mode 
As was suggested, I'd check https://www.udemy.com/robots.txt to check what they allow. If you try to scrape in contradiction to their robot.txt it is an illegal activity. If you're engaging in an activity with a hackathon that is asking you to engage in such activity I would suggest considering another activity.
In short, I expect that a paid service like Udemy wants you to use their API. They get control over the data exchange that way and everyone is happy (and behaving in a legally acceptable manner).
Web scraping is filled with ethical grey areas and no-goes.
Who is ever going to enforce webscraping? It's impossible.
Pls I need help
Having errors trying to get the Book_id
Showing me function object has no attribute โobjectsโ
if you want help
post text
not screenshots
and especially not pictures of screens
Def index(request):
Context ={
โBookโ : Book.objects.all()
}
render(request, โBook/index.html, context)
While loading it on the page
It says the function attribute has no attribute โobjectsโ
how would I update a site with an event without reloading the page in quart?
https://coursevania.com/
But how this site is doing same thing
Hey, it's your call what to do. I'm just relaying my understanding of the world of web scraping
How can I do
I have 6 hrs left

U know any site any course
Even 1
Which I can scrape n can show
I can win
We have other things done
ok someone please help
im trying to hyperlink the word accommodations to the id tag "faq13" but its not working
the word is clickable but it takes you nowhere
what am i doing wrong?
Get the metadata for the required field and use it to query the required field data
what does "query" mean ? this is django. thanks.
I am not completely clear on what you're asking for. But, when you use an <a> anchor tag in html for an in-page hyperlink you need two parts to it. If on the other hand, you're trying to create a link outside the site, then the href value you have is not going to work.
An in-page anchor tag should have two parts. This first anchor tag is the clickable link:
<li><a class="heading-link" href="#1-Introduction">Introduction</a></li>```
This second part is where the above link will take you to in-page:
```html
<h3 class="heading-link"><a id="1-Introduction">1. Introduction</a></h3>```
As a rule, posting screenshots for code is not very helpful. It is much better to post the code in markdown style, with back-ticks.
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
As a side note, I just released v0.3.0 of LanesFlow. There's now an hour tracker ๐
There are two options. You can either track hours for a pool of prepaid hours for the client organization, or you can go with billable hours. This is the prepaid hours option in play.
I think this needs a few filters....But otherwise, I welcome any thoughts. If anyone has experience with this sort of thing and has feedback, please share.
im still confused about this can i pm you?
I'd prefer not to DM troubleshooting. All benefit by keeping it here
How to get full video url in django with FileField?
Do you want to store the video, or just link to the URL?
why wouldn't what i have work? i have the same setup for my "return to top" button
Can you paste just the code? Working with screenshots is brutal for reviewing code.
Use three backticks...
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I am showing you what I know works ๐
<h2 id="faq13">I am looking for accommodation for the event, where is best to stay?</h2>
<a href="#faq13">accommodations</a>
first line is on my FAQ page, second line is on the home page
Video is already stored
Url is media/videoname.mp4
I want to send that video to google translate api so i need full path i think?
im trying to link the word accommodations to the id=faq13 on the FAQ page
I would use a CharField in the model to store the raw url. I'd review API to ensure I'm sending it according to their guidelines.
Take a look again at your code and the snippet I've provided. If I solve this problem for you you won't gain the most learning from it. You've missed something in the id tag
I think what your talking about is class="heading-link"
but I don't know what I would put there in my case
No. Take a look at the beginning of the tag...you have id...but where is a?
sorry I'm like 3 weeks into coding
It's all good. The receiving tag is not an anchor. It's missing the <a...
Like I said, look at what I posted.
Sorry for the inclusion of the css class. That was distracting
Can you post your code...and please NOT screenshots
i dont know how to
Do you know how to select text and copy/paste?
Just copy the two tags...not the whole html file
I'm going to type them up the way I'd do it...give me a minute...
i have been copy and pasting
<a href="#faq13">accommodations</a>
<a id="faq13">I am looking for accommodation for the event, where is best to stay?</a>```
i have that exactly and it wont workl
Then I can guarantee you you're missing something. I have that exact layout working for me.
Coding is very meticulous. I've spent 2 days trying to find errors such as : instead of =
does it matter if it is linking from the homepage to a FAQ page
This is why you need to post your code. I can't help you unless you work that out.
I suggest you work out how to read the following along with copy/paste
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
OOooooooo. YES. That's another page. Then you need the URL for that page
Also, I suggest you study the art of asking a good question. Seriously. If you want help from other programmers you're going to want to learn this:
https://pythondiscord.com/pages/guides/pydis-guides/asking-good-questions/
A guide for how to ask good questions in our community.
Ok. I've got to go to bed. Best of luck. I know you'll get there....
finally got it
thank you for real, i spent hours trying to figure this out
Once I worked out you were trying to get to another page, that showed why it wasn't working.
On the plus side, you now know about in page links as well as links to other pages ๐
On a completely side note, I just got my web application emailing out html emails when events happen ๐
I have to say, seeing a polished email arriving from an automated web application like that...makes my heart very happy ๐
Thank goodness for CONST variables ๐
Hello? Anyone here wants to make a django project with me
How can I filter on the basis of queryset of foreign key in Django ??
`class CsvFile(models.Model):
file = models.FileField(upload_to='csv/' )
class FileSearch(models.Model):
file = models.ForeignKey(CsvFile, on_delete=models.CASCADE)
pattern = models.CharField(max_length=500)
status = models.CharField(max_length=100)`
Like these are the model
qs = CsvFile.objects.filter(file__contains="xxx")
now how can I get all File search whose file foreign key is in qs
@grave raft qs.filter(file_set=CsvFile object)
(django) i have a order model and i have thought of adding datetime fields placed paid dispatched delivered can you suggest me improvement to the model?
what are the stages of an order?
The stages you've listed cover the core steps. But an ordering process will vary by business depending on controls, etc.
yes its just a personal project and i want it to be universal. placed field gets a datetime when the user checks out, do you have any idea about adding a field so indicate the order is being worked on?
I've been working with processes as a business analyst/consultant for 25+ years. There is no such thing as a "universal process".
I would add order_status = models.CharField(choices=ORDER_STATUS_CHOICES, default='1) Order placed')
That is from memory, so check syntax....
You should create a CONST tuple at the start of the file for ORDER_STATUS_CHOICES...
the fields i mentioned are datetime fields
I know. I offered syntax for a choice field.
do you think i should add a field which would mark the order is being worked on?
i have one more question how do i provide the interface for disptached, delivered and paid (in case of cod) in my custom admin dashboard?
how about empty post form with csrf token for dispatched, delivered and paid stages which sets their values?
and showing the form corresponding to current stage?
How can I dynamicly calculate in django, days delta along queryset
Is sending an article i wrote on django here against the rules?
For each row? in the queryset
Annotate should do that i guess
Basicly I have a model with a field, date_to, I wanna calculate how many days are for each item
Annotate should work
so i wanna add a field, expires_in_days = date_to - now()
ohhhh
yea for example lets asume, item expires on 6.9.2021
i wanna add a field expires_in_days = 1
6.9.2021 - 5.9.2021
etc..
can you add it as a class method and call it whenever you need instead?
I hope I'm not giving bad advice
Annotate and order by annotated field
Unless you want to do it in multiple places
We'd have to think of something more efficient
i need in multiple ...
hmm
even if i do forloop, i cant after that execute order_by
i can by sorted and key
found something on SO
Daniel Roseman's solution makes a calculated field an attribute of a Model, however it does not make it accessible via QuerySet methods (eg. .all(), .values()). This is because QuerySet methods call the database directly, circumventing the django Model.
Since QuerySets access the database directly, the solution is to override the Manager's .get_queryset() method by appending your calculated field. The calculated field is created using .annotate(). Finally, you set the objects Manager in your Model to your new Manager.
Here is some code demonstrating this:
from django.db import Model
class InvoiceManager(models.Manager):
"""QuerySet manager for Invoice class to add non-database fields.
A @property in the model cannot be used because QuerySets (eg. return
value from .all()) are directly tied to the database Fields -
this does not include @property attributes."""
def get_queryset(self):
"""Overrides the models.Manager method"""
qs = super(InvoiceManager, self).get_queryset().annotate(link=Concat(Value("<a href='#'>"), 'id', Value('</a>')))
return qs
class Invoice(models.Model):
# fields
# Overridden objects manager
objects = InvoiceManager()```
Now, you will be able to call .values() or .all() and access the newly calculated link attribute as declared in the Manager.
It would have also been possible to use other functions in .annotate(), such as F().
I believe the attribute would still
basically overriding the default manager
hey im trying to use render_template from flask library but i get an error
the error is this:
Traceback (most recent call last):
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "c:\Users\gg\Desktop\html\1.py", line 8, in home
return render_template("web.htm")
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\templating.py", line 148, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\jinja2\environment.py", line 997, in get_template
return self._load_template(name, globals)
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\jinja2\environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File
"C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\templating.py", line 59, in get_source
return self._get_source_fast(environment, template)
File "C:\Users\gg\AppData\Local\Programs\Python\Python38\lib\site-packages\flask\templating.py", line 95, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: web.htm
even though my web.htm is in the same folder with the python file
@app.route("/")
def home():
return render_template("web.htm")
(context django) i have a order model with datetime fields placed, paid, dispatched, delivered
i want to show status of the order depending on these fields should i write model method or filter?
Thanks this helped a lot!
Already pretty decent with Python, but Iโve decided to rewrite the backend of a personal project in Django (I tried NodeJS first but it just feels like it barely works lol). Iโve never used it before, but have been interested for a while since I like using Python in general. Whatโs the best tutorials you guys know of for building APIs with Django?
Two scopes of django
its a book, highly recommend
includes best practices and good explanation
How can I make custom responses for Django REST framework's authentication? I'd like to replace {'detail': 'Authentication credentials were not provided.'} and {'detail': 'Invalid username/password.'} etc. with custom responses
can my frontend React app establish a websocket connection to my backend django server?
if so, how would I open the websocket client and what library would I use in React?
pls ping on answer
I just need the libraries and their source / docs
django channels
modify the middleware
What would be a simple solution to do so? Without modifying stuff in the original files obviously
Django or Flask? Which one should I use?
Not sure... (without modifying the original file). Maybe you can find the middleware class, make a new middleware which inherits from it, and find a way to modify the response message. Then apply that custom middleware instead of the one provided by DRF.
Django if you want quick development due to its battery-included nature. Flask if you want more freedom to develop exactly to your own specs.
Sounds like a plan, I'll try, thanks
Hey guys! I want to make a scrollbar which when scrolled scrolls more than what the normal one allows with a bit of momentum
Any help is appreciated
@fossil pond https://github.com/nathco/jQuery.scrollSpeed
Probably helps
Hi, I am using Python flask
I need help
How can I handle file upload?
Like
I have input type file
How can I handle that?
How do I get jQuery.scrollSpeed.js into my html for this to work?
Hi, I'm trying to deploy my socket.io server on Heroku but it's throwing this error on heroku when ever my client tries to connect:
2021-09-05T17:40:11.114390+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/socket.io/?transport=polling&EIO=4&t=1630863609.333491" host=MY_HOST request_id=MY_REQ_ID fwd="MY_PUB_IP" dyno= connect= service= status=503 bytes= protocol=https
This is my Procfile:
worker: uvicorn server:app
Thanks!
Add --port $PORT
2021-09-05T18:09:02.227365+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/socket.io/?transport=polling&EIO=4&t=1630865341.2534761" host=HOST request_id=3RID fwd="PIP" dyno= connect= service= status=503 bytes= protocol=https```
worker: uvicorn server:app --host 0.0.0.0 --port $PORT
Ah, you need a web: ... line
ic let me try that one real quick
okay so it did connected but it instantly throw this:
2021-09-05T18:17:30.317827+00:00 heroku[router]: at=info method=POST path="/socket.io/?transport=polling&EIO=4&sid=P3767GBFupznddJ4AAAA" host=HOST request_id=RID fwd="PUBIP" dyno=web.1 connect=0ms service=13ms status=200 bytes=198 protocol=https```
and ofcouse my client raised an error too once this was raised in server
Traceback (most recent call last):
File "c:\users\maila\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner
self.run()
File "D:\Coding Stuff\UpWorkStuff\LinkedInDelivery\li_worker\src\helpers\sio_client.py", line 16, in run
self.sio_client.connect(server_url)
File "C:\Users\maila\.virtualenvs\li_worker-JBpAobyS\lib\site-packages\socketio\client.py", line 338, in connect
raise exceptions.ConnectionError(```
but the client connected then disconnected instantly
Are you using websocket?
๐คท
It's funny how that works. I found out the hard way the difference between a browser reset and a hard-reset. And even then, incognito can sometimes be the only way to get through it. Port numbers for Flask dev was my nemesis when I was coding Flask. If you ran multiple projects and wanted different ports...watch out!
I highly recommend two-scoops. I'm still working my way through it. But as my Django experience grows, my ability to make use of that wonderful book grows also.
haha glad we have someone who read/is reading it : )
shoutout to the writers, they did amazing job on it
pure experience and knowledge
read only that book you'll have django in palm ๐
what do we think about the look of this?
thinking to add more contrast.
and change the logo location to the center here.
just spent ages animating it all and adding drag n' drop items. Loving how it's so reactive.
It looks pretty nice,
can I clear my django-q queue from the command line? I haven't been able to clear it from the admin interface, because my browser crashes when django-q is running ๐ค
I'm using django ORM as a message broker
hello
i get this error while just setting up django from docs after adding the the methode
class game_selection(models.Model):
game_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.game_text
def was_published_recently(self):
return self.pub_date = timezone.now() - datetime.timedelta(days=1)
File "/home/noah/Bureau/Django/steamseller/library/models.py", line 12
def was_published_recently(self):
TabError: inconsistent use of tabs and spaces in indentation
Hey guys,
I've always tried to learn flask and all, I did some goofy things here and there but never got to deploy them.
What's the best way to deploy a flask app ? I always encounter these examples WSGI, but I feel like I don't understand anything and that I have to do more reading about networking and whatnot.
Sometimes I even feel somewhat "scared" and hesitate to read about it.
Does anyone have a good place to start ?
@fickle basin I think you should check that you are using 4 spaces for each indent
it is 4 spaces
it's working after copy/past ?? thats wierd
sublimetext is set on Tab Size : 4
that weird
maybe it's the 8 spaces on the line before?
@native tide I found this page helpful in identifying some of the security issues, if that's what you're worried about: https://flask.palletsprojects.com/en/2.0.x/security/
I asked around for good books on Django before I started my first Django web app (with an idea I'm excited by). I used it to brush up on some best practices and get pointers. I expect to dip back into it over the years to come. LanesFlow is now some 28,095 total lines of code, with over 10 applications. You could say that Two Scoops has been instrumental in this newbie's journey in Django (didn't know Python Apr 15, 2021, or Django Jul 8, 2021).
And yes, amazing job by the writers...
Corey Schafer has some good tutorials. I did go through his Django deployment video. Maybe he has a Flask deployment video too.
hey all, are there any alternatives to Google Analytics for Flask out there? I'm looking to use a self-hosted alternative, or maybe even considering my own data capture+analytics system storing info from each request from scratch. but that seems a bit too much. I'd much rather leverage an open source solution if there is any
@stone flax I've been eyeing https://plausible.io, but haven't tried it yet
thanks! I'll check it out
I'm trying to deploy a flask_socket io server with mod_wsgi+apache2, however, it doesnt seem to work, anybody knows how to run flask_socketio server with mod_wsgi+apache2 on vps?
dont use apache unless its mandatory. nginx
oh ok
problem is i already deploy the old flask app with apache2
well i mean, i can switch to nginx
yeah do it, you wont find good tuts for apache
I want to hand over the parameters to Django's redirect. What should i do?
flask code:
return redirect(url_for("views.act_date", user=params))
hmm
ok thx and sorry for the really slow response lol
return redirect('views:act_date', args=params)
Can someone help me understand how requests are handled in an ASGI server? What async really does in situations when say 100 people are requesting the server? Does it resolve request one my one? if so then what's the use of it being async? If not how does it serves these requests?
guys can someone help me my issue at #help-pineapple
lets imagine you have on async worker
first user requests the server, and got stuck in a long await operation
during this time I think in theory server supposed to be able to process another user ๐ค
I could be wrong though
anyway, multi worker async server exist anyway
so threading can be applied too
to process users in multiple manner
better ask expert in #async-and-concurrency channel
Doesn't WSGI Django use Asyncio to process requests asynchronously though?
yes that's my main confusion, I don't understand the difference between async request and spinning threads. I made a server that runs OCR on image with an ASYNC server and while it was processing image it didn't accept new connect so I had to implement it so that it receives a request and puts it onto a thread. So I don't understand what ASYNC is suppose to do when it's clearly not working?
i know for sure only that
ASGI server is needed in order to work with django channels/web sockets to make real time chat
hmm, I shold take this to #async-and-concurrency . Thanks @inland oak ๐
those async features confuse me greatly too ๐
I hope there is some good book about them
I hope so too, it's simple to understand when I implement it from scratch for test but when it comes to working with frameworks like Socket.io that has an ASGI Server. Man I feel completely lost
@lime mist From my knowledge, WSGI applications are functions which take in a request and return a response. So in theory requests are handles synchronously.
The difference with ASGI applications is that it's a callable which is async, and it awaits the response. So the server can handle other requests while the response is being awaited.
My confusion is that django uses asyncio already to handle requests, maybe I need to read about that more.
it could be using asyncio in order to have a queue of the sync requests too perhaps ๐ค
in order to not reject them when server is already busy, and process them in the order they are coming
As I shared my experience with a project, I was using an ASGI server and still it didn't accept any connection while it was doing OCR on an Await for a request before
I saw a mention of asyncio being used as job queue at least
could be but in my experience it rejected the connection after 10 or so seconds because it was still processing 1st req
library should be async friendly
Asyncio is probably used for async views. But if you use async views in a WSGI server do you even get any benefit? I don't think so, since it's still 1 request at a time.
it the library is not async friendly, it will not help that it is awaited, because it will still block the thraed
for example, it will not matter if I put Selenium library into async
or if I will use requests library with async
it is not async friendly
I need aiohttp for that
@lime mist what asgi server were you using? Also what's OCR?
computer vision library
recognizing stuff in images, characters I think
A minute, let me share my source
Ah okay
yeah grab test from image, school project ๐
btw!
starting from python 3.9
you could launch async not friendly processes
in a second thread!
It would be cool connecting a computer vision lib to a CNN to detect images in real time
import socketio
import json
from helpers import processTextifyRequest
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
app = socketio.ASGIApp(sio)
online = 0
like = 0
@sio.event
async def connect(sid, environ):
print(f"[CONNECTED] {sid}")
global online
online += 1
await sio.emit("serverStats", json.dumps({"online": online, "like": like}), to=sid)
await sio.emit("updateOnline", online)
@sio.event
async def getText(sid, data):
await processTextifyRequest(sio=sio, sid=sid, data=data)
@sio.event
async def doLike(sid):
global like
like += 1
await sio.emit("updateLike", like)
@sio.event
async def disconnect(sid):
print(f"[DISCONNECTED] {sid}")
global online
online -= 1
await sio.emit("updateOnline", online)
thus, making sure that environment remains async friendly
I'll have to learn more about these 
async def processTextifyRequest(sio, sid, data):
loop = asyncio.get_running_loop()
print(f"[REQUEST RECEIVED] {sid}")
with ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, getTextFromBase64, data)
print(f"[PROCESSED] {sid}")
await sio.emit("text", result, to=sid)
ngl I'm lost with this ๐ฅด seems like more async / asgi reading is needed
If I don't do this then the request is served one at a time ๐ฆ
What if you use asyncio.gather() somehow to concurrently run coroutines?
I can't really explain it well
But when I was working with async, just awaiting coroutines was just like sync code. I had to use asyncio.gather() etc
if you are free then maybe you wanna play around and make it work without threads?
https://github.com/git-avinash/textify-client
https://github.com/git-avinash/textify-server
me three
from youtube
from official docs
https://docs.djangoproject.com/en/3.2/
how to improve this? (forgot to tell its js)
if (item0Inner == p && item1Inner == p && item2Inner == p) return [true, p, item0.id, item1.id, item2.id];
if (item3Inner == p && item4Inner == p && item5Inner == p) return [true, p, item3.id, item4.id, item5.id];
if (item6Inner == p && item7Inner == p && item8Inner == p) return [true, p, item6.id, item7.id, item8.id];
if (item0Inner == p && item3Inner == p && item6Inner == p) return [true, p, item0.id, item3.id, item6.id];
if (item1Inner == p && item4Inner == p && item7Inner == p) return [true, p, item1.id, item4.id, item7.id];
if (item2Inner == p && item5Inner == p && item8Inner == p) return [true, p, item2.id, item5.id, item8.id];
if (item0Inner == p && item4Inner == p && item8Inner == p) return [true, p, item0.id, item4.id, item8.id];
if (item2Inner == p && item4Inner == p && item6Inner == p) return [true, p, item2.id, item4.id, item6.id];```
i dont even know what a tuple is (,:
so would be like:
if ((item0Inner, item1Inner, item2Inner) == p)```?
im trying to understand how it works
if ((item0Inner, item1Inner, item2Inner) == (p, p, p))```
ye that will work
it's just checking 1 object rather than 3 now.
so reduces the 'ands' and '==' you have to do
hmmm cuz this doesnt exist right?
if (item0Inner == item1Inner == item2Inner == p)
not in python the way you would think. also chaining them can causes issues depending on the type
cos of dunder methods
okay
what do you mean?
so there are python magic methods
no, I mean, why do you think a == b == c == d won't work?
that tell a type how to * or / or other stuff. depending on what they are next to. and wheter thats on the left or right
(in the general case, assuming __eq__ is sensibly defined)
what is the problem?
so one nice thing about Python is that you can combine comparison operators
e.g.
but looks shit too compared to comparing tuples IMO
!e
print(1 < 3 < 6)
print(1 < 7 < 6)
@vestal hound :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | False
whereas in most other languages you'd need to do something like (1 < 3) && (3 < 6)
oh
well, now i have it like this:
if ((item0Inner, item1Inner, item2Inner) == (p, p, p)) return [true, p, item0.id, item1.id, item2.id];
if ((item3Inner, item4Inner, item5Inner) == (p, p, p)) return [true, p, item3.id, item4.id, item5.id];
if ((item6Inner, item7Inner, item8Inner) == (p, p, p)) return [true, p, item6.id, item7.id, item8.id];
if ((item0Inner, item3Inner, item6Inner) == (p, p, p)) return [true, p, item0.id, item3.id, item6.id];
if ((item1Inner, item4Inner, item7Inner) == (p, p, p)) return [true, p, item1.id, item4.id, item7.id];
if ((item2Inner, item5Inner, item8Inner) == (p, p, p)) return [true, p, item2.id, item5.id, item8.id];
if ((item0Inner, item4Inner, item8Inner) == (p, p, p)) return [true, p, item0.id, item4.id, item8.id];
if ((item2Inner, item4Inner, item6Inner) == (p, p, p)) return [true, p, item2.id, item4.id, item6.id];
```something else i could do?
๐ฅด
okay back up a bit
xd
what are you trying to do?
tic tac toe ifs to check if game is done
ah.
in general
you can do like a == b == c == d
and it will work
however, overall
this looks like your data model
is probably not well thought through
its javascript?
ye
also i was thinking. nan == nan so sorry
it is?
oh then this won't work
===
3 equals in js
no colon after the if
if u wanna see my mess: https://github.com/ericmp33/tic-tac-toe
hold up then what are the parentheses supposed to do
haha im out. its .js ๐
wdym?
(item0Inner, item4Inner, item8Inner) == (p, p, p)
use a swtich
why do you have parentheses here
delete all that. it was python
JS doesn't have tuples
also, yes
in general
you should ask JS questions here only insofar as they are relevant to webdev in Python
oh true it doesnt work. just checked it :/
idk where to ask javascript help :/ so i ask here
I'd love to make a website like https://ygg.fun, I've got my own website running now. What's my next step to constructing it, learning HTML?
there is a js discord server or something?
it's off topic for this server
probably?
wdym u got ur own website running now?
okay, but dont u know some?
As in configured nginx and uWSGI, here it is: http://void.codes
oh okay
Just says Hello There! atm but nothing special at all
can you elaborate
you mean
so yeah if u dont know html nor css u should go and learn right now (: @native tide
like how to build a website (in the sense of the code itself, as opposed to deployment)?
np (; , ty anyways
In the sense of coding it - I've got no HTML/CSS/JS experience thus far, but I've got no idea where to even begin. I have no idea how to combine it all and make it work through Flask either.
well
you could also look into Django
why?
he should go for basic things
html + css !
no?
well, you need a backend to serve that
of course, Flask works too
but IMO Django is better because
first things first
it comes with all the parts
that you need for a basic website
-> less dependency management
shrugs there are many paths
this is just one
Say I create a HTML document to structure the main page of my website, how would I get Flask to display that HTML doc?
I don't know the exact mechanism in Flask, but ultimately each Flask route handler returns a response
so you need to get the HTML into that response
if you want to fill it with data dynamically
you'll need a template
otherwise, a static HTML will do just fine
Tried it, not working idk why
Even used https://idiotwu.github.io/smooth-scrollbar/ but nada
Customize scrollbar in modern browsers with smooth scrolling experience.
I learnt html how do i start learning webdev in python
i wanna be a backend one
help please
best way to maintain a server-state in a web server?
This system is made with Python Socket.io and is suppose to load-balance jobs across all available online workers
@sio.event
async def connect(sid, environ):
server_state.workers_online += 1
server_state.add_worker(sid)
await server_state.rebalance_workers(sio)
log(INFO, f"{sid} Connected!")
await sio.emit("sid", sid, to=sid)
@sio.event
async def disconnect(sid):
server_state.workers_online -= 1
server_state.remove_worker(sid)
await server_state.rebalance_workers(sio)
log(INFO, f"{sid} Disconnected!")
@sio.event
async def envoke_workers_rebalance(sid):
await server_state.rebalance_workers(sio)
The method to note here is server_state.rebalance_workers
and it updates this:
class ServerState:
def __init__(self) -> None:
self.workers_online: int = 0
self.worker_job_maps: list[Worker] = []
here is that method in action:
async def rebalance_workers(self, sio) -> None:
temp_worker_job_maps: list[Worker] = deepcopy(self.worker_job_maps)
for worker in temp_worker_job_maps:
worker.jobs = []
worker.proxy = None
proxies = Queue()
for x in get_proxies():
proxies.put(x)
for worker in temp_worker_job_maps:
if not proxies.empty():
worker.proxy = proxies.get()
else:
break
active_jobs = Queue()
for x in get_jobs():
speed = int(x[2])
if speed > self.workers_online:
speed = self.workers_online
for _ in range(speed):
active_jobs.put(x)
while not active_jobs.empty():
job = active_jobs.get()
temp_worker_job_maps.sort(key=load_balance)
for worker in temp_worker_job_maps:
if job not in worker.jobs and worker.proxy is not None and len(worker.jobs) < MAX_JOB_PER_WORKER:
worker.jobs.append(job)
break
self.worker_job_maps = temp_worker_job_maps
While testing I noticed a glitch in worker_job_maps list. I'm speculating it was because this is not the best way to update these variables as some other connect/disconnect/forced_rebalance can evoke this while it might still be getting processed.
What are your thoughts? Is this the right way? If no then how can I make this better?
Have you looked at Flask or Django yet?
Does someone know if it's possible to still use my domain name for mail purposes but make the domain not accessible by going to it with an internet browser?
Nooe
I started with Flask in June of this year. Even though I sensed my web project was complex enough, Flask gave me a start to grasp web development (backend, application, front end). After about a month I flipped to Django July 9, 2021. Just under 2 months later and I'm 28k lines of code in. ๐ The website I'm building can be found through my profile.
I've got a vague idea on that, mainly because I stumbled across it. You use DNS records. For the domain I'm working on I simply set up DNS to setup one server for mail and another for web. Are you familiar with DNS? If not, I suspect you'll need to brush up. I'm no pro, but I do have a domain and dedicated mail service set up for lanesflow.io
Ohh nic3
So you means I should start with flask?
For Flask, depending on how you learn:
- Books are deep, but slower
- Boot camps should give projects, but not as deep as books (udemy.com)
- As for tutorials, they're good so long as you continue to delve deeper. I recommend corey schafer on You Tube.
I thought I should delete the A and AAAA records?
Yes. Definitely start with Flask.
That first month was invaluable. And if your site isn't that complex, Flask can definitely be enough
Ohok
I'll start with it
There you go. That sounds right. But in truth, I'd still need to look the deets up for DNS
I LOVE web dev...Seriously. Tons of fun. You get to code in Python and can see the results instantly in the browser. Amazing experience
Ikr
I just built a billing/hour tracker for users in my web app...in less than 24 hours...
I started with tutorials. about 11 apps in the web application later, and I'm starting to get comfortable with Django
๐ This has two modes...prepaid pool or hourly billing. Determined by the user when they update their profile
So yeah...Flask and Django...amazing frameworks. Worth the perseverence.
But what amazes me most about Django...is the SPEED of my site. I can only assume that my choice to limit JS on the front end has paid off big time. Ping aside, the click to render speed is astonishing...even when working with DB calls for user data...and on this site, there are DB calls for every page...some of them significant queries.
any idea guys?
there is always a room for improvement ๐
with a bit of caching we could speed up things further ;b
Indeed. Always room for improvement. ๐
I suspect I'll miss the days when I could tinker with changes as the sole dev. Just rolled out a new app in lanesflow and have already refined on the image above.
up to hundreds of times ๐
Well, hundreds of times on a split second...diminishing returns. ๐
For the short-term I suspect I'm safe. The site is almost instantaneous right now
That said, when I get into react for the map app, that'll be a different game. I can see a JS front-end chogging up the render speed hard
React is popular, but I am hesitant a bit about it
I don't like that it mix JS and HTML together
I would prefer to try Angular perhaps
its structure looks quite prefessional
I know right...I need the diagramming though. I'd have to see if Angular has the diagramming libraries...
Agreed, that's why I personally love Svelte
It's pretty similar to Jinja2 and the Django template languages, in the sense that it doesn't add much new syntax, it's just a (very very) thin layer on top of regular HTML
Angular attracts me for looking quite similar to Django structure, battery included approach
and having typescript as mandatory from the start
That's encouraging.
My goal is to maintain the rest of the site as-is and ONLY have the JS framework serving up the one app. I've no need for a UI across the site. I just want the diagramming for the one app
From what I've heard, Angular is losing lots of popularity and satisfaction
really? too bad.
Does svelte have diagramming libraries available. I need to build something akin to https://draw.io
Yeah, take a look at this: https://2020.stateofjs.com/en-US/technologies/front-end-frameworks/. Angular is near the bottom
Great website
huh. interesting
Hmm, not that I know of.
That's the kicker...The only reason, for me, to go to a JS front-end is for one specific use case...to build a dedicated diagramming app that can interact with the data that the application layer can send to context in the template.
I'm ok with sacrificing speed for that app, but don't want it across the rest of the site
Ah yeah, if it's diagrams you need, Svelte probably isn't what you want.
It's rather new compared to the other more popular frameworks, but it is growing fast.
Yeah. I bet 1-2 years from now that'll change. ๐
So hard to guess with JS frameworks
I think that's the most rapid technology
dissapearing and appearing new ones quite quickly ๐
I know right. Still, I'm glad to have the luxury of user communities highlighting risks/benefits
well, since I dislike for some reason react
React is polling well on that website tho
I would choose between Vue and Svelte then
I personally hate it because of how messy it is, it's such a convoluted mix of JS and HTML
And state management can be hellish
Well, thanks for the insights chaps. Still got research to do. May have to explore a few of them. That website is very helpful tho
https://www.youtube.com/watch?v=cuHDQhDhvPE
Oh yeah, that's one video
I built a simple app with 10 different JavaScript frameworks... Learn the pros and cons of each JS framework before building your next app https://github.com/fireship-io/10-javascript-frameworks
#javascript #webdev #top10
๐ Resources
Full Courses https://fireship.io/courses/
Performance Benchmarks https://github.com/krausest/js-framework-benc...
seeing helloworld in all frameworks quickly)
Definitely worth a watch. Ty for sharing
yeah, that would make me afraid of it in advance
it does not sound like a way for a big clean project at all
agreed
actually it breaks one of clean code principles right from the start ๐
Robert Martin recommended to not mix different langs like that
liked the book. finally having an image where to go for cleaness
been getting this error for months =>
django.db.utils.IntegrityError: could not create unique index "Occupy_post_user_id_7dca33ac_uniq"
DETAIL: Key (user_id)=(1) is duplicated.
can someone help please thanks in advacne !
Seems like you are saving/posting data with an (id or whatever u required to make unique in the model) that exists already in the db.
I assume u are trying to create a user manually? So u got that error & it tells that the user id already exists
yh bro but im confused i have no id field ?
Django automatically creates an id
oh wow
I suggest to u something if ur input was correct, remigrate all models. That means u have to delete files(except init.py) in the migrations folder in every app and run migrations to start without existing users
Or just queryset to delete all users
Ive tried it couple times, but if ur project is sensitive then dont try it + if u want to try it and a bit afraid of errors just backup(do another copy of ur project)
But also try this before anything in console :
python manage.py shell
Import User
User.objects.all().delete()
Angular looks still quite in demand though
in terms of job positions
equal to React
while leaving vue far behind
Perhaps it not in satisfaction because of just higher learning curve
Any ideas?
Videos or just readable content?
Okay but i think i have to know how backend and web developpement work first
In jobs, yeah
But in terms of the actual framework, I've seen satisfaction decreasing
best way to maintain a server-state in a web server?
This system is made with Python Socket.io and is suppose to load-balance jobs across all available online workers
@sio.event
async def connect(sid, environ):
server_state.workers_online += 1
server_state.add_worker(sid)
await server_state.rebalance_workers(sio)
log(INFO, f"{sid} Connected!")
await sio.emit("sid", sid, to=sid)
@sio.event
async def disconnect(sid):
server_state.workers_online -= 1
server_state.remove_worker(sid)
await server_state.rebalance_workers(sio)
log(INFO, f"{sid} Disconnected!")
@sio.event
async def envoke_workers_rebalance(sid):
await server_state.rebalance_workers(sio)
The method to note here is server_state.rebalance_workers
and it updates this:
class ServerState:
def __init__(self) -> None:
self.workers_online: int = 0
self.worker_job_maps: list[Worker] = []
here is that method in action:
async def rebalance_workers(self, sio) -> None:
temp_worker_job_maps: list[Worker] = deepcopy(self.worker_job_maps)
for worker in temp_worker_job_maps:
worker.jobs = []
worker.proxy = None
proxies = Queue()
for x in get_proxies():
proxies.put(x)
for worker in temp_worker_job_maps:
if not proxies.empty():
worker.proxy = proxies.get()
else:
break
active_jobs = Queue()
for x in get_jobs():
speed = int(x[2])
if speed > self.workers_online:
speed = self.workers_online
for _ in range(speed):
active_jobs.put(x)
while not active_jobs.empty():
job = active_jobs.get()
temp_worker_job_maps.sort(key=load_balance)
for worker in temp_worker_job_maps:
if job not in worker.jobs and worker.proxy is not None and len(worker.jobs) < MAX_JOB_PER_WORKER:
worker.jobs.append(job)
break
self.worker_job_maps = temp_worker_job_maps
While testing I noticed a glitch in worker_job_maps list. I'm speculating it was because this is not the best way to update these variables as some other connect/disconnect/forced_rebalance can evoke this while it might still be getting processed.
What are your thoughts? Is this the right way? If no then how can I make this better?
Did anyone tried doing an API with django and showing response data with TEMPLATES at the same time. Ive tried that and I think its a good way if u dont want to use a frontend framework and want to implement an API. So does it include any later problems ive not notice? performance & speed? more querysets? less secure? etc..
NOTE: Doing this needs to have atleast 2 views, one for the API View, and the other is for the TEMPLATE View, same for URLs.
I'm creating a Django app which is basically a social media app. On the social media app you can upload images, how should I go about storing these images on the server? Should I just write the image to a file, should I encode it to b64 and put in in the database or something else?
if someone replies please @ me
Development or Production?
For production
Not yet, I'm still learning a lot of this
okay, so I think u will need to learn hosting files first and then get into showing images in ur django app
When I do that, how is the data stored? as a file for example image.jpg or is it stored in some other way
images are stored in the host cloud
np
@rotund perch I'm using queries in views.py with a Postgres DB in production. I've extended this to doing things like correcting user errors on input based on process requirements, updating templates dynamically, and presenting a rich data experience for the user.
The speed is astonishingly fast so far. But it is early days.
@wind dove I made the decision to stay away from uploaded media in production. Storing media on the app server loses statelessness of Django, and hinders load balancing potential. Storing to the DB presents security risks. I have opted to use external image hosting when needed down the line. For now, I upload images for articles (blog) as a static image behind the scenes and collectstatic inside the docker container.
@fossil loom I would expand on Darkwind's suggestion. Django documentation is excellent and I use it often for reference.
Have you started to look at a web dev framework, such as Flask or Django, yet?
so uve done it with 2 Views or an API View to TEMPLATE?
I code directly the queries into the view, typically using Class Based Views and logic within the form_valid function. I hope that answers your question. I'm only a couple of months into using Django
That seems intresting, how do users upload files into the container?
Okay TY!
They don't. I don't work with uploaded files for a number of reasons. I use forms to capture and control information input in a way I can completely control.
Uploading files in the field of process and business improvement is a misunderstood concept. It's based on the assumption that a file is the best way to capture data.
but what if u wanted to do an app that users can upload images on it, u'll need a host provider isnt?
In order to allow for load balancing later, or avoid security DB risks, I'd leverage a host with the resources and infrastructure to host the images and connect to them through URLs.
In other words, if a image hoster is trustworthy and has the resources to scale, why re-invent that wheel? Unless of course, you want to become an image hoster yourself
Yes Awesome ,Thanks.
Hey good people! I want to add a radio button to my Django form and I was thinking how do I introduce that variable to my model class?
Any help is appreciated
what happens after i delete ?
Can uvicorn serve 2 instances of a same web app to 2 connected clients?
I am using uvicorn to serve my socket.io server using heroku and there one of the things I'm maintain is an online users variable. I connected 2 clients which they did successful it still shows 1 as online users.
The code is perfect as if works fine when I test it on localhost. So my speculation is that uvicorn is somehow serving 2 instances of my server.
Can this be true? If yes then how can I disable it?
hello guys. I am pretty new to this area and I have to make a site to my school project in such a small period of time. Well, I was trying to use materialize css to do a Tab feature and I managed to do this, but I don't know how to align the iframes the way I'd like to. I'll show a pic of how (at least close) it should be
sorry buddy but i don't know
@fossil pond I would use a CharField with choices=CONSTANT in the model, the radio button input type on the template (https://www.w3schools.com/tags/att_input_type_radio.asp) and use css to style.
Or at least, I'd start that way ๐ I've not done radio buttons. But I do choice inputs all the time.
@fossil pond I've made use of the select input to great effect on a filter for lists on my Django site...
All data on the data base table will be deleted
Anyway for counting requests or responses or queries per action in django?
can you filter with model method with django_filter library?
or do i need to write my own logic in a function?
I wouldn't be surprised to see a library or function for this. But for purely solving this with just queries:
Setup an integer field in a table, every time a view is run query for the counter, add 1, save back to the table.
https://sailsjs.com/documentation/reference/web-sockets/socket-client/io-socket-on
I am emitting a list of strings from the server-side, is there a way to convert the msg to a list of strings at the client-side?
So, I can use Object.values(msg.var_name)
Can you please show me how to do it in the view?
i have a order model when someone order on cod but the address is wrong (we can't validate if its wrong) what flag to set on the order?
any recommendation. its a personal project
Ooh thanks I'll try it out!
Please tell me how to refer to the specific index of the list in the template of django.
ex){{ user[location].name }}
how to use this in django?
I donโt actually think you can? why do you want to do that
can someone help me with requests in #help-cookie
I need to implement an dropdown with each option I want separate form.. For example i have 1 form which has dropdown type1 2 3 and I want for type 1 enabled separate form 1, for type2 dropdown option it enables form2 and so on dynamically...
Django...
found it with keyword "dependent" fields...
corey schafer
and this
minguel named guy
thanks
it says its not running on production?
can this be simplified further?
def clean(self):
if not self.placed:
if self.paid:
raise ValidationError(
"Order can't be paid if its not placed"
)
if self.dispatched:
raise ValidationError(
"Order can't be dispatched if its not placed"
)
if self.rejected:
raise ValidationError(
"Order can't be rejected if its not placed"
)
if not self.dispatched and self.delivered:
raise ValidationError(
"Order can't be delivered if its not dispatched"
)
if self.paid and self.rejected:
raise ValidationError(
"Order can't be rejected if its paid"
)
if not self.rejected and self.reject_reason:
raise ValidationError(
"Order can't have reject reason if its not rejected"
)```
the environment is on production
(context django) if i have textfield with blank=True do i need to provide default?
or does it have empty string if no value is provided?
blank is if the value can be empty in Forms
you will have to supply a value for it if the field is not nullable
got a quick question
@ me if anybody can help or give some advice
basically
im working on a game rn
a text based RPG
that's just text only
and i wanna put this on a website
as opposed to like a downloadable exe that runs in the terminal (the way i currently have it)
and what's the easiest way to go about this
im a total beginner with python webdev
actually nevermind
ignore that
Hi, please take a look at this stackoverflow question: https://stackoverflow.com/questions/69064671/django-celery-database-update
Anyone know where to find beginner friendly tutorial for Django?
Hi, im trying to make a simple endpoint @upbeat sigil_view(['GET']) that returns a string, does this look correct?
def simpleEndpoint(request):
return Response("Hello world")```
or should i just return "Hello world"?
so just removing Response
And how can I test if this works?
Its correct, if u want to test it u can either use postman or a browser
Just do a url that points to that function to call it, and write the url in the browser
Np
Hey guys! For my Django routing it goes to R:\Projects\Websites\project\main\static\images\ when it should not go to static idk why that's happening. Has anyone faced this issue?
hey guys ! i have a question. now when developing apps with kivy, or desktop apps with tkinter (or something else), orr even websites with django+flask. am i able to design first in figma or adobexd and then convert those files to the code ? or how does it work ? because for example .. most of kivy apps look ugly, soo designing them with figma in my opinion is better and then transferring them to the code. is that possible ?
what is the problem the static doesn't work ?
Static works. When I redirect to the webpaage it is going to static instead of templates.
I fixed it by changing the redirect link from href ="/contact" to href="{% url 'contact' %}"
But strange because for my other pages href ="/resource_name" is working fine
Would love to know why it happened
/resource_name i am actually doesn't now what this do but in django when you want to redirect to any given page you should use this {%url %} i think this called jinja or something like that
Yep thanks! I'm still wondering why is it working for my other files
@fossil pond
can you plz show me your urls file
someone know why the fontawesome stuff is only working once?
i used the links on differtent html file but it only works on one
you may just forget to add another backslash / like this href ="/contact/"
ah i forgot to do this on every site:
<script src="h ttps://ki t.fontawesome .com/5136008 754.js" crossorigin="anonymous"></script>
Ah no that's not the case
how can i change the size of a container with flexbox?
No issue with that either
path("", views.home, name="home"),
path("projects/", views.projects, name="projects"),
path("project/<str:pk>/", views.project, name="project"),
path("portfolio/", views.portfolio, name="portfolio"),
path("inbox/", views.inbox, name="inbox"),
path("contact/", views.contact, name="contact"),
path("message/<str:pk>/", views.message, name="message"),
]```
Did you try adding a backslash like I told you?
dude can you show me what the error when you want to redirect
is it page not found ?
What is the line of <script> you're using to reference Font Awesome in <header>?
Including static at the template start combined with {% static url 'url-name-here' %} is the guaranteed way for it working. If not calling static worked for another page , I'd be curious to see url.py for the app, along with the template html. However, understanding why it worked using the incorrect approach is probably not as helpful as understanding the correct way to call on urls within Django. I hope that makes sense. ๐
its fixed i missed the import link on my other html files
Good to read ๐
When I add the extra backslash it redirects it twice. I get a portfolio/portfolio call
Corey Schafer, YouTube. I started with him July 9. 28k lines of code later and the result is in my profile. Great tutorials
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("projects/", views.projects, name="projects"),
path("project/str:pk/", views.project, name="project"),
path("portfolio/", views.portfolio, name="portfolio"),
path("inbox/", views.inbox, name="inbox"),
path("contact/", views.contact, name="contact"),
path("message/str:pk/", views.message, name="message"),
]
and for the template even if it is blank I get the same output so I doubt it is relevant. But thank you, I shall use the correct way. A few bad tutorials can really ruin a lot of hours!
Not being familiar with figma I can't say anything in that regard. However, as someone who started learning Django recently, I'd suggest that developing code within the Django application layer (views.py for the app) or Flask is something that is best from within Django. There are a number of reasons for this, but explaining them if you don't know Flask or Django could quickly get confusing.
The idea of trying to port Python into a Django app doesn't strike me as an intuitive approach. Django/Flask is a framework that offers a way of building a web application with a spectrum of potential. But then, the use case of what your code is trying to accomplish would have a bearing on this. Most Django python code I've worked with is mostly about CRUD with the DB, and building the interface with the front-end (the browser). What I like about web applications is that once I'm clear on html/css (and even JS if I feel I need more dynamic behaviour) I've got the question of UI addressed.
Yes...a bad tutorial can be BRUTAL. I feel your pain. That said, it is good to be on the other side. Ultimately, once you get including static, along with how the urls.py files work for each app, you'll find it all making more sense. I'm currently working on an web app that has 11 applications and likely more than 200 urls. Naming those urls intelligently so that it's super clear what you're working with gets more important as the web app scales. Also, using an IDE that will auto-populate can be a time saver like you wouldn't believe.
Are you using template inheritance?
not yet, im working my way up to django currently by learing css, squlite and js haha
When I use template inheritance, I'll throw such script lines into the header for base.html. That way, the script is always there and updated in one place.
still a long way
but do you know how i can reduce the size of a container with flexbox?
id like to shrink down the site a bit
i think its currently scaling with the desktop resolution size so no size limit
I have been using bootstrap, which comes with flex embedded. I typically manage flexbox by setting up as follows
<div class="row">
<div class="col-2">
<h5>Customer</h5>
</div>
<div class="col-2">
<h5>Type</h5>
</div>
<div class="col-2">
<h5>Scope</h5>
</div>
<div class="col-4">
<h5>Need</h5>
</div>
<div class="col-2">
<h5>Rank</h5>
</div>
</div>```
What the above shows is a row with 5 columns. Each row can be divided into 12 columns. I happen to have cols with 2-2-2-4-2 (which totals adds to 12).
Now, if image size is an issue, you might look at capping the width of the image by setting a width with css for the image and applying that class.
In turn, in subsequent rows I start again, and can declare a col structure that is the same or different. It feels intuitive now that I've been using it for a couple of months, and comes down to thinking...each row can have upto 12 columns....
i fear that when i switch to bootstrap one day that my whole grid system is doomed xD
that's a fair assumption. I'm not pitching Bootstrap or Tailwinds. However, what they did give me was an effortless and intuitive entry point to flexbox. It's astonishingly simple to manage flex with a css framework.
On the inverse, one day I should try flex with vanilla css ๐
๐
but then, I didn't start coding with Python to become a css master ๐
I needed enough css to get a UI that works for me and looks decent.
tkinter works also for UI but yea css is simple and has more fancy features ๐
but im still a beginner with html, css etc so bootstrap is kinda like a game mod, modding/adjusting the code/features itself?
Thankfully, I'm clear on becoming a web developer. So I'll never really need tkinter. It was good to learn from, but it looks old school.
Even with a framework I'm getting clearer on css. There is tons of potential with layout, and there is some css stuff out there that is mindblowing.
Bootstrap/Tailwind is an easy vector into styling. They're taken care of a lot of the things you're most likely to need. They're also proven and tested, so for the majority of UI demands they're a rapid way of getting a build. I wanted my web app project to expand in functionality and have a consistent UI. Bootstrap gave me a quick way to establish a UI I liked. And I still like 11 applications later in Django.
That said, there's also the JS Framework route...which takes UI and behaviour to whole other level.
All said and done, I'm happy with my start with Bootstrap. For the next project I'll try Tailwinds for the experience.
And then one day, when I've got the time I'll delve deeper into css. However, a css Framework introduces you without requiring you to understand it all.
so it makes things simpler compared to vanilla css?
Simpler. Hands down. There's a learning curve. However, there's also great documentation.
I started by querying how to "do something with bootstrap/tailwinds stack overflow" and someone had the answer already out there.
Bootstrap allowed me to move quickly into focusing on function, with the comfort that form/style is great. My css file is 650 lines, and it's been weeks since I touched it.
I hear great things about Tailwinds though. So either flavour comes well used and regarded
alright i will take a look into it but i really fear it just ruins my whole project xD
Has anyone here used crispy forms? I want to make a really cool looking contact form with it. It has bootstrap integration. Can you share some good resource if you have?
I'd caution changing from vanilla css at this point, unless you want to rebuild...
I use crispy ALL the time with Bootstrap. Amazing
Aah Iโm about to go to bed now. Iโll ask you my questions tomorrow.
Sorry xD
If you have any resources please share them now Iโll look at them when I wake up
Be happy to help. I'm around every day.
As for resources, I was introduced during a 100 day bootcamp on Python. It's actually quite simple. I can show you the key bits to do for your Django project. There is a pip install, settings.py to configure, and then the include for the template. Quite simple tho
How do you implement this in html?
list_var[index].option
What framework are you using? Flask, Django, other?
Use Django
So, you're using jinja2 for templating.
Are you using class based or functional view in views.py?
umm..I dont know..I used function.
OK. Sounds like functional views.
So, you need to build the context dictionary to pass over to the template.
How you populate that dictionary is going to depend on if you're working with a DB.
the context dictionary is going to look something like:py context = { 'year': get_current_year() }
Once the context dictionary is built, then you can call on that in the html template:
{{ year }}```
I received data from DB and handed over the list information to context. But I want to refer to a specific index value within html, but I can't.
If you pass over a list, then in the template you can use a for loop in the template: ```html
{% for element in list %}
Html
{{ element }}
{% endfor %}```
The for loop in jinja feels just like a for loop in python. This can extend to dictionaries as well.
Thank you. I got it.
Looping inside html allows you to amazing stuff. Good luck ๐
{% load index %} in jinja can be done too. You can import index into a template, and then use the {{ element|index:forloop.counter0 }} tag to manage multiple lists within a for loop.
If you use index though, you need to import a package for that.
There's one more question. If i receive the variable 'location' in the first for loop, how do i refer to the 'location' of the list?
ex)in Python
for location in var: list[location].option
'location' is list.
This where you can make use of the index...
If you know the index, then you can run an if statement inside the loop:
{% for element in list %}
{% if element == target_value %}
# do something
{% endif %}
{% endfor %}```
I think I got the hang of it. Thank you.
It's not hard. Everything you're looking to do is do-able ๐
Calling specific index values and conditionally acting on them requires a bit more thinking tho
One thing though...if you want to run on the counter you can get specific about using the forloop counter to match for the indexhtml {% elif failure_is_late|index:forloop.counter0 %}
Sorry to ping you. Just one more question about Svelte.
is it not having problems with State management?
Should be better in this regard Vue.js or Svelte can work with it finely too?
Svelte looked just so attractive to me, quite interesting to choose, but needing to know if there will be not problems with essential libraries
Or better to go safer vue.js
https://svelte.dev/tutorial/writable-stores
hmm, official svelte docs are broken for stores functionality
the buttons aren't working
I think vue.js would be safer for startup purposes
svelte looks like lightweight solution for pet projects at the moment
hmm, nice typescript is supported in svelte
https://svelte.dev/blog/svelte-and-typescript
Why not React? Nice and simple and it's the new craze.
because its mix of js/html/react abstractions look messy being all together ;b
check how Svelte looks clean
Hello
Looks cool. I'd probably learn Svelte over React but I'm way too far into it now and the job prospects are the best. Looks good tho.
Might not be as many community libraries to use though.
I wrote an article for real time chat. I used the header to pass the token for token authentication. Im working with a frontend developer now and i was told it's impossible to pass custom headers for wbsockets through js. I have to change the middle ware to make it take token through query parameters. Ive done that. But I'd like to know if there's a way to pass custom headers for ws requests
yeah, from job perspectives better probably to go for the second best option: Vue
for my pet projects, I would definitely go Svelte though
hey @ionic raft
(blog) C:\Users\Yong PC\Documents\try_django\blog\try_django>py -m pip install django
Requirement already satisfied: django in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (3.2.7)
Requirement already satisfied: asgiref<4,>=3.3.2 in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (from django) (3.4.1)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (from django) (0.4.1)
Requirement already satisfied: pytz in c:\users\yong pc\appdata\local\programs\python\python39\lib\site-packages (from django) (2021.1)
WARNING: You are using pip version 21.1.3; however, version 21.2.4 is available.
You should consider upgrading via the 'C:\Users\Yong PC\AppData\Local\Programs\Python\Python39\python.exe -m pip install --upgrade pip' command.
(blog) C:\Users\Yong PC\Documents\try_django\blog\try_django>django-admin
'django-admin' is not recognized as an internal or external command,
operable program or batch file.
``` why is django-admin not working?
what are you trying to do?
[auth]
changepassword
createsuperuser
[contenttypes]
remove_stale_contenttypes
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
[sessions]
clearsessions
[staticfiles]
collectstatic
findstatic
runserver
commands
python3 manage.py findstatic --version
I'm not sure about env but this is the way to work with a docker and a docker-container,
i don't believe there is any big difference in commands.
For me, state management with stores is working perfectly
Did you click "show me" at the bottom of the tutorial?
If you do that, then it should fix itself
ops. it is working now ๐
typescript is supported by svelte too
what else to wish?
I'll take svelte for myself ;b
@inland oak pretty sure TS is supported by all the major frameworks.
svelte is young one
it started to support TS only in 2020 year
well, svelte appeared only in 2019 year
https://2020.stateofjs.com/en-US/technologies/front-end-frameworks/
youngliness is not a problem for a huge interest to it though
Svelte is very nic3
love from first without even trying it ;b
The lack of a virtual dom runtime also makes it probably the go to if you want browser support
Its the only frameworm I've used that supports my ipad with safari that hasnt bren updated in 6 years
I've been making https://dev.lnx.rs with it
Previous mostly worked with vue or react
what would you choose between them?
if you would be limited only to them
Svelte 100%
except svelte? ๐
After working with it for a while its definitely my favourite framework
After that probably vue
Generally i prefer the template layout svelte and vue
thanks. interesting.
a bit curious how would some dev compare his experience with angular too
eh, if only I had a bit more time to learn frontend ๐ค it would be nice to play with svelte
but I am bit too busy learning devops stuff
window.redraw = function( _id, endpoint ){
$.get( endpoint, function( data ) {
$( "#"+_id ).html( $(data).html() );
});
}
a method that just redraws returned html to the dom is also cool.
and just use python
wow wont that be bad
idk whats going on isn't this how u start a virtualenv
i guess this is more of a python prob cuz im working on flask and i had this project on windows now since i shifted to linux idk howo to do so
should i still go to #editors-ides
Well it's definitely not a web dev problem
Does anyone know how I can split files and make them use the same imports without writing it on top of each file separately?
Basically I want to do all my imports once (like general imports) for a bunch of files to avoid redundancy of the code.
if its sensitive data of course its bad, but in ur case u will need to delete all users from the users table so u can recreate new users.
or do this
this is for web dev try in #python-discussion
ok great thanks
np
you can import everything into one file and call that file in your main ... but I think it's stupid because you complicate your code
That's not what I want.
I have multiple Flask Resources and I don't want in each resource:
from flask_restful import Resource
```If that makes any sense.
I get it now
I don't think that's possible
Me neither after thinking about it for longer
I am getting this error
Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class AccountAdmin.
here is my admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import *
from .forms import RegistrationForm
class AccountAdmin(UserAdmin):
add_form = RegistrationForm
list_display = ('email', 'first_name', 'date_joined', 'last_login', 'is_active')
search_fields = ('email',)
readonly_fields = ('id','date_joined', 'last_login')
ordering = ('email',)
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(User, AccountAdmin)
admin.site.register(Category)
admin.site.register(Product)
anyone please help
On linux, you start a virtualenv with
source <virtualenv-folder>/bin/activate
So I want to have 2 webservers running on the same machine. If I purchase an additional IP for that machine, then simply set the host to the desired IP for that server, would that be all I need to do, or would more configuration be required?
Please ping me when responding
you could make it work without purachasing additional ips
with a bit of nginx rules you could setup...
if requests start with /somepath, then they go to first web server
I am running Apache on this server btw
if with / path, then to second server
Am I able to do it by subdomain?
well yeah, it could be used too
But!
better just deploying to two servers ;b
what do you deploy?
Right now I have 3 servers for 3 different webapps, but I figure if I can just stop purchasing more servers that would be good. I am going to add a webserver to a Discord bot in the same application, aiohttp
how to test Django signal 'user_logged_in'?
Hi guys! I'm having a problem with a multiple type checkbox that I've implemented using crispy forms on Django. I get an error saying that they are not the right fields when a user chooses them.
project_type = models.CharField(max_length=20, null=True, choices=TYPE) : models.py
project_type = forms.ChoiceField(choices=TYPE, widget=forms.CheckboxSelectMultiple) : forms.py
What mistake did I make?
TYPE = [ ('mobile', 'Mobile'), ('desktop', 'Desktop'), ('web', 'Web'), ('other', 'other'), ]
It appears in the UI but when someone chooses 1 or more values , a JS prompt is received saying that the fields aren't right
@inland oak Do you think I ought to just get another server, or should I be fine just setting it up via apache configs?
depends on what you are deploying
describe a bit
I'm implementing the user login activity
so when the user logs in It fires a signal which creates an entry in a table
but while testing the login with the client it also fires the signal and the signal is expecting a request
Need help in this guys
I have a Discord bot, and I want to set up a subdomain for it, so that it has its own small website. I am deploying the Discord bot and webserver in the same application.
better to have two different servers ;b
you could be forced to have one server though
depending on how you will choose exporting data
bot could be having some backend tied to it anyway
but web server could be on a separate server anyway
Im running the bot and aiohttp server in the same application, so I wont really need to export data
Ill look into getting another server, thanks for the advice
I will probably just do development on my main server on a port for now
guys i need a html help
i am deploying a ml model
but when i hit predict the textbox values are resetting
when i tried to fix that result is not coming
i tried onsubmit = "return false"
<div class="login" onsubmit="return false">
<center><h1>Surge Price Prediction</h1></center>
<center>
<!-- Main Input For Receiving Query to our ML -->
<form class="form" id="Formid" action="{{ url_for('predict')}}"method="post" >
<label for="Type_of_cab">Type_of_cab:</label><br>
<select name="Type_of_cab" id="Type_of_cab"></br>
<option value=" "> </option>
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
<option value="4">E</option>
</select><br>
<br>
<label for="Gender">Gender:</label><br>
<select name="Gender" id="Type_of_cab"></br>
<option value=" "> </option>
<option value="1">Male</option>
<option value="0">Female</option>
</select><br>
<br>
<br>
<label>Confidence_Life_Style_Index</label><br>
<select name="Confidence_Life_Style_Index" id="Confidence_Life_Style_Index"></br>
<option value=" "> </option>
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
</select><br>
<br>
<button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
<br>
</form>
</div>
Hey is it good practice to format all my data using serializers in django?
"REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client."
what's unrendered content means here?
is this the place to talk about low level web stuff?
like im talking tcp packet level
u hv made this using
tkinter
@native tide
ooh nicely built
ty lol
it was my first ever tkinter projects
and my last
i dont use tkinter any more
it isnt too good tho
meanwhile im stuck with this
what gui toolkit are you using now?
i cant anchor the entry widget
so it comes like this
center of fram
e
i dont use one, im remaking that tkiner project but on a website so i can have animations and more features
which?
oh i dont know that yet
stuck on vsc
y?
ok
any idea how this can be done
pad, fill, expand?
pad is spacing between other widgets, edge of window, etc
padding
instantiate the widget before the return button
i hv done that
the label and entry widget are a single func instantiated before the return button
show full code on hastebin
nvm i shall ask tmrw
and let's move to #user-interfaces
oh ok
heyo... hopefully quick question... i have two database columns, one that lists a member of a server and another that lists roles associated with that member on that server... when trying to "display" those roles, i run into a (very long executing) template display challenge. i think it may be a custom filter thing but i'm not opposed to rearranging data also... any thoughts on how to simplify this?
{% for role in roles %}
{% if role.memberServerID.id == member.id %}
{{ role.roleID.name }},
{% endif %}
{% endfor %}```
Does raw query and ORM have the same model?
u mean course at udemy?
how can I speed up a flask view that is making a call to an external API?
@app.route('/loading')
def loading():
assignments: dict[str] = dict()
global courses_list
if len(courses_list) == 0:
courses_list = get_courses(session)
for course in courses_list:
assignments[course.orgunit_id] = get_assignments(session, course.orgunit_id)
return render_template("courses.html", courses=courses_list, assignments=assignments)
im assuming the best solution is implementing a docker container that uses celery and redis
but idk where to start with that, never used either
How do I go about setting up a quick email server? Not looking to do anything fancy, just send an email
Please @ me when responding
@topaz finch https://mailtrap.io/blog/flask-email-sending/
dunno if this helps at all
from flask import Flask
from flask_mail import Mail
app = Flask(app_name)
app.config['MAIL_SERVER']='smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = '97e041d5e367c7'
app.config['MAIL_PASSWORD'] = 'cfaf5b99f8bafb'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail = Mail(app)
@app.route("/")
def index():
msg = Message('Hello from the other side!', sender = 'peter@mailtrap.io', recipients = ['paul@mailtrap.io'])
msg.body = "Hey Paul, sending you this email from my Flask app, lmk if it works"
mail.send(msg)
return "Message sent!"
if __name__ == '__main__':
app.run(debug = True)
Im currently using SendGrid, but 100 free emails a day is about to be too few. Am I able to retain my domain as the domain for the email?
@topaz finch is it a domain you bought? like your own .com/whatever top-level domain?
Yes
namecheap ftw
@topaz finch you should be able to move your MX/SPF records to whatever email provider you choose then
Most dont seem to have good enough free plans, and I am not looking at paying more than a few bucks. Thats why I am trying to figure out how to set this up with my own VPS servers
@topaz finch there is a lot to consider with hosting your own email. standing it up, securing it from attacks, privacy/data retention. not to dissuade you, but I would vet pricing from other providers before taking it on yourself.
Fair enough, any suggestions as to who? I mean, I would be fine with sendgrid if they didnt go from free to $15
while I hate to pitch Amazon, they'll give you 62k emails per month under their free tier for SES
@topaz finch mailgun has a flexible, "pay-as-you-go" offering
Awesome, I will check both out. Thanks so much @frosty cedar
@topaz finch you're welcome!
In Django+React (with jwt tokens), I found a weird effect that when I login through my site (react), it gives me a JWT token as expected but also creates a session cookie. When I go to log out through the client and then log back in as another user, it logs me back in as the same user as before.
I get the feeling that the session is what's still active and being authenticated but I'm not quite sure what part of the auth process the hiccup is in. Anyone seen this before?
What would be the best direct route to building a drag and drop front end UI?
Django, flask? Frameworks?
Yes, I took Dr Angela's 100 day Python boot camp. Excellent experience.
django newbie here. i have a question:
Django uses an Object-Relational-Mapper (ORM) to map model definitions in the Django code to the data structure used by the underlying database.
``` what does "map model definitions" mean ?
Hello?
Hi Im trying to create virtual env using pipenv install django and i get this error please help ValueError: Unable to find resource t64.exe in package distlib
I dont know I am new to web development I think might help you https://www.geeksforgeeks.org/selenium-python-tutorial/
@tawny pollen To be able to interact with a database, you have to do so with SQL. The django ORM maps your pythonic code into SQL. e.g. writing a model then migrating will create a table in the database.
@runic lodge Django/ Flask acting as APIs. More importantly is the frontend framework. I've had simple drag and drops with React. It gets pretty complex. Look at react-beautiful-dnd.
do u know flask?
can u help me in
don't advertise your help channel.
ok
It means:
you are writing python code with classes.
Instead of writing sql
Interesting so dev programming pipeline is python > flask(api)/Django > React(or VUE) for front end ?
How does the api for flask work?
I know python would be for backend, breaking down code, running algos etc. and whatnot but what about that mid level stuff
API mods:
flask: https://flask-restful.readthedocs.io/en/latest/
django: https://www.django-rest-framework.org/
@runic lodge wouldn't call it a pipeline. But yes.
Svelte can work for frontend too
Hello, Whats the Diff Between JWT & Knox Auth In Django. Also, Which is Better for Security Purposes
any web ideas
Authentication with face detection
Help django class based view
template:
<form action="{% url 'search' name=contact_list.first %}" method="GET">
{% csrf_token %}
<input type="search",name="search", placeholder="Search contact", aria-label="Search">
<button type="submit", class="btn btn-success">Search</button>
</form>
view
class SearchContact(ListView):
model = AdressEntery
template_name = "main/search.html"
context_object_name = "src"
def get_queryset(self, *args, **kwargs):
queryset = super(SearchContact, self).get_queryset()
search = self.request.GET.get('search')
queryset.filter(name__startwith=self.kwargs['name']) #it should be here queryset.filter(name__startwith=search)
return queryset
the problem is that my self.request.GET.get ('search') returns None
I've got an api/views.py that goes like this:
from functions import connect_mongodb
mongo_client, db = connect_mongodb()
And a functions.py like this:
def connect_mongodb():
mongo_client = pymongo.MongoClient(f"mongodb+srv://{MONGODB_PATH}")
db = mongo_client["django"]
if DEBUG:
print(f"Connected to MongoDB ({__name__})")
return mongo_client, db
When api/views.py starts it prints Connected to MongoDB (functions) since connect_mongodb() is imported from functions.py. How can I change it so it prints Connected to MongoDB (api.views) like if I were to print __name__ in api/views.py (that returns api.views) but still keep the function imported?