#web-development
2 messages Β· Page 190 of 1
at this point I honestly don't know anymore lol
if I mess with the STATIC_URL i get all sorts of exceptions thrown at me that its conflicting with MEDIA_URL
@cerulean badge you can have one "table" in your redis db for your queues, and another one for your data.
I just changed the STATIC_URL = '/absolute/path/to/the/files/' and the get request seems to queering the right directory, but I'm still returned a 404...
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
desc=request.POST.get('desc')
file=request.FILES['file']
thumbnail=request.POST.get('thumbnail')
author=request.user
if ValidationError:
messages.error(request,'CAN ONLY UPLOAD PDF FILES')
return render(request,'index/notes_upload.html')
entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
entry.save()
messages.success('Notes updated successfully!')
return HttpResponseRedirect('/')
return render(request,'index/notes_upload.html')``` i'm uploading .pdf files only then too it's flashing error and data isn't saving to db 'CAN ONLY UPLOAD PDF FILES'
I don't think if ValidationError is valid syntax. I've never tried to check if an exception was real, but it's probably returning True.
Use a try/except block for handling exceptions
well
I mean
it's probably the wrong directory, right
otherwise you'd get a hit
Hi, I'm a new python dev and the project I'm working on uses both uvicorn and starlette - is uvicorn the web server and then starlette is a framework on top of that? I'm from a .net background so I guess an analogy would be they have their web server called kestrel then MVC sits on top of that. Would that be similar?
yes
I have no idea what those .NET things are
but yes, Uvicorn is a server (following the ASGI spec) and Starlette is a web framework
Great thanks.
Hi, I'm trying to add 5 miuntes to the current time
Using this
datetime.timedelta(
seconds=300
) + datetime.datetime.now(timezone.get_current_timezone())
I get this as the error
unsupported operand type(s) for +: 'NoneType' and 'str'
I print them individually it isn't none.
then you're changing something
show the surrounding code
So my next problem is getting the logging to work, when I start my server I can see log entries like this:
INFO: Uvicorn running on http://127.0.0.1:8082 (Press CTRL+C to quit)
But if I put in my own logging code in the application I never see the log output e.g.
log.info('test')
Never comes onto my terminal. I'm using Ubuntu.
try:
user = User.objects.get(email=request.data.get("email"))
activation = Activation.objects.get(user=user)
activation.expiry = datetime.timedelta(
seconds=300
) + datetime.datetime.now(timezone.get_current_timezone())
activation.save()
That's it
Quit the server with CTRL-BREAK.
unsupported operand type(s) for +: 'NoneType' and 'str'
Internal Server Error: /register
huh
where's the rest
this is
Flask?
you mean a website?
Django
then where's the full traceback
Yeah
yes
Yep
well
That's why my name is like a tag
Whattttt
but you use a web framework to serve pages
for example
let's take Instagram
the webpage is in HTML and CSS (and JS)
but somewhere on Facebook's servers, there is code that takes the URL you type in, does stuff, and returns that webpage
that code is Python
Ooo
Hi, the app. I am working on starts with uvicorn when testing locally, but in the production environment where it runs in a docker container it's started with gunicorn. Does anyone know why this difference exists? Thanks in advance.
gunicorn could launch uvicorns
check its parameters
thanks. looks like it runs and manages uvicorns
For some reason I just can't seem to get my log output appearing in the terminal window. I start uvicorn from the terminal, I can see my print statements but nothing from log.
put into docker file somewhere
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
not running in docker at present - shall i set in my terminal ?
Someone, please ππΌ
um, try to do that. the PYTHONUNBUFFERED variable fixes this issue when I launch gunicorn in docker at least
thanks,,, just found something else as well that might solve it
i wanted to get more n more deep into django and it's rest framework now
im learning alot in django as im doing freelancing
but idk how to apply web scraping with django
ai with django
- i wanted to get deep into it's rest framework no client asks for that so my that skilleset is being dead
@dusk portal Using Upwork?
nah not any dedicated account at any platform yet just got clients on discord servers
xD
yeah, what table does celery use by default?
how do you get clients from discord servers lol
@cerulean badge I believe it uses the "table" at index 0. You can store all of your data in another index, e.g. 1
You can go into your redis shell and see the data stored at each index. Your broker data should be stored at index 0.
ok thanks
@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
this is from django3 by example
https://paste.pythondiscord.com/ijugevoqul.py
my question is wouldn't it return wrong suggestion if 2 people are visting their cart at same time and one have products with id 1, 2 and 3 while the other have product in cart with id 123?
i am talking about this line
flat_ids = ''.join([str(id) for id in product_ids])
tmp_key = f'tmp_{flat_ids}'
@cerulean badge you could store cart info on the clients idea in localstorage then make API calls for the products instead
the issue would still be the same, right?
if 2 users make the api call at same time ....
each user has their own session. i.e what they see is unique to them
sir, did you read the code? https://paste.pythondiscord.com/ijugevoqul.py
from your statement it seems like you're talking about two people visiting the same cart?
to suggest products it is using scores, for cart if there are multiple products it creates a tmp_key in redis with their ids, thats what i am talking about
i see
hey @thorn igloo
supp
Anyone dealt with the issue where you login to Django admin, therefore creating a session, and then when you try to login with a JWT of another user on the website (not admin panel), it logs in to the account associated with the session?
I'm experiencing an issue with djongo when used with Django REST framework where it initiates a new connection with my MongoDB at every request except for the very first one after starting the web server. That means the first request to my Django API is fast (~50 ms) but all the following requests are significantly slower (~600 ms) because they all initiate a new connection (it's much faster when I'm running the web server closer to the DB, but I'm running them far apart each other for debugging so it's easier to spot such issues).
When profiling the request I can see that pymongo\pool.py:1263(connect) is present in each request except for the first one, which I assume means the first request uses the pre-initiated DB connection, but all the others have to create a new connection, hence why it's so slow. I'm also seeing huge spikes of connections in my MongoDB dashboard, there should be only 1 connection, but when I'm testing this it gets up to 50-80 connections, and even when I shut down the web server, the connections only drop by one and plenty of zombie connections remain that only die after some timeout.
For the installation and configuration I've followed their GitHub instructions (https://github.com/nesdis/djongo/) so it goes like:
DATABASES = {
"default": {
"ENGINE": "djongo",
"NAME": "django",
"CLIENT": {
"host": f"mongodb+srv://{MONGODB_PATH}",
}
}
}
(MONGODB_PATH = f"{MONGODB_DJANGO_USER}:{MONGODB_DJANGO_PASS}@{MONGODB_CLUSTER}" from environment variables)
Anyone else encountered the same or similar issue? I can send a link to the endpoint if someone would like to help with debugging
You might be better off on SO. I've seen you post this here a few times.
@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
will suggest_product_for raise error if called with empty products list?
https://paste.pythondiscord.com/ijugevoqul.py
@cerulean badge Why not call it with an empty list and see what happens?
i did and it doesn't raise an error but this issue says otherwise
https://github.com/PacktPublishing/Django-3-by-Example/issues/46
Chapter 9 throws an error if all the products from the cart are removed. The following should be added to recommender.py def suggest_products_for(self, products, max_results=6): product_ids = [p.id...
you activated virtual env? if you have a virtual env
Hm, I'm not familiar with redis. But the docs say that at least one member is required. https://redis.io/commands/ZREM
how to do it
if you have a virtual env i think you would have known how to activate it lol
ok thanks
dont write py and -m it's django-admin startproject xyz
xyz == project name
ok ππΌ
Anyone here used django all auth Iβm having trouble getting the user object in request
whats your problem?
when i call the api on my server the user object isnt returned, if i do it using my browser then it works, how can i get the user object through an api call?
the request.user object
it works on browser call
but not when i call using the axios
sry brother, never used axios or implemented rest api
hey
can anyone help me plszzzsszzz
my css and js are not loading whenever I host it
on my local host it is loading
my local host
and this is hosted by drv.tw but I have tried hostinger also
its not loading css and js
what should I do????
??
helppp
Axios is a package for calling an api in JavaScript like fetch but rest is completely different thing and Iβm already using rest standard in django
no
Try with vercel if not
I am using bootstrap
Never used it
Can some one help me I need to ship my product but Iβm stuck on this for last two days
.
@warm patio Well, what's the difference between a "browser call" and the request from axios?
anyone else?
Your http request with axios should contain information about your user, such as a token, which your authentication backend can use to return a user.
So I have a next js front end and Iβm calling the api from there by browser call I mean entering the url directly in browser
Doesnβt happen when I call the api using fetch or axios but works through the search bar
What authentication method are you using?
No, because instead of storing cart info on the server you're storing it on the client. A singular request will have cart information linked with it so you can then retrieve products.
With your method, how are you going to identify which user has a specific item in their cart?
Django allauth Twitter
@warm patio hmm, I'm not sure about that authentication method - but with any authentication, your request should include identifiable information about the user you're trying to authenticate. A bare http request with no such data will not authenticate a user.
Umm I just get the users name or if and save it in the db but Iβve never implemented shopping cart feature so idk
Do you think this is because when redirecting to next js the session data is getting lost
This is the only reason I can think of
@opaque rivet pls read this
do you need to purchase storage separately to host media files in digitalocean? i am talking about media files not static files
What do you guys use for logging in Django as well as whatever frontend you're using? Does the FE error logging in production generally get sent to the BE and processed there or does the client handle its own errors to log to a file?
third party JWT library with writing its tokens to cookies with block from javascript access
frontend person is going to be searched % Probabling going to be React, but I am eyeing Vue.js plus there will be usage of React/Vue Native as well
If I would be doing for my own project, I would go for Svelte ;b
ah, no no, logging errors.
and you said for logging as observability
I am at the moment implementing it
going for Promtail + Loki + graphana
For FE or BE?
BE
Gotcha. What would you use for FE error logging?
partially observability is also covered with Prometheus and its Exporters
it has exporter for Nginx too
so probably FE will be covered with just it
Plus I attached Alert Manager to prometheus π
So I get alerts to discord if something went bad
Prometheus is also exported to Graphana
Hm
Yea I suppose I could just log errors to my discord server.
With a custom discord hook logger.
Actually prometheus makes nice observability
It has exporters for Linux, for Django, for Nginx, for any database
the only thing its missing, catching custom logs comfortably, that's why adding Promtail/Loki
together they should have a good basic coverage
it could be cool to go for something advanced like tracing instruments in addition(Jaeger?), but oh well, that would be a wish for a future
I'm looking for the simplest implementation I can get. I assume logging to stdout is the easiest.
Maybe I'll bite the bullet and use Sentry. π
there is always logging library π
as simpliest solution
Sentry looks cool to try though
I am mostly going with Loki because it... is a choice for growing sort of?
as far as I heard it is highly used with Kubernetes
so.. going to be cool compatibility in some future
plus, it is universal to catch logs from any frameworks/languages
Any idea how can I compile multiple css files into one global css file?
Need it to happen whilst in development too
Why do you need to?
because I have like to have my scss files organised into different sections whilst building a big project
and then compile into one file, and then minify
Using templates?
or a FE framework?
Short answer I don't know, but why would you need to combine them? Does minifying and importing multiple files create an issue?
Doesn't scss have an include directive?
So you can have one file that includes your others, and compile that specifically?
I know there's one CSS system that works that way at least
There's partials, yes
You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is a Sass file named with a leading underscore. You might name it something like _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @use rule.
https://sass-lang.com/guide#topic-4
Syntactically Awesome Style Sheets
@past cipher ^ Are these what you're looking for?
Also, if you're using the JS API there may be a way you can do that directly from there
Anyone familiar with djongo + Django REST framework? https://github.com/nesdis/djongo/issues/568
is there a jetbrains ide for web dev like using firebox css html js all in the one ide
phpstorm I think?
it is php focused
but iirc it supports the rest of webtech too
Why my css is not rendering? I think I have everything correct, a static folder with my index.css file in there, and I have a layout html:
<!DOCTYPE html>
<html>
<head>
{% if title %}
<title>WeatherBuddy - {{ title }}</title>
{% else %}
<title>WeatherBuddy</title>
{% endif %}
{% block head %}
{% endblock head %}
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>
And this is the index.html page:
{% extends "layout.html" %}
{% block head %}
<link ref='stylesheet' type='text/css' href="{{ url_for('static', filename='index.css') }}">
{% endblock head %}
{% block content %}
<h1>The Weather, one search away.</h1>
<h3>Search for a city to know its weather.</h3>
{% endblock content %}
hey i am new to this field in web development , i am trying to make a website using django and mysql , so what should i need to download to activate mysql
how do i know my mysql database username and password
any resources
Which is better for web dev?
Mid 2011 mac mini
- 2.3GHz dual-core Intel Core i5 with 3MB on-chip shared L3 cache
- 8GB RAM
- 240GB SSD
Acer Chromebook 311
- 1.1GHz Intel N4000
- 4GB RAM
2011 mac, generally, the better specs, the better it is. (It could be different depending on the situation your in.)
Firstly mysql-server and then mysql-client.
yea i downloded all that and when i run it it is saying acess denied for the local host
Hey @heavy oak!
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:
django.db.utils.OperationalError: (1045, "Access denied for user 'AJR'@'localhost' (using password: YES)")
I think you need to reset mysql root password and create new db and user for your project
https://www.google.com/amp/s/www.techrepublic.com/google-amp/article/how-to-set-change-and-recover-a-mysql-root-password/
this error it is showing when i run python manage.py runserver
i downloaded now so i remember my password
i am kinda new so i dont know how to create a new db , any resources
You can use mysql workbench
Or follow this https://matomo.org/faq/how-to-install/faq_23484/
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX , DROP , ALTER, CREATE TEMPORARY TABLES, LOCK TABLES ON **csproject **TO 'AJR'@'localhost'; when i use this code it is showing no database selected but my database name is **csproject **
what is the problem can you please tell , srry for the ping but it was important ππΌ
ok it worked srry for the pin g
can anyone suggest some good resources to learn django?
There is a tutorial in the documentation
Hi
<a href ="index.html"><button type ="submit"> Click here </button> </a>
The form gets submitted but it doesnt get linked to "index.html"
Hi. I want to write an API consumer using python, to get data from a web site. Is there any good wrapper library that gives template classes/abstractions? Or I should use requests to develop my own? Thanks.
do you need to purchase storage separately to host media files in digitalocean?
i am talking about media files not static files
bro r you using any backend with it?
no
so what do you want exactly?
the form to get submitted and linked to another page
u need to use backend for that
but leme see if there's any solution for that
node.js or js?
js
it needs to be redirected from backend
so what to do?
is it a project to be submitted?
yep exactly
ok wait
form method is post or get?
post
action?
not defined
actually i got a project from school
i havent defined an action
the data isnt stored
i dont understand dutch
just check yourself
from html it is not possible ig
we can use jquery
they say create an html form which in which the submit button gets linked to another page
idk
i ll just skip it then
they didnt teach us any javascript yet
its just css and html
but anyway why is it not possible? @civic crater
yeah it is possible by backend
wait a sec
they didn't said that form needs to submitted
https://www.google.com/amp/s/programminghead.com/AMP/how-to-link-submit-button-to-another-page-in-html.html this website says its possible with 3 ways i tried all the 3 ways none of them worked
If want to know about, How to Link Submit Button to Another Page in HTML using Form, Anchor and JavaScript. Then you have got the Right Tutorial.
yeah i m also trying these
and if you need to link the form u need to use backend
they are using PHP for that
is php necessary for type = submit?
because i could link any other type with anchor and java script
yeah bro you can link a button to other webpage
but cant submit a form to other webpage in html
then there is a need of backend
i cant use js as a backend?
yeah u can but u need to install node.js
i do have it
would you like to build it in django?
sorry i dont know django
no i dont practice php too
π¦
l'll try if i can help you
as i know basics of node.js
i have visual studio code i m pretty sure i installed it but how do i start a project
excuse me guys, do u guys know how can i group css rules? i wanna do something like below, and i think i've seen it before
/* Pricing section */
#pricing {
padding: 7% 15%;
.row {
text-align: center;
margin: 10px 4.5rem;
}
}
I want to add further rules for .row elements which has a parent of #pricing
there is a flask application that works with celery + redis. When starting 50-100 tasks, after completing all of them, 2-3 (sometimes 5) tasks freeze, they are not executed. If you restart celery, the tasks that are frozen will be executed.
celery run:
celery --config=dmndmn.celeryconfig -A dmndmn.celery_run.celery worker --loglevel=info --concurrency=5
start tasks:
tasks.start_scan_task.apply_async(args=[id])
help please
I'm a student and can't afford paid domain hosts..
I dont need much from the host just a custom name nothing else. no storage and all.
Does anyone has any ideas where i can get one ???
Please ping me on an answer tyy
ok ty
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
subject=request.POST.get('subject')
desc=request.POST.get('desc')
thumbnail=request.FILES['thumbnail']
file=request.FILES['file']
author=request.user
entry=Notes(title=title,subject=subject,desc=desc,thumbnail=thumbnail,file=file,author=author,published_on=datetime.now())
entry.save()
messages.success('Notes updated successfully!')
return redirect('/')
return render(request,'index/notes_upload.html')```
it's storing to the db
but instead of redirecting
it's showing
TypeError at /notes_upload/
success() missing 1 required positional argument: 'message'
it's saving to the db not a problem but not redirecting insteading of that it gives error
What is success()?
How do I serve files requested by flask?
@dusk portal because you need to pass two positional arguments, the request object and the message.
Normalise reading documentation
It is possible in SCSS or SASS else you need to write like this in CSS3:-
#pricing{
padding: 7% 15%;
}
#pricing .row{
text-align: center;
margin : 10px 4.5rem;
}
SITE_NAME = 'https://www.whatsmyua.info'
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
@app.route('/')
def index():
return("nuts")
@app.route('/<path:path>',methods=['GET','POST',"DELETE"])
def proxy(path):
global SITE_NAME
global excluded_headers
if request.method=='GET':
resp = requests.get(f'{SITE_NAME}')
headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
response = Response(resp.content, resp.status_code, headers)
return response
elif request.method=='POST':
resp = requests.post(f'{SITE_NAME}',json=request.get_json())
headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
response = Response(resp.content, resp.status_code, headers)
return response
elif request.method=='DELETE':
resp = requests.delete(f'{SITE_NAME}').content
headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
response = Response(resp.content, resp.status_code, headers)
return response
When I request http://127.0.0.1/test, it acts as a reverse proxy for https://www.whatsmyua.info. The page loads, but the css and js needed by the page don't. How do I fix this?
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /test HTTP/1.1" 200 -
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /css/style.css HTTP/1.1" 404 -
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /js/app-built.js HTTP/1.1" 404 -
127.0.0.1 - - [16/Sep/2021 13:21:37] "GET /js/app-built.js HTTP/1.1" 404 -
I am doing same things and it work
messages.success/error/info(request,'THIS IZ MESSAGE')
and then return render redirect HttpResponseredirect n all
And in html for object in messages and {{object}}
hello django peeps can you help me ?
There's no need to be dismissive. Asking to ask is fine in this community.
Go ahead and tell us what your problem is.
I want to show in the author detail template the blog posts the author made
DETAIL VIEW
class BlogAuthorDetailView(generic.DetailView):
model = BlogAuthor
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet
context['blog_list'] = Blog.objects.filter(author=self.user)
return context
MODELS.MODEL
class BlogAuthor(models.Model):
# author name
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
bio = models.TextField(max_length=1000, help_text='Write a short biography')
def __str__(self):
return f'{self.user}'
def get_absolute_url(self):
return reverse('blogauthor_detail', kwargs={'pk': self.pk})
class Blog(models.Model):
name = models.CharField('Blog Name', max_length=200)
post_date = models.DateTimeField('Date Posted', auto_now_add=True)
author = models.ForeignKey(BlogAuthor, on_delete=models.CASCADE, null=True, blank=True)
text = models.CharField('Blog Text', max_length=1000, help_text='Short description of your blog')
class Meta:
ordering = ['post_date']
def get_absolute_url(self):
return reverse('blog_detail', kwargs={'pk': self.pk})
def __str__(self):
return f'{self.name}'
TEMPLATE HTML
<!-- Section 2: Contact Information -->
<section id="contact-info">
<h2>Blogs List</h2>
<ul>
{% for blog in blog_list %}
<li><a href="{{ blog.get_absolute_url }}">{{ blog }}</a></li>
{% endfor %}
</ul>
Any one can suggest me described django rest framework YouTube tutorial?
When returning a Response object, flask(the app) thinks the content is hosted on the current site (localhost) and tries to get the JS and CSS files for it. Hence, the 404 code
Hello people! I had a problem.
My homepage takes too much time to load, so what I wanna do is show some other page until it loads, and then show the original page, and I was wondering how I can do this. Any ideas? I suppose this is a common issue. I am using django btw. And you can check out the project at https://github.com/ayushsahu247/StockInvestingApp
Yes, Tomi Tokko has a good one. Check him out
I don't use Django but I'll advise to use this link- https://web.dev/measure to help you out with reducing your page loading time
It can also be done with chrome developer tools
It doesn't have to be online. From Google Chrome, in the Development panel(with console and others), you can click the arrow button and use lighthouse with your Django app on localhost
whats lighthouse?
It's the equivalent of webdev on Google Chrome, for measuring performance of web pages
I can't figure this out my dude
wheres the arrow button?
Have you tried to inspect element in Google Chrome
what then?
On the pane with elements, console, sources and others, there should be an arrow at the end(or lighthouse on that pane)
ok i got something
so i have to do this on my localhost's page?
Yeah, when you load the page in Google Chrome, you run lighthouse on it(Generate report btn)
Usually, JS is the culprit for slow page loading
in my case its the api
i think
thanks man!
Alright. What's your page load time in seconds?
The first contentful paint and time to interactive
Below under "opportunities" are suggestions to help your page load faster
in Django how can I configure the error log to be sent by mail
every time there is an error, it should be sent by mail
what is better, knox auth or JWT based auth?
do people use and configure django admin interface in actual products? in either base django or a rest api?
Any idea how to deal with MemcacheUnexpectedCloseError?
exceptionpymemcache.exceptions.MemcacheUnexpectedCloseError
Bases: pymemcache.exceptions.MemcacheServerError
Raised when the connection with memcached closes unexpectedly.
This is all I got from the documentation π¦
Thanks! Lighthouse score went from 30 to 83
so, I'm using python django with react, and I am creating an SPA website
I have a few pages that just need to render the index.html file, because all the frontend is filled in by react
so I have created urls for those pages, but for some reason I can only render the root website directory(localhost:8000), but whenever I try to load something else, for example I have a url /profile, it just gives me an error, saying that it couldn't get /profile/static/main.js
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.IndexView.as_view()),
path('profile/', views.IndexView.as_view()),
]
from django.shortcuts import render
from django.views.generic.base import View
class IndexView(View):
def get(self, request):
return render(request, 'index.html')
index.html:
<script src="static/main.js"></script>
template dir's in settings:
PROJECT_ROOT = os.path.dirname(__file__)
'DIRS': [
os.path.join(PROJECT_ROOT, 'static') #ΡΡΠΎΠ±Ρ ΡΠΏΡΠΎΡΡΠΈΡΡ Ρ
ΡΠ°Π½Π΅Π½ΠΈΠ΅ ΡΠ°Π±Π»ΠΎΠ½ΠΎΠ²
],
I just don't understand, why does it look for the main.js file in /profile/static/main.js, but not just /static/main.js
because when I go to the root url of the site, everything is fine
nevermind, people of the internet, I fixed it by changing <script src="static/main.js"></script> to
{% load static %}
<script src="{% static 'main.js' %}"></script>
im just trying to create a simple documentation for my discord bot how would i learn how to do that
you can make notes right in your program files, explaining each function and etc.
or you can create a github page for it with a readme.md file, which will have all the documentation/explanation of the whole of your program
What kind of docs are you trying to make? User docs or developer docs?
for the cmds and stuff of my bot
For users I'd just use markdown
@glacial yoke because that src path is relative. If you are on http://site.com/profile/, the src is relative to it, so it will become http://site.com/profile/static/main.js
For absolute paths prefix it with /
Yeah, thanks, I already fixed it, so itβs all fine now
But of course your solution with static is always best, because then you can dynamically change all of the src of your static files.
Hey, i'm creating a web app and I need to ensure the user can only access only their data. What is the recommended secure way of doing this? So far, it seems you use the same database and filter by user=request.user. Do you have any links or documents / youtube videos I should watch to do this in a highly recommended way.
https://bot.cprc.repl.co/ how do I fix the navbar on mobile? should I check for aspect ratio and make a burger menu?
hey guys i have a javascript question
Im sending an array like so
$('#proceed').click(function(){
var items = [];
$(':checked[data-assetid]').each(function(index,value){
var assetid = value.dataset.assetid;
items.push(assetid);
});
var data = {
'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val(),
'item':items
};
$.post( "/test/", data,function(data){
alert(data);
});
});
but what im receiving is
{'csrfmiddlewaretoken': 'B9XLe2X4tj7DGoist0liricYmTayfSYibxHDbruEl78Kgf1c1smobwmIwI2SunSm', 'item[]': '23271161534'}
why is that bracket there
I have not set it in the dict but its automatically being added when its sent to django
how can i add uuid into the flask module?
it keep shows the error sqlalchemy.exc.CompileError: (in table 'patient', column 'subid'): Compiler <sqlalchemy.dialects.sqlite.base.SQLiteTypeCompiler object at 0x7fbf5afe6dc0> can't render element of type UUID
this is the question of authentication
and authorisation
what framework are you using?
you can use UUID type only with postgresql I believe. Not with sqlite. You would have to do something yourself.
I think the easiest method is to just use String type, and give the default argument the uuid.uuid4 function:
subid = db.Column(db.String, default=uuid.uuid4)
Django
Thx. So basically one database and filter based on request.user.
That make sense ig
please guys can anyone help?
hey i added a css file with html using vsc and when i see the preview it is working , but when i run my server using python manage.py runserver and it is showing only html file not the css file effects coming
@heavy oak your page is probably cached. Hard reset the cache with ctrl + F5
it worked thank you
Nice. Is the page loading fast enough that you don't need an extra page while loading?
@wary flint Yes, but to access request.user you need a method of authorization, to actually get a user object from the request.
need help storing user input from a html form into a txt file but it wont work idk why, everything works on windows but wont work on ubuntu for some reason
r you using django?
nope its html/php related
thats why i put it here
idk if this is supposed to be strictly python tho but i assumed not necessarily since its a webdev chat
non-Python stuff is allowed if it relates to Python web dev in some way
e.g. asking for non-in-depth help with your JS frontend that connects to a FastAPI backend is usually okay
but if it's like a PHP backend...maybe not π
i got this error please help
can i test stripe webhooks in production without stripe cli?
i created a endpoint but the event is not recieving
Hey i have a text field stored in my database.
But when i show that in my html template the new lines doesn't show the new line.
it worked
but i also want to use safe filter
you can chain filters
yes just remove the space from between | and safe
done this {{text|linebreaks|safe}}
it shows new line
but dont render it in safe filter
because i want to use html snippets
yeah something like that
use the markdown package
ok leme try
bro it worked when i did changed the position of safe filter
like this : {{text|safe|linebreaks}}
TY
lol np
Hi,
I'm using DRF
I wanted to know about if DB queries are transactional, I'm making use of postgres
For instance my current code is
group = Group.objects.get(id= <id>)
member = Member.objects.get(id=<id>)
current_points = group.points
member.previous_points = <some int(ex:20)> from <somewhere>
member.save()
group.points = member.previous_points + current_points / <some int> (Assume there's a division by zero exception thrown here)
group.save()
Is the data to member object saved or is it omitted until everything is succeeded?
What I understood is by default it uses autocommit mode
Main two differences between windows and linux filesystems
-
linux has all paths as /somepath/folder/subfolder (instead of Windows where it is C:\somepath\folder\subfolder
-
in Windows C:\folder and C:\FOLDER are the one folder.
Linux case-sensetive, it is not like that there. Write the path with exactly same letters as it really is.
- linux like Windows has file and folder permissions for reading/writing/executing. Perhaps you don't have writing rights in your linux folder.
P.S. Small advice, consider developing from ubuntu desktop if you are deploying to ubuntu server.
It will make life much easier
Since you would test your program in your development area in advance to work for linux
It is one of twelve app rules actually
A methodology for building modern, scalable, maintainable software-as-a-service apps.
Yes member object will be saved successfully unless you place your operations inside a atomic transaction block
Django - Anyone got a clue what might be the issue with this? https://github.com/nesdis/djongo/issues/568
Okay thanks
Hey guys, can i do a question about html and css here?
Can anyone hop on a quick call and explain to me and a friend some key concepts about web communication? somewhat related to the requests library.
Hello everyone, I currently have a pending question in the help-avocado section in regards of a Django question if anyone is available I would much appreciate the help !π
how can i deploy my quart app on github like example.github.io ?
Anyone please?
Can someone explain to me the concept of Keep-Alive & Connection Pooling? in the voice channel is preferred
how can i debug a site like this , not sure if its called debug or wtv
anyone uses django consistently?
is there any option that i can make a free website with my own hetzner server? i want to make a bot who links my website where you can register
Only browsers enforce cross origin requests, so does anyone know if you requested a server resource from another origin and you used django-cors-headers, would the request be successful, or would it be blocked?
<a href="/update-patient/{{patient.subid}}" this is my html code for a button, and i made the route to /update-patient/patient.subid, but whenever i click on it, it always brings me to update_patient/{{patient.subid}}
how can i fix it?
Same way as datetime.date should work:
>>> from datetime import date
>>> foo = date.today()
>>> foo
datetime.date(2021, 9, 18)
>>> str(foo)
'2021-09-18'
generally - when you call sth like print(foo) it should return str automatically.
Hello i have a question. What stack usually django goes in?
The Unchained stack π
LOL
can you give more context @white cove ? are you talking about what frontend stuff django plays well with?
Yeah, i mean that kind of stuff
Not exactly what i was looking for but thank you i guess
nope doesnt twork
im trying to display in image located in my static file but from within my vue app
is it not a datetime object? what does type(foo) tell you?
wym
reCaptcha isnt allowing captchas from my local area IP address
i put in 192.168.1.166 and it is saying invalid domain for site key
what are the steps to be professional back end developer with Django
https://host.infinityiron.xyz/whois/ryon
this is my website i need help in making it's embed say
showing info for {user}
please ping me when you have a response :D
(context django) when i have login required to a view and someone who is not logged in tries to post request to that url then he is redirected to login page and after login do they get redirected to that previous url with post request?
hey what is recommended to make a login/logup systm in django?
by making a auth app?
I'm rendering my Vue app from within a Django template but I can't get an image to show up
Is that in flask or Django?
use the excellent built-in authentication framework: https://docs.djangoproject.com/en/3.2/topics/auth/
browser redirects are always made via GET - so you will most likely want to put login required to the view that the user will fill out
let's solve it here - where is the connection failing? do you get the request in nginx, but get an error in your app? do you get an error in nginx trying to connect to the app?
there's no predefined way of how to become a professional developer with anything. imo, what you are looking for is to work with django until you find yourself comfortable enough to build your apps in it easily, and follow best practices of the community. it's also always a good idea to help out with open source projects using django, if that interests you
you usually deploy django behind an application server such as gunicorn or uwsgi, and then have NGINX or another http-capable proxy (e.g. haproxy) sit in front of gunicorn, accept HTTPS requests, and forward them to the backend. is that what you meant?
Please
@stark tartan hey, we wouldn't want anyone to post invite links publicly on the server
and it can be unsafe in some situations
you can always carry out discussion in our voice channel and ask for stream perms if necessary
hey i want to download pycharm for web development does the base community version support html , css and javascript? or i need to buy the professional version?
Yes thank you
Hey I am deploy django channel on liunx sever with nginx it is socket connection is failing over https
If some one have knowledge please
post your full question
which error are you getting, from where, how did you configure it
Okay wait now
erroe in consuole 1 WebSocket connection to 'wss://texqapmkle.com/ws/global/' failed:
@meager anchor
Hey are you there @Volcyy#2359
Any other info you want
wss:// is encrypted, and your site doesnt have any ssl configured. so wss will most likely fail while doing the tls handshake
I have bro
Website is working fine
But WS creating problem
In HTTPS mode
Did you ever done thess thing
your nginx config mentions gunicorn.sock, are you running this under gunicorn? judging from the channels docs you need an ASGI server to server websockets
https://channels.readthedocs.io/en/latest/deploying.html has a reference on which proxy headers you need to set, perhaps that's causing it to throw up
and gunicorn doesn't support asgi https://github.com/benoitc/gunicorn/issues/1380
use a server like daphne or uvicorn
Sorry guys, I don't know where else to ask so I'm asking here. I'd like to have a domain like awake.com and want to create different mails for different services so I know which asshole company leaks or sells my mail to others. What do I need to buy (VPS? Just a Domain?) to establish a system like that?
No related to web dev
Should we learn HTML or its not required for web development
I learnt python basics
And want to go for web development
I study computer science not biology
I will take it as yes
HTML is basic boss
Hey it's done now
Thanks for support
hey there! can I enabled on the heroku gzip compression?
I am running django with gunicorn inside a docker container on port 8000
I also have a nginx web-server set up listening on port 80 and redirecting requests to upstream server on 127.0.0.1:8000 (django docker container) it all works well, however website is also accessible through http://domain_name.com:8000 and I can't find out how to prevent it, can anyone help me figure this out?
hey guys, maybe someone could help me finish setting up my project with django+vue+webpack?
my dev.py settings:
from .settings import *
DEBUG = True
ALLOWED_HOSTS = ["*"]
MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
INSTALLED_APPS.append("debug_toolbar")
INTERNAL_IPS = ("127.0.0.1", "localhost")
WEBPACK_LOADER = {
"DEFAULT": {
"BUNDLE_DIR_NAME": "",
"STATS_FILE": os.path.join(BASE_DIR, "frontend/webpack-stats.json"),
# 'STATS_FILE': BASE_DIR.joinpath('frontend', 'webpack-stats.json'),
}
}
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = "/dmedia/"
MEDIA_ROOT = os.path.join(BASE_DIR, "mediafiles")
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
VUE_ROOT = os.path.join(BASE_DIR, "frontend\\static\\")
CUT FROM settings.py :
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))
STATICFILES_ROOT = os.path.join(BASE_DIR, "staticfiles")
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"ObjectMgr",
"webpack_loader",
]
ROOT_URLCONF = "ObjectMgr.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "ObjectMgr.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
index.html
{% load render_bundle from webpack_loader %}
{% load static from staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>frontend</title>
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=viewport content="width=device-width,initial-scale=1">
<link rel=icon href="{% static 'favicon.ico' %}"> {% render_bundle 'chunk-vendors' %}
</head>
<body><noscript><strong>We're
sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to
continue.</strong></noscript>
{% for i in 'abc' %}
<strong>{{ i }} DJANGO PART</strong>
{% endfor %}
<div id=app>
</div>
{% render_bundle 'app' %}
</body>
</html>
wsgi.py
"""
WSGI config for ObjectMgr project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ObjectMgr.settings")
application = get_wsgi_application()
urls.py
import os
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from django.views.static import serve
favicon_view = RedirectView.as_view(url=os.path.join(settings.STATIC_URL, "favicon.ico"), permanent=True)
urlpatterns = [
path("favicon.ico", favicon_view),
path("", TemplateView.as_view(template_name="index.html")),
path("admin/", admin.site.urls),
url(r"^static/(?P<path>.*)$", serve,
{"document_root": settings.STATIC_ROOT}),
url(r"^dmedia/(?P<path>.*)$", serve,
{"document_root": settings.MEDIA_ROOT}),
url(r"^media/(?P<path>.*)$", serve,
{"document_root": os.path.join(settings.VUE_ROOT, "media")}),
url(r"^img/(?P<path>.*)$", serve,
{"document_root": os.path.join(settings.VUE_ROOT, "img")}),
url(r"^js/(?P<path>.*)$", serve,
{"document_root": os.path.join(settings.VUE_ROOT, "js")}),
url(r"^css/(?P<path>.*)$", serve,
{"document_root": os.path.join(settings.VUE_ROOT, "css")}),
url(r"^fonts/(?P<path>.*)$", serve,
{"document_root": os.path.join(settings.VUE_ROOT, "fonts")}),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r"^__debug__/", include(debug_toolbar.urls)),
] + urlpatterns
vue.config.js:
var BundleTracker = require('webpack-bundle-tracker')
var WriteFilePlugin = require('write-file-webpack-plugin')
module.exports = {
outputDir: (process.env.NODE_ENV === "production" ? 'dist' : 'static'),
publicPath: '/',
devServer: {
publicPath: "http://localhost:8080/",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method",
"Access-Control-Allow-Credentials": "true",
},
},
chainWebpack: config => {
config.optimization.splitChunks({
cacheGroups: {
vendors: {
name: 'chunk-vendors',
test: /[\\\/]node_modules[\\\\/]/,
priority: -10,
chunks: 'initial'
},
common: {
name: 'chunk-common',
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true
}
}
})
},
configureWebpack: {
output: {
filename: 'js/[name].js',
chunkFilename: 'js/[name].js'
},
plugins: [
new WriteFilePlugin(),
(process.env.NODE_ENV === "production" ?
new BundleTracker({
filename: 'webpack-stats-prod.json',
publicPath: '/'
}) :
new BundleTracker({
filename: 'webpack-stats.json',
publicPath: 'http://localhost:8080/'
})
)
]
}
}
first problem in index.html:
'staticfiles' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_urls
cache
i18n
l10n
log
static
tz
webpack_loader
if I change import from {% load static from staticfiles %} to {% load static from static %} I get another error related to webpack configuration that I cannot fix
In template /ObjectMgr/templates/index.html, error at line 12
WebpackBundleLookupError at /
Cannot resolve bundle chunk-vendors.
Any help with this would be much appreciated
nvm i solved it π
Can someone help with debugging this behavior in Django with djongo? https://github.com/nesdis/djongo/issues/571
I'm trying to setup a project but somehow I cannot properly connecting my backend to my frontend
dev.py :
from .settings import *
DEBUG = True
ALLOWED_HOSTS = ["*"]
MIDDLEWARE.append("
I'm having some trouble with authentication with my web app and I"m getting this error, any ideas how to fix it?
I'm using firebase and react
Whenever my client API tries to connect to my sio web server it returns this error ```
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/quart/asgi.py", line 311, in call
await self.app.startup()
File "/usr/local/lib/python3.9/site-packages/quart/app.py", line 1757, in startup
await gen.anext()
File "/app/run.py", line 43, in func
await sio.connect(url="http://172.20.128.2:5000")
File "/usr/local/lib/python3.9/site-packages/socketio/asyncio_client.py", line 144, in connect
raise exceptions.ConnectionError(exc.args[0]) from None
socketio.exceptions.ConnectionError: Unexpected status code 404 in server response
Seems as if your server answers with a 404 (Page not found) error code. Have you tried opening the http address with a browser or a command line http client such as curl? Do these get an answer other than a 404?
oo
When testing outside of implementation it seems to work fine but I get this error when trying to implement. What do I need to return from the server in order to evade this 404?
how should I write a docker-compose and Dockerfile for a flask backend with postgres?
ok thanks
(context django) how do i pass the next url to redirect to after login to login_required for a specific view?
You can embeded next paramenter in url
and how will you do that?
Something like this. https://realpython.com/dockerizing-flask-with-compose-and-machine-from-localhost-to-the-cloud/
error
relevant code
def user(value):
with open('allowedKeys(v1).json', "r") as E:
k = json.load(E)
try:
return k[value]['name']
except KeyError:
return "Error 404 user not found"
def V2_encode(name, key):
with open("allowedKeys(v1).json", "r") as E:
l_E = json.load(E)
l_E[key] = {"name" : name, "key" : key, "attrs" : {"Private" : "None", "Admin" : False}}
with open("allowedKeys(v1).json", 'w') as E:
json.dump(l_E, E)
def V2_decode(name):
with open("allowedKeys(v1).json", "r") as E:
k = json.load(E)
try:
return dict(k[name])
except KeyError:
return "account not found."
@app.route(f'/dev-point/{set_route()}/<name>')
async def ocn(name):
V2_encode(name, assigner.give_id())
return V2_decode
@app.route('/')
async def return_landing():
return redirect('/landing')
@app.route('/landing')
async def call_():
return await render_template("landing.html")
@app.route('/login/@<name>')
async def asd(name):
return await render_template('the-game.html', name=user(value=name))
@app.route("/sign-up")
async def aksj():
return await render_template("sign-up.html")
@app.route('/sign-up', methods=['POST'])
async def on_():
key = assigner.Create()
txt = (await request.form)['text']
V2_encode(txt, key)
login_key = V2_decode(txt)['key']
return redirect(f'/login/@{login_key}')
if you have an answer please ping me :D
its loading faster.
Hey people
How to render a dummy page until the real one is loaded?
a page like this
Is it possible that I send data as it is computed, instead of waiting for it all to compute and then send?
(context django)
pq = Product.objects.annotate(sales=Sum('items__quantity'))
when i loop over pq and print sales of every product it prints them correctly
but when i pq over this it doubles the sales anyone knows why?
pq = Product.objects.annotate(sales=Sum('items__quantity'), rating=Avg('reviews__rating'))
hey yall, how do youll use react and django in production with authentication and everything, i use http proxy middle ware to proxy api calls but it only works in dev mode not when deployed on prod and i need proxy since the user doesnt get saved in the request if i dont proxy
You'll need to use a JS frontend framework, you can render a skeleton page and then populate that page with data from AJAX API calls which happen asynchronously
alright, good. Where do I start learning this?
well you start by learning a JS frontend framework. I work with React and think it's simple to pickup.
are you familiar with the axios request library?
It's a request library. You can make async requests with it to populate your page.
sounds useful. Ill look into it
Does anyone know if Uvicorn has a feature similar to uWSGI multi application mode?
I'm migrating my flask + uWSGI stack over to FastAPI + Uvicorn but would hope uvicorn has a multi-application mode
multi-application mode should allow us create multiple processes per FastAPI applications
The way uWSGI doe it by using the emperor mode. Emperor mode will watch a folder of ini config files. Each file corresponds to a single python app.
Hello Everyone
https://datatables.net/examples/api/multi_filter_select.html
This url has a datatable
i want to reduce the column widths of this datatable so that it takes as less of the horizontal space as possible.
I am trying to add more columns here and it goes out of the page width and table starts horizontal scroll.
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
@final meteor have you looked at this? https://datatables.net/examples/basic_init/hidden_columns.html
i tried responsive: true,
but it will strip off columns automatically to fit the view. it will only show the first X columns that fit in the webpage
i was able to get around this by
<style>
table.dataTable tfoot th,
table.dataTable tfoot td {
padding: 0px 0px 0px 0px;
border-top: 5px solid #111
}
table.dataTable tbody th,
table.dataTable tbody td {
padding: 5px 5px
}
</style>
How can we fix that?
when I zoom out... to see the page smaller... my page breaks. I have it set for cross-browser compatibility so I'm not sure why this happens
Wdym by page breaks?
Layout?
yes
as in like images being distorted etc
I don't know. The Response object in flask is designed to return the request body as html so for sites with inline css, you won't have issues but if they have external resources(like css, js), you cant have access to those resources
Not sure what's the fix for it
Maybe use rem units so that everything scales proportionally
I'll try it
I am
Hello everyone,
I am facing a problem relating to my FastAPI - backend with my Vue - frontend. I have a CORS middleware, and having Axios connecting my "http://localhost:5000" (Fastapi - backend) with my Vue - frontend. But whenever I access my "http://localhost:8080" (Vue - frontend), it's showing raw html, and saying it has no JavaScript enabled. (My JavaScript is 100% enabled, btw..) I'll attach an image of the data returning on the webpage ("http://localhost:8080" (Vue - frontend).
If someone maybe knows what I am doing wrong, please let me know, I would really appreciate that! If more information needed, please let me know.
Thanks in advance.
Disclaimer,I did not work with vue, only helped to deploy react.
Perhaps u a trying to render vue files directly, while they need being run with vue dev server or being built/compiled from vue files into bunch of html/css/js files properly
How about checking official vue deployment docs
Oooh.. That sounds actually pretty solid! Haven't thought of that. Thanks a lot! π
I will, thanks a lot for your fast reply @inland oak !
U a welcome
How do you preserve new lines in Jina?
Hello Sir,
I can't see my grades:/
new lines aren't keep with the above text
It has been a while since I didn't visit discord, at first I didn't know anything, just some html a little bit of css, python and django. things now changed
I want to learn flutter but to learn flutter you should learn dart, should I do that? I am just looking for advice, btw, I don't know js. which one should I go for.
Folks is there a way to get color palletes in bulk? Copy paste hex codes in bulk for generative art?
Perhaps a 100-500 pallettes all together?
Can i make web site in Android?
The best color conversion, naming and scheming API out there.
Over 78034 color palettes listed created by color hex users, discover the new color palettes and the color scheme variations.
Can you explain? Android is an operating system. Using a browser on an Android device you can visit a website. But what do you mean "make web site in Android"?
Can you make one in Java or Kotlin (the primary languages used for Android App development)? Sure you can. But it has nothing to do with Android. You'll look for web frameworks for Java or Kotlin.
Well, learn Flutter if you want to build Flutter apps -- and yes that means you'll need to learn Dart first. Or learn JS and use React Native or something similar to Flutter to make apps using JS as the primary language.
That mean i can't make right?
thanks a ton. How do you auto extract 500+ palettes from site#2?
I don't fully understand.
You can make a website in HTML, CSS, and JS (the basic stack) and you can visit from an Android device.
Or you can build a website in the same languages Android apps are developed in (though you'll still need HTML, CSS, JS [likely]) depending on what the site is you want to build.
You can even use web languages like JS to build out entire apps and cross-compile them to both iOS and Android using Flutter, React Native, Cordova, and a dozen other projects.
You'd have to write a spider to crawl the site and get those palettes. It doesn't look like they have an API.
I want make web for my some work(college demo) useing HTML.
Cool, you can do that. And just HTML can be hosted for free online (GitHub Pages for instance). And then you can view that site from any web capable phone like an Android or iOS one.
But what i need to build web? Need to use any app or something?
No. You can use a text editor. Just gotta get it hosted somewhere once you're ready. Netlify.com, GitHub Pages, free hosting sites or plans.
Someone say you make HTML in any text editor app
I am using gunicorn, nginx, and flask (following corey schafer's linux deploy walkthrough) and nginx isnt serving my static files
thats my nginx config
and here is my app
the path is correct /home/connors/flask/flask_app/static
i have looked online and havent found anything that has helped
when i go to 192.168.1.236/static/main.css i get a 403 error
Django problem: I want to render a page, while I do some computations, and then render the page again. How can I do that?
NGINX doesnt have permissions to look at my static files. How do I elevate NGINX permissions???
idk how to give nginx permission
chmod -R 777 /path/to/folder/with/static/files/
as the easiest and silliest option
it didnt work. I restarted nginx and it didnt work.
chmod -R 777 /home/connors/flask/
changed to static folder still no cigar
do you use ubuntu?
i have limited experience, but im not brand new
which linux server do u use
this is running on ubuntu server on a raspberry pi 3b+
service ufw stop
try using this
it will disable your firewall
which can be an issue
i am making a react project that uses discords oauth2 and integrates with flask and when u click a button on the react side it redirects to the flask discord oauth2 but i cant think of a way to make sure authentication has taken place on the react side so they cant just type in the url manually, any ideas?
still nothing
im sure there is some really stupid user error here
check /var/log/nginx errors
there will be two text files there with some details perhaps
access.log: 192.168.1.166 - - [19/Sep/2021:18:20:19 +0000] "GET /static/favicon.ico HTTP/1.1" 403 134 "http://192.168.1.236/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0" a bunch of these
error.log: 2021/09/19 18:20:19 [error] 3906#3906: *31 open() "/home/connors/flask/flask_app/static/favicon.ico" failed (13: Permission denied), client: 192.168.1.166, server: 192.168.1.236, request: "GET /static/favicon.ico HTTP/1.1", host: "192.168.1.236", referrer: "http://192.168.1.236/" a bunch of these
u know, it looks familiar
referrer.... is a wort of some security mechanism i think, although it can be not involved here
what's your nginx config file for starters
i have tried it with and without the slash at the end
In this Python Flask Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode.
If you would like $20 of free credit towards a Linode account, then you can use my link here to sign up:
https://linode.com/coreyschafer
We will be covering the entire deployment of a Flask application. This includes s...
im following this walkthrough
everything has been just fine up until now
lets remove server_name for now
yeah
nope
and add location /static/ {
im sorry this is so frustrating
slash at the end of it too
nope
Β―\_(γ)_/Β―
at this stage I exhausted blindly shooting the target
only real look would work I guess
I would guess a filesystem permission problem I think
perhaps chmod was not enough to solve the issue
@fiery turret try moving your project to /web folder (which lies at the root of your system) (create the folder)
and hosting it from there
I think you could have some conflicts with that you are trying to host it from your home user folder
even chmod, could be not enough for nginx to access it
i cant cd into /root
do cd /
and mkdir web there
i said /web path, not /root/web
don't forget to apply chmod -R 777 at this folder after you are done
Try changing your alias to /home/... /static; without the last forwardslash
(venv) connors@flask-server:/web/flask$ gunicorn -w 1 run:app
-bash: /home/connors/flask/venv/bin/gunicorn: No such file or directory
oh wait
duh.
create venv from zero
python3 -m venv venv
venv can't be moved, it will have its internal absolute paths broken
hes the most helpful person on this server
!mute 887097812704182283 π
:incoming_envelope: :ok_hand: applied mute to @abstract knoll until <t:1632080394:f> (59 minutes and 59 seconds).
i just posted something weird. leave me alone.
im installing requirements.txt
we could have resolved it also, by launching nginx with root rights π
but whatever, that is the solution too
it works? π
π
can i put up my firewall again?
sure
make holes for http/https traffic in it on your own if necessary
and allowing incoming connections to flask at 8000 port from localhost too, if necessary ;b
programmer is a person who is more stubborn than his computer in error battles
just kidding
when a create a new user I got "Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead." this error.
svg's are cool
Im trying to create a supervisor, but it cant find the location to my gunicorn
is there a way to find where its located?
ive tried using 'find' but didnt work
nvm im a genius
usually you use which but it should be installed in your virtual environments bin folder (if you use one)
I have a question as:
Which library is usually used to make a website using python?
or framework, like what's market requirement right now!
django/flask are very popular python frameworks for building backend web apps
Yes, I'm making one using flask!
,.p
Hello, everyone
I have a few questions about getting django set up. Should I install system wide? Also, if I install on virtual environment do I have to install django through pip every time on separate env under the folder associated with it?
Always use a virtual environment. And yes, you have to install it on every environment separately.
Great, thank you fr! So for example would the code look like this:
Hi all
I'm having a slight problem on something that I suspect is stupidly easy
if we imagine I have the following data structure:
pass
class ModelB(models.Model):
a = ForeignKey(ModelA)```
and I run the following queryset:
A.objects.values()
I have no idea how to get values from Model B
I want to do something like this:
A.objects.values(ModelB__id)
but just not sure how to get values when the foreign key is held on the other table (so to speak)
you can get the related objects like
A.modelb_set.all()
that returns a query of all the modelb objects which have a foreign key pointed to modelA
ooo that's interesting
is there a way to be more specific and only select the desired fields from Model B
yes, but I never do that. I think it is using values as you're trying to do
it's just a normal query so you can do normal query things
A.modelb_set.filter(id=5)
for example
I guess you can do A.modelb_set.all().values('id', 'some_other_field')
hey i am showing an error in django when i import module from my app floder for example if my apps name is sample when i import from sampleapp.module import user(my models name) and when i run the server it is showing sample.sampleapp module not found pls help
thanks so much @indigo kettle ... will google the hell out of it
when i import the module and run my server using python manage.py runserver it is saying
from sample.sampleapp.models import User ModuleNotFoundError: No module named 'sample.sampleapp'
You have two imports that I think are trying to import the same thing
I think you can delete the first line
in views.py
yea thanks it worked π
can you tell me an example that my edit text is recieving the messge
<form class="box" action ="register" method="POST"> <h1>REGISTER</h1> <input type="text" name="Rusername" placeholder="Username"> <input type="text" name="Remail" placeholder="Email"> <input type="password" name="Rpassword" placeholder="Password"> <input type="text" name="Rconfirmpassword" placeholder="Confirm Password"> <input type="submit" name="RegisterBtn" value="Register"> </form>
you are trying to print something inside of an html file?
i just want to know if my input funciton works or not like if i wrote something on username and click register i need to know that it is accepting the name how do i know it
anything i need to know if it works or not ?
i'm following a flask blog tutorial, and after implementing blueprints, my site is messed up
It looks like this
when it should actually look something like this
bruh... I deleted everything in the css file and pasted it back in and now it's fixed
I've had this issue many times where flask shows messed up looking websites for no reason
Anyone know the cause?
itβs a mapping between URLs and the view functions that should be called for those URLs.
what does "mapping" mean?
Do you do a full refresh between changes? CTRL+F5

class Product(models.Model):
name = models.CharField(max_length=200, unique=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
class Order(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='orders',
on_delete=models.SET_NULL,
null=True
)
placed = models.DateTimeField(null=True, blank=True)
class OrderItem(models.Model):
order = models.ForeignKey(
Order,
related_name='items',
on_delete=models.CASCADE
)
product = models.ForeignKey(
Product,
related_name='items',
on_delete=models.CASCADE
)
quantity = models.PositiveIntegerField(
default=1,
validators=[MinValueValidator(1)]
)
how would you annotate each product with the sum of its orderitems quantities that have order__placed__isnull=False?
What's the best way to login with email in django djoser (jwt based authention)
I think you are looking this solution
Product.objects.values('name').annotate(
order_placed_quantity=Coalesce(Sum(Case(When(
items__order__placed__isnull=False,
then=F('items__quantity')
))), 0)
)
I want an advice. js has a great community a lot of courses are out there, I mean you won't get lost, but flutter no, few courses, smaller community, but great framework, I want to learn flutter and dart just because of being able to make a cross platform app with the same code base.
Hello everyone, I'm creating a website where users can upload files to the server, but I can't manage to construct the full file path when I want to delete it again. This is how I am saving the file, so how can I get the full path to remove it again?
def save_sheet(sheet):
# Rename file and return full file name
_, f_ext = os.path.splitext(sheet.filename)
sheet_fn = secrets.token_hex(8) + f_ext
sheet_path = os.path.join(app.root_path, 'static/user_content', sheet_fn)
sheet.save(sheet_path)
return sheet_fn
@app.route('/file/new', methods=['GET', 'POST'])
@login_required
def new_file():
form = FileForm()
if form.validate_on_submit():
# Construct full file path to save and pass to file instance
sheet_file = save_sheet(form.sheet.data)
sheet_path = url_for('static', filename=f'user_content/{sheet_file}')
created_file = File(title=form.title.data, subject=form.subject.data, author=current_user, sheet=sheet_path)
db.session.add(created_file)
db.session.commit()
return redirect(url_for('dashboard'))
return render_template('create_file.html', title='Upload File', form=form)```
Feel free to @ me if you can help! Thanks.
hi guys
Hi
Hi guys can someone help me with this
Im trying to move the "about us" to the right a little bit and it will be fixed there no matter what
Can someone recommend me how to do it
Thanks guys
You can put them both in a div ```
<div>
<img>
<a>About us</a>
</div>
and in your styles you can do div { display: flex; postion: fixed; top: 0; left: 0; }
you are also forgetting to put these :::::::
:
Hey anybody use AWS 300$ credit please ping me I want ask some questions
@next oxide
Tks Iβll try
This code seems good for saving the file. If you want to delete, you can query the file you want and get its sheet attribute(or column) which is added to the created_file before it is saved.
selected = File.query.filter_by(title=<your_title>).first()
file_path = selected.sheet
Hi, thank you for your response. I just found out what caused the problem, apparently os.path.join won't properly point to the location on the file, if I just combine the file path strings normally, everything seems to work. But again, thank you for taking your time to answer :)
(django) how do i pass the url to redirect to after successful login with redirect?
hi!!
Folks how does one convert animtaed GIFs into animated SVGs?
(django) any libraries to have mobile no. and otp based authentication?
you will have to set the redirect url after login in the settings.py
LOGOUT_REDIRECT_URL = ...
LOGIN_REDIRECT_URL = ...```
its already solved but thanks
(django) any libraries to have mobile no. and otp based authentication?
Hey I need some celery help
This my views file
from django.shortcuts import render, HttpResponse
from .tasks import *
from django.core.cache import cache
# Create your views here.
def home(request):
# cache.set('name', 'ayush', 2)
set_name.delay(10)
name='shreya'
print(cache.get())
if cache.get('name'):
name = cache.get('name')
return HttpResponse('Hi, from celery- '+name)
This my tasks file
from celery import shared_task
from time import sleep
from celeryApp.models import Hero
from django.core.cache import cache
@shared_task
def set_name(duration):
sleep(5)
cache.set('name', 'ayush', 10)
return None
But the page still shows name as 'shreya', and not 'ayush'
Hey guys need some wise advice...
please...
I need to get a job or atleast a internship in 6 months. I need to develop knowledge about web development.
I only know the basic knowledge of python.
(Print string in reverse, print triangle pattern ,etc)
I am not sure about front end and backend development...
Can I become a good backend developer by only knowing django , flask .
Do I have to learn about DSA,HTML , CSS,etc????
Which one can i avoid as a backend developer
You can skip DSA imo, but you should know basic html tags no matter what you do in web dev.
mapping means pointing the urls to the function that you've created .
Is anyone available for an issue with serving media files ?
A guide for how to ask good questions in our community.
What is the most widely used modern stack for python in 2021?
i'm talking front end backend DB middleware etc
django rest framework + react (which I would replace with vue or svelte, but they are lesss popular)
drf with any frontend
ok and what DB is most often used with that
postgresql ;b
i'm just looking for the most marketable set to verse myself in since i haven't dove too deep in the python end of professional web/app dev
but i enjoy python more than anything else i work with so it seems like the understandable thing to pursue
https://2020.stateofjs.com/en-us/technologies/front-end-frameworks/
react is leading and occupying 53% of the market π¦
i don't really like JS
Well last time I wrote a lot and no one replied I wanted to make sure someone was available but ok here I go:
Iβm currently writing on mobile*
I have in my media file a folder named 15 with pdf files in it. My goal is to be able to click on the hyperlink that is on a table according to the patient & open up that pdf file.
Now I have my Django href ready and they display accordingly to the patient. However when the link is clicked Iβm getting a page not found and Iβve been trying to figure out what could be set up wrong along the lines of either settings, my model, my html template, or urls & perhaps my view.
I can give any further information as a screenshot as code snippets are quite difficult right now for mobile
JS and TS are the only options for frontend
backend is anything, for python it is django and fastapi popular
you can actually do some front with python frameworks, but it is quite limited in what it can do
that's popular solution yeah
from SQL family
for a single person
what do you mean by its limited ?
if you do frontend without frontend frameworks, eventually you reinvent (poorly) frontend frameworks
or you are limited to html/css only
extensive JS usage is not really good looking there without frontend frameworks
from noSQL family, MongoDB is popular
plus I use Redis for caching and messaging queues
different types of DBs fit different tasks
This is an example : of the main page (127.0.0.1:8000/show) show which is my html template
My file hierarchy as demo as root is as followed :
>demo
>media
/15
All the pdf files
>patients (main app)
>static
Db.sqlite3
Manage.py```
For my media url and root it is as followed :
MEDIA_ROOT = βUsers/Dany/Desktop/demo/mediaβ```
In my urls.py it is set up as followed for media along with the proper imported modules :
Urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT```
Inside my show.html which is my one and only html file serving the table and database I have
{for pat in patient %}
<Td><a href = β(β\media\{{pat.file_name| urlizeβ}}β target = β_blank|_self|_parent|_top|framenameβ>{{pat.file_name}}</a></td>
For the model Iβm only going to be referring to the file field :
class Patient(models.Model:
file_name = models.FilePathField()
Iβm sorry for the extensive post but I want to give as much detail possible, if any more details are required or needed for further assistance please do not hesitate.
Any help would be appreciated
any good tutorials i can follow to learn drf?
EDIT: managed to resolve the issue FINALLY after two days attempting this. The resolution was to change the
<Td><a href = β(β\media\{{pat.file_name| urlizeβ}}β target = β_blank|_self|_parent|_top|framenameβ>{{pat.file_name}}</a></td>
To:
<Td><a href = β\media\{{pat.file_name| urlizeβ}}β target = β_blank|_self|_parent|_top|framenameβ>{{pat.file_name}}</a></td>
Thanks guys ! I knew the rubber duck theory would help π
If anyone has any suggestions to recommend please donβt hesitate ! Just @ me and Iβll be pending improving the app, thanks again !
Hey, I'm stuck with this prob anyone can solve this?
https://stackoverflow.com/questions/69256266/favicon-and-manifest-json-is-not-loading-in-django-react-project-setup
So i have this in django:
class SliderViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint.
"""
queryset = Text.objects.raw(''' SELECT * FROM text WHERE id in (SELECT MAX(id) FROM text GROUP BY domain_id ) order by date_visited desc limit 10 ''')
serializer_class = SliderSerializer
permission_classes = [permissions.IsAuthenticated]
It seem this does not refresh everytime i do a get request, only when i restart the server.
How can i make sure that everytime i do a get request the api refresh the info that it have?
How far have you gotten? What suggestions are you looking for (front end, back end, db, interface questions, what?)
I think you need to consider this "queryset - The queryset that should be used for returning objects from this view.Typically,you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it it important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests."
Above is from this tut: https://github.com/subhra2508/django-rest-framework-tutorial
I'm not a big Django user, but some examples I've seen override get_queryset in your viewset class and that helps make sure that the query runs every time and not just the first time django fires up the viewset.
This seems fairly unintuitive.
When you view the source in browser to see how the template rendered, what URLs are you seeing for those missing files?
lmao for a second i thought you actually used a brush
Wellβ¦ I used the mark up brush on iOS π
def get_queryset(self):
return yourQueryset
Add this method to your view set.
A query such as this one:
Poll.objects.filter(
Q(group__public=True) |
Q(
Q(group__owners__in=[user]) |
Q(group__admins__in=[user]),
group__public=False)
).order_by('-created_at')
Is creating a ridiculous amount of duplicate query objects, does anyone know why this happens?
the only thing i want is to filter if the group is public, or the group is not public (but the user is an owner/admin of the group)
narrowed it down, apparently it duplicates itself everytime Q object is comparing something, 5 members = 5 duplicates + 2 owners = 2 more duplicates
Hate to be another again on this thread, but Iβm trying to hyperlink a folder all the files inside.
Example:
Media/4182554/all pdf files
Iβm receiving a 404 issue βdirectory indexes are not allowed hereβ
If needed above I have details of the project including file hierarchy, settings, models, urls
Sorry if there is some grammar issues or some things donβt make sense, Iβm pretty fried from working on this clients hcms haha
My question is at the end of it:
How can I click this hyperlink to open up said folder and serve all the files inside of it ?
can someone pls suggest good front end dev resource?
freecodecamp to learn html and css seems like the way to go
whos tryna hold this wood while i code?
how can I make an axios post request to my django db, from my react app
axios
.post("/api/message", {
message_author: personaname,
message_text: newmessage,
})
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err);
});
when I run the code above, considering that personaname and newmessage are both strings, it just doesn't work
someone, help, please
Hello hello
I'm wondering if anyone knows whether it is okay or not to modify something within base Django
Specifically, I've modified a line in formsets.py in site-packages which completely sorts out an error I've been getting
Is this a bad thing?
It's probably unadvisable
If the error your getting appears to be a Django issue it would be prudent to create an issue if one doesn't exist for it
If it is not intrinsic to Django, you'd best to fix the issue in your application
Rather than modifying Django to work around your own issue
Of course this is all very general information
I'm not personally familiar with Django, and I am not looking at your code or the Django code you've modified
So I cannot give anything concrete
But in general yes, it tends to be bad practice to in place modify a third party library that you're using
And unrelated but@native tide please do not bump help channels in other chats, be patient. If someone is available to help they will.
Anyway, hope that helps @light cloak ^^
@tribal python I thought that might be the case. It's a shame because Django is apparently not really geared towards dynamic forms, which is what this issue revolves around. An error is being thrown up because I'm using an attribute of Django which has an index of None, and the error is due to index being compared to an integer further in the code. Very frustrating. Thank you very much for your answer though!
I mean, if you can propose a change to Django that wouldn't negatively affect any other circumstance but help improve applications such as yours, it could definitely be worth bringing to them.
Would be interesting to know if it wouldn't negatively affect other applications - I'm fairly inexperienced so I doubt I'd be able to know either way - but I'll see if I can submit a ticket and get them to perhaps take a look at it π Good suggestion
Hi
I'm trying to add a field to my model in django for that I made a migration like this
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('interface', '0011_auto_20210627_2247'),
]
operations = [
migrations.AddField(
model_name='post',
name='postid',
field=models.UUIDField(default=uuid.uuid4, unique=True),
),
]
when I try to run it i get an error
DETAIL: Key (postid)=(85fd7975-0fc8-427c-a0e5-f0c387524bce) is duplicated.
Is JavaScript useless outside web development?
default=uuid.uuid4, you probably have an object for your model which have this default value already, which violated unique=True when adding another object without a specified uuid.
No. There is server side js (nodejs). JS for native app dev (React Native, and a dozen others).
it's also sometimes used as a scripting lang inside of other tools
So, I can build a regular old app which is just a normal executable with a normal GUI?
Like Python or any other language does
not sure off top of head, but there is Electron which allows you to make desktop apps with HTML/CSS/JS
slack, vscode, and other apps you may have used use Electron
discord desktop app -maybe-
haha, I guess .. can build whole websites with it, run api services, I've written some scripts in it that never even touch the web but just run on a schedule
technically nodejs is inside electron too which sets up some cool things you can do between the client js and the backend js
but yeah if I were to make a desktop gui, I wouldn't look to js first
any time
yo ppl, can a css wizard help me out, I am having trouble with a flexbox thingy, I would prefer dm's since i can explain better and not clutter this channel, thanx!
hi
how can I get a user's IP in flask?
request.remote_addr isn't working
I'm using https://replit.com to host btw. If you have an answer please ping me
Thank you
no u can use js for almost ANYTHING now
mobile apps, web apps front end and backend, 2d/3d games, and even hardware programming like arduino
Yes, you can. But not while on replit it seems. Likely replit, for safety reasons, is launching all of your code in an independent container and then serving up the content via proxy.
For instance, when you go here: https://DazzlingIgnorantApplicationprogrammer.thebouv.repl.co
You can see that I'm echoing out request.remote_addr and that the value is a non-routable private address. Likely the address of the proxy making the request.
So a visitor makes the request, it passes through some "stuff", something ELSE makes the request, returns it, and then THAT is showed to you.
Same thing could happen if you had Cloudflare or something in front of your app. You likely will end up with the IP of the load balancer, NOT the address of the user (unless the load balancer itself is setup to pass through the ip but they usually do that via X-FORWARDED-FOR headers). It can get tricky but as far as I can tell you can't really get around it on replit due to how they do their setup. A traditional host wouldn't be like that (unless of course the aforementioned load balancing is in front of it).
Changed my script to show you other headers too:
https://dazzlingignorantapplicationprogrammer.thebouv.repl.co/
You can even see X-Forwarded-For on there. But even that address isn't the visitor for instance.
As when I visit I see 35.191.15.131 and that isn't my address.
That IP is for GCP which is probably where replit.com is hosted.
((or a host is using GCP, and that host is hosting replit))
GCP meaning Google Cloud Platform
thank you a lot for that info
cleared it up
π
you're welcome
Hello, I'm building some cool app with django and drf. But I'm a embarrased how my code is with drf serializers. They are a bit complex and have to juggle with requests that may have an instance or not.
I have a lot of "if self.instance:" conditions in object and field validations. It makes the reading hard.
How can I avoid this and split the code better ? Two different serializers for creation and update ?
Hi there! I'm doing this website where there are three buttons(they represent 3 products) which when clicked need to display their corresponding prices. Could someone please help me out with this? I was thinking this could be done with js but idk how
How can I download Google app engine in windows 10?
I already have Python 3 installed.
I download something called "Google Cloud shell" and it looks like command prompt.
I don't know what to do? Someone helpe out...
Is django rest framework is necessary to learn as we also have to learn React with it??
If I am looking for jobs with django
should i ask about my doubt in android studio here?
Yeah you need to learn rest framework. It is not necessary but if you want to use react as your front-end and django as back-end then it comes handy.
And you are made learn React just to practice. You can do that without react tooo
Good to know
do i need to learn js if i have a good knowledge of how django works?
If you want to do web programming, you'll need to learn JS eventually.
But you don't need JS to make a website - depending on what website, of course.
Can anyone help me out with the helium module?
What is helium?
don't though. Just use it for browser interaction you can't achieve with css/html. phone users prefer native as js is the slow 90s tech built into chrome. Also don't use electron to bundle a 120mb chrome just to run a few hundred lines of js. Just learn something native. Maybe Unity or Unreal for game dev as they are performant and dont run like a dirty 90s browser tech that needs replacing.
I want to learn it cuz Iβm tryna learn web development. I just wanted to know if it can do something other than web.
if you hit a nail with the back of a screwdriver it will go in. but it has limits
Good one.
Hey guys i have a quick question. I have an api endpoint that has pages of data in json format that i'm getting with grequests. It updates every 5 minutes (+- 10 seconds). What would be the best say to store those 200 pages of data with it's ETAG attached (so i can compare it to the new one and replace it if it was updated)?
sorry if wrong chat
use a json db. i.e. coucdb or mongo. then you can just use a http api to update it
couchdb has that built in. really simple. mongo a little harder than couch but you get mongo ql and its more popular.
JSON dbs have http apis built in. so often you're wasting your time parsing when you could have a view with a map/reduce function
ah so those db use json internally? I was using mySQL and it was kinda counterintuitive to connect to the database every 5 seconds just to retrieve ETAG
serilaising to json is a waste of time IMO return html whenever you can. But as you said you have json to begin with . i'd stick with json
yeah i have no control over api sadly
couchdb you can learn in a day or 2. it stores json blobs. you can have API endpoints built into the db that you POST GET from. using the same json blob.
so if its change just POST it
and it will update
amazing. I gonna look into Mongo since i see it quite often. TYVM
ye. i think it has a native http interface now. it never used to.
How to loop through this dict with nested data?
{'English':
{'student': 'John Doe', 'coursework': 'English List 2.3', 'status': 'Accepted', 'comment': 'Very nice bit of coursework, John.', 'grade': '89'},
'student': 'Scott More', 'coursework': 'V3 Ttest', 'status': 'Not Submitted', 'comment': '', 'grade': ''}
With Jinja
nvm just realised its not a nested div
the second student section is missing brackets
How much time is required to learn django rest freamework
@past cipher ```
{% for student in your_dict['English`] %}
{{ do_something_here }}
{% endfor %}
yeah the problem is when I create the dict on the backend
i've been having trouble all day with it
@past cipher what is the problem?
grade_info = []
course_exists = False
teacher_courses = TeacherInformation().fetch_teacher_courses()