#web-development
2 messages · Page 114 of 1
What’s the terminal commands, to run to create a “main.html” file? By the terminal?
Hello. Tried to use retrieve a product by id but Im getting an error.
@app.route('/product/<id>', methods=['GET']) def get_product(id): if id is None or not id.isdigit(): return jsonify({'result' : 'Missing ID!'}), 404 return Product.objects(id=id).first()```
@slow rapids
Try casting it to an int first. As well with mongo you may need a library to help if that's not working either.
So I'm trying to learn web development off a book that works with html, js, and php. The problem being php is dated. Is there a way I can use the
<?>tags but put python in it instead to run server side?
@native tide
PHP was originally just for templates. You can use something such as Django, or Jinja2 with Python. However, it is good practice to keep your logic separated from your templates. This also includes PHP. If you're wanting to really perform calculations and logic on a page look at using JavaScript.
What’s the terminal commands, to run to create a “main.html” file? By the terminal?
@frozen python To just create the file?touch main.html
@frozen python To just create the file?
touch main.html
@warm igloo do I need to CD into anything?
I mean .. depends on where you want the file created. touch main.html will create it where you are.
good idea @jade lark I'll probably do django development after I can figure out angular and dbms. Thank you for your input
@warm igloo thank you, can you also use console to write code? as in a import already and things like that?
write code temporarily just to test? use the repl ( https://pythonprogramminglanguage.com/repl/ )
write code in console and save it? use a text based editor like vi
this is all on *nix btw, I have no idea on windows
@warm igloo thank you. Well, I’m asking as in I want to have some code automatically added into a page like urls.py, so I can add it from the console on some things
@jade lark im using mongo_engine. Thank you for the suggestion
@jade lark im using mongo_engine. Thank you for the suggestion
@slow rapids Ahh that would make more sense. Well I won't be much help on that.
good idea @jade lark I'll probably do django development after I can figure out angular and dbms. Thank you for your input
@native tide
If you're using Django you'll just need to learn the ORM for dbms.
As well if you're doing simple logic just using plain old javascript would work just as well too. Depending on the size and complexity of your application. I would start with Django first and go from there.
^^ Handle the backend stuff first and then implement frontend
And React would be good for that 😉
@jade lark really I'm just learning to work with different things first don't have a project in mind. I just want different options at my disposal
@native tide Best way to learn is to pick a project and work on it. Plus finishing something from start to finish is a good way to build a portfolio
request.method == 'POST': how does this work o.o
@jade lark may i also ask what is the best way to see if a request response is a json? In my case thr request is done inside the endpoint with requests.get(url)
@jade lark may i also ask what is the best way to see if a request response is a json? In my case thr request is done inside the endpoint with
requests.get(url)
@slow rapids
Check the response headers. Specifically the Content-Type
Yeah i also thought of that but thought there would a way to parse the text and understand if it was @jade lark
Tried googling but didnt find much so i am asking
json.loads or json.dumps possibly? You'll need to have exception handling if it tosses a ValueError.
Then checking if a certain key exists or all of them. You could make a helper class or function to validate the data.
Ok thank you for the suggestion
You're welcome hopefully it ends up helping.
for the requests library, .json() does json.loads for you and it's a bit easier esp. since you don't need to import json
res = requests.get(url)
try:
res.json()
except ValueError:
print("is not json")
else:
print("is json")
do widgets work for password fields in django
hey guys im really stuck on this socketio problem
im hoping someone can help
i was working on a chat feature for my web app, however i had to remove the pytho logic, and i moved the html/jquery file outside of my project directory
the issue im having is that socketio is still making continuous polling requests everytime i run the app
even though there's no longer any socketio logic in the script!!!
I created fields with the serializer in DRF, but, only “name” comes up as a field to enter. I also have “description” as a field, but it’s not a choice to enter in anything.
I have this in my base.html template for referencing my javascript file
<script rel="text/javascript" href="{% static 'base.js' %}"></script>
Would this be the correct way to do so?
ahh its different from the css import by using src instead of href makes sense
any help https://stackoverflow.com/questions/64840093/how-can-i-properly-validate-a-rest-api-query-parameters
Oh cool so that's what the the request does in Django, it's an await function for GET and POST. O.o
im creating an app that turns a link from pdf to csv.... im trying to host it on ElasticBeanstalk... is the best way to save it on EBS, then convert, then download it.. Or can the conversion be Realtime, and skip the step where i need to save it somewhere... ?? any ideas?
here is my code ```from quart import Quart
from discord.ext.ipc import Client
app = Quart(name)
web_ipc = Client("localhost", 8090, "TOKEN")
@app.route("/")
async def show_guilds():
guild_count = await app.ipc_node.request("get_guild_count") # Make a request to get the bot's IPC get_guild_count route.
return str(guild_count) # return the data sent to us.
@app.before_first_request
async def before():
app.ipc_node = await web_ipc.discover() # discover IPC Servers on your network
if name == "main":
app.run('localhost', port=8090, debug=True)
but when I try to run sometimes it says File "web/web.py", line 15, in before
app.ipc_node = await web_ipc.discover() # discover IPC Servers on your network
AttributeError: 'Client' object has no attribute 'discover'and other times it says thisOSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions``` I am trying to attach this to a discord bot using a module called discord.ext.ipc and here is my code from there
from discord.ext import commands
# Our bot will be the server we make requests to in order to get data from it.
from discord.ext.ipc import Server
class Bot(commands.Bot):
"""Main bot class"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_ipc_ready(self):
"""Event dispatched upon the IPC being ready"""
print("IPC ready")
async def on_ready(self):
"""Event dispatched upon our discord bot being ready"""
print("Bot ready")
bot = Bot(command_prefix="!", case_insensitive=True)
bot_ipc = Server(bot, "localhost", 8090, "TOKEN")
# ipc.server.Server takes four arguments: the bot object, the port to run the IPC on, and a secret key used to authenticate client connections (seen in the web server file).
@bot_ipc.route() # if no name is supplied in ipc.server.Server.route, the function name will become the route name.
async def get_guild_count(data):
"""This route named get_guild_count will return the amount of guilds our bot is in"""
return len(bot.guilds)
if __name__ == "__main__":
bot_ipc.start() # ipc.server.Server.start will begin the IPC
bot.run("TOKEN") # run the bot as usual```
Hmm trying to use PayPal Python SDK and I have a create request and capture request, they both only check if the request method is POST, other than that how does it differentiate if the POST is meant for create or capture
I used "git clone (github address)" to download my files onto my server but what command do I use to update them after making another change? It tells me I cant use "git clone"command again because that file already exists.
woudnt it be sudo apt update?
do a 'sudo find 'file', see if it exists .. Then delete it... if it does and you dont need it.. otherwise, maybe make a new directory and try again
You would use git pull to bring down your changes @torpid pecan
Awesome, that worked 👍
Hey everyone 👋 .The question I have today is what do you do to minimise risk that may occur due to human error because you are using an unfamiliar language/ new language As software developers? The only answer I can think of testing and reading from the official documents that is it
If you're new to a language, but familiar with another, try to make sure to apply similar patterns of development. So, if you know good security habits for one language, try the same patterns. Look up the version of the pattern in that new language and it will help you understand the new lang better because you've tied it together by concept.
I've even taken old code I wrote in one lang, and translated it to another. It gave me that bridge of understanding.
And if by risk you mean specifically security risk, you can also minimize risk/errors by using SAST and DAST scanning of your code and running application.
If its a web app, make sure to run it through something like ZAP to test for OWASP top ten.
Thanks for the answer that makes total sense, and I've also learned something new do with security testing
hello, i'm a newbie using django and i have a problem that cannot solve.
In my createview i need to select from the dropdown the object car that has the field is_active = true,
how can i acomplish that?
class Car(models.Model):
brand = models.charfield(...)
is_active= models.BooleanField(default=True)
class Service(models.Model):
car = models.ForeingKey('Car'....)
name = models.Charfield()
class ServiceCreateView(CreateView):
model = Service
form = ServiceForm
...
If i change the field is_active to false in Car model, should not be shown in the dropdown.
can someone put me in the right direction?
Why would the CSRF token need to be signed, if it were altered it would just be invalid anyways right? From https://flask-wtf.readthedocs.io/en/stable/csrf.html
Hello
So I use django for my backend
and React-js for my frontend
this is my react-js component. I want to insert the user's username and some other properties of user into it. How can I get this information from the backend?
import React, { Component } from 'react';
import '../../css/app_style.css';
class StatusBar extends Component {
render() {
return (
<div class="status-bar">
<div class="status-container">
<div class="label-container">
<label class="username">Test Username</label>
<label class="personal-name">User's real name</label>
</div>
<img src='staticfiles/assets/users/default.jpg' class="user-avatar"></img>
</div>
<div class="config-container">
<button type="button" class="logout-button"><i class="fa fa-sign-out"></i></button>
<button class="settings-button"><i class="fa fa-gear"></i></button>
</div>
</div>
);
}
}
export default StatusBar;```
pls ping me when help
thanks!
@twilit needle develop a RESTful API on backend which is consumed by your frontend
then use axios/fetch to hit the endpoint, get results, and show them
How can I "git pull" an old github commit
git checkout [revision].
Boys is there any convention on how many fields a django model should have?
Boys is there any convention on how many fields a django model should have?
@halcyon lion i think no
Should I have my virtual environment inside or outside of my repository?
depends what u are using 😄
some libraries can give you problems due to difference based on the OS ppl are suing
using*
I made a site with python, a very small one for testing from my pc, can I connect from my mobile phone or some other device, why can't I connect?
@urban ferry Where is this site running?
in my pc
with DRF whenever you want to update the information of an object within a database, would you still use a serializer? I am finding myself just doing it manually when I only want to update 1/2 fields of an object. Is this okay?
with DRF whenever you want to update the information of an object within a database, would you still use a serializer? I am finding myself just doing it manually when I only want to update 1/2 fields of an object. Is this okay?
@native tide yes you can use serializers
And what benefit would that give when you want to just update the fields of an object partially?@stable kite
@native tide you can parially update your records through sterilizers in DRF
https://www.django-rest-framework.org/api-guide/serializers/#partial-updates
Django, API, REST, Serializers
I know... but that doesn't really provide any benefit except for running validation and whatnot (all my request validation is done on the frontend too, so that doesn't matter).
@native tide wdym i didn't understand your question
Essentially...
Why should you use serializers VS just using request.data and updating an object?
It's probably just a trivial thought which doesn't matter but I just found myself to not be using serializers, e.g. when deleting objects, or updating a field or two. I would just use request.data
@native tide we use sterilizers because they convert json into Model Objects
so that you don't need to do it manually
I don't think you're understanding what I'm asking, it doesn't matter anyways. Thanks
hi
is this for django ?
class MedarbetarPalListAPIView(generics.ListAPIView):
queryset = Person.objects.filter(quarantine__isnull=True).exclude(first_name__contains='Doktor').order_by(
'first_name')
serializer_class = ListParametricMedarbetarPalSerializer
authentication_classes = (HSAIDAuthentication, TokenAuthentication,)
def get(self, request, format=None):
unit = request.GET.get('unit', None)
group = request.GET.get('group', None)
type_ = request.GET.get('type', None)
work_categories_ = request.GET.get('work_categories', None)
query_ = request.GET.get('query', None)
name_query = self.queryset.objects.all()
print(name_query)
# Construct query with Q objects
q_objects = Q()
# Add the filter if the attribute wasn't specified or it wasn't specified using a star (*)
if query_:
q_objects.add(Q(first_name__icontains=query_), Q.AND)
if type_:
q_objects.add(Q(type=type_), Q.AND)
if unit:
q_objects.add(Q(person_unit__unit=unit), Q.AND)
if group:
q_objects.add(Q(group=group), Q.AND)
if work_categories_:
q_objects.add(Q(person_unit__work_categories=work_categories_), Q.AND)
# Get all threads according to filter
# prefetch and select related for increase DB performance
serializer = self.serializer_class(
self.queryset.select_related('group', 'type').filter(q_objects).order_by('first_name').distinct(),
many=True)
return Response(serializer.data)
im trying to add query serch
combine first_name and last_name in model taken from query just below class
class Person(models.Model):
first_name = models.CharField(max_length=127, blank=True, null=True)
last_name = models.CharField(max_length=127, blank=True, null=True)`
i figured how to add query request ... but not sure how to use it with 2 fields from model
---
if query_:
q_objects.add(Q(first_name__icontains=query_), Q.AND)
It should search by contains with a combine of first_name and last_name
e.x. Lara Croft ... search for "cro" and "la" should show Lara Croft
how to combine fields in views ?
searchset = Person.objects.all() = all objects
filter ?
Hello ?
like say i have a Person her name is Susanna Lindberg
if i search for lindberg susanna it should show up
or if i search for lind sus
I have a question why do you use Python not Javascript
In flask projects do routes go in a different file? Or how is it suppose be structured?
Any examples?
I understand that routes can return template or a html, but what if a route needs to communicate with an API/DB or do some extra work. Where would logic for this go?
what does sqlalchemy.func.coalesce() do?
please , in the official django documentations , there is this code
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output)
how does this join method works? it's a bit weird , a for loop in the iterable
It is a list comprehension, which is a syntax that produces an iterable. The join method works the same as it does with any iterable.
[q.question_text for q in latest_question_list] is a powerful feature that produces a list called a list comp
l = []
for q in latest_question_list:
l.append(q.question_text)
@cosmic aspen
that is whaat it meaaans
its hands down the most useful thing in python imo
yeah , i literally said to myself "Who's the genius behind this sorcery"
theyre even more powerful than that. You can include conditionals in there as well
l = [q.question_text for q in latest_question_list if q.pk % 2 == 0]
You can do list comps inside of list comps, if your iterable is also a list comp. There are also dict comps
Its kind of a breakthrough in assembling the data you need when you realize its a thing
How could I practice/learn deployment?
you can create web apps and deploy them on Heroku
Alright
In addition to heroku, you can also spin up VM servers locally if you have a computer that can handle thata. It wont allow you to easily put the sites online, but... it will teach you to configure a production server with all the things needed for it to work.
And... you can use it as a local network server more easily at that point.
Deployment is a LARGE term
to a VM?
to baremetal?
to kubernetes?
to swarm?
then, dev, staging, or prod?
do you want to do pipelines with ci/cd, do you want to sftp files, do you want to rsync them?
yeah thats true. They start to call it DevOps at that level of sophistication.
But you got to start with just pushing to a server that either is in production or works the same as one that actually is.
I find rsync to be pretty awesome when working with local VMs
Thats really the only experience i have with devops other than heroku
if you do end up wanting to do local vms, check out proxmox or even just virtualbox
yeah virtualbox is what i use
should be building a proxmox cluster across 6 thinkcenter mini-pcs soon
it's a open source competitor to VMWare/ESXi
Mine are mostly test servers. Ah okay.
so legit vm operating system with all the things you could want
is virtualbox not a fully featured hypervisor?
monitor all your vms, freeze them, copy them, etc
virtualbox is all i know
virtualbox has limitations AND it runs ontop of your OS where ESXi or proxmox ARE the OS
so closer to the metal
I see.
check it out sometime if you want to grow your skills in that dept (managing vms) as you get way more control over the vms, the resources they use, their volumes, etc and is closer to what you'd use professionally
Cool, Ill check it out. My major issue with VMware was that it was proprietary and not accessible when i tried it.
So ill do that next time i need to
they do have a free version you can use to learn, but there are some limitations, but in the homelab world most people recommend proxmox as it is open source and you'll learn the same things
Also, if you don't know about the homelab hobby like I didn't earlier this year .. checkout out r/homelab on reddit sometime. And good luck to your wallet/free time. Haha. 😉
thankfully I got free hardware from work to do some stuff like those 6 thinkcenter pcs, but I've also created a kubernetes 5 node cluster on raspberry pi 4s using a laser cut blade-server chassis.
And now we're not talking about web development so I'll stop
yeah, unfortunately, I dont have the money to run a home server room haha. I like the idea but it seems unrealistic for me.
Is there a way to change path('accounts/', include('django.contrib.auth.urls')), to a different end point when using those generic auth views? For example, I can change that to path('users/', .... but, this doesnt change the fact thaat all the other views loaded in by that include still use 'accounts/'
This is described here https://www.webforefront.com/django/setupdjangousercreation.html
How to set up log in, log out, password change, password reset and user sign up workflow in Django
For now im just going to leave it. I can learn more by not changing things constantly, but I still would like to know.
ah, the way you do it is right there. You just explicity call all of the views insteada of using include
There are tons of Anime API 's but not all them have good documentation
Who can give me a good one
@somber aurora you could probably use something like imdb or some 3rd party api and sort out the database with tags that only have animation
so for ajax how would I make a post request that would fire off a function in my views.py (django) here is what I have so far
$(document).ready(function () {
$(".btn").click(function (event) {
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000/computer/test",
});
});
});
def computerView(request):
context = {'title': 'Computer Stream', 'applications': computerStream.applications}
def test():
print("Hello!")
return render(request, 'pages/computer_view.html', context)
I know this probably isnt near correct since I dont have a url that is localhost/computer/test it is only localhost/computer and I have never seen a function inside of a function before but that is what it looked like in the various stackoverflow posts I have been viewing. so what do I need to change to get that jquery post run the test function? @swift heron if you reply thanks!
css:
.container{
width: 80%;
margin:auto;
border: 5px red solid;
padding:0px;
}
html:
<div class="container">
<div class="box-1">
<h1>Hello There</h1>
<p>
Lorem ipsum dolor sit amet consectetur,
adipisicing elit. Nisi enim nemo
doloremque placeat excepturi quasi natus
maiores inventore nostrum totam.
Saepe nemo ullam iure illo, minus quasi enim
atque porro!
</p>
</div>
</div>
hey this is making it like this.
what I want is make the top and bottom look the same as the left and right side.
how can I do that?
please happen to ping me for an anser
I want it to look like this
@granite loom Check out the padding CSS property
If you set the padding for .box-1 as 1px, it fills the space within container.
@granite loom Check out the padding CSS property
@outer apex but I why was the thing that I was doring not working?
Sorry, padding wasn't quite the full picture. Read up on Margin Collapsing.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
Also certain tags have default margins. H1 and p tags for example.
@swift heron in your AJAX request you could add a header (such as test:1) and then in your function, check for this header, and if it is there, run test()
This is the structure of my folder, home.html is inside the html folder, and I am trying to link style1.css to it.
this is how I am currently doing it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
crossorigin="anonymous" />
<link rel="stylesheet" href="style/style1.css">
but it isn't linking it, does anybody know how I can fix that?
please happen to ping me for an answer
You have to remove the font linking it is incorrect @granite loom
ohh, np i got it
ohh i just did ../style/style1.css
cya
.button {
transition-duration: 0.4s;
}
could someone explain to me what this is doing?
Cause i don't understand
please happen to ping me for an answer
@granite loom that the transition will have a duration of 0.4s
oh thx
anyone know any good tutorials for gRPC in python?
I wish to experiment with APIs using gRPC, but I want to make sure I have a solid foundation first. All of the tutorials I could find were for Go or Java.
Unless the gRPC functionality is identical to one of the above.
What are some nice css frameworks for a personal website?
Static site
I liked this: https://latex.now.sh/
A minimal, almost class-less CSS library to write modern websites that look like LaTeX documents.
Are there alternatives (not necessarily latex theme but just sort of a minimal css lib
has anyone worked with flask socketio
anyone have any experience with that? I'm abit confused about how eventlet fits into all this, and how the flask server handles sockets
idk but it sounds like you might need to disable mime checking
Is there a way where i can display live database modifications on django without reloading the wrbsite?
@native tide so is a header what is used to specify the function you want to run?
anyone knowledgeable on django/html wanna hop on a voice call. I need some help on how to setup a search funcion 😦
@swift heron no... why do you have a function inside a function anyway? Can't you just seperate the endpoints?
Headers are just part of the request
But in your request you can send JSON
yeah I was just going by an example on stackoverflow I didnt understand it either but this is all new territory
yeah Jquery
So in your request, you can include JSON. Such as {test: true} then in your function, you can see whether test is true (therefore running the 2nd function) or if it's false not running the 2nd function.
It would probably be easier if both of the functions were part of a class, too
@hybrid patio What's the issue?
@halcyon lion Best to do that with JS, I'd recommend React and having some backend APIs
@native tide i am dumb
just had the form name wrong in my view
and it works fine now :d
it says results in bulgarian 😄
okay I think I have an idea of what is happening let me try this one second
Also, what is the point of the view in the first place? You're making a POST request to a regular view, not an API endpoint. Am I missing something?
so here is what I am thinking
$.ajax({
url: '127.0.0.1:8000/computer',
type: 'POST',
json: {test: true}
});
Which when somebody goes to 127.0.0.1:8000/computer
A requrest will be sent to my views function to load that page
def computerView(request):
context = {'title': 'Computer Stream', 'applications': computerStream.applications}
if request['true']:
print("Fired!")
return render(request, 'pages/computer_view.html', context)
But I am checking the request json if the value is true and that is how I communicate from the frontend to the backend?
This example dosent work but is this the general idea?
I am trying to run a function is all
Yes that's the general idea. But it will have to be within an API endpoint, not a regular view.
Also it would be if request.data["test"] == true: in Django
can you show an example of an API endpoint?
nope havent seen this yet
That'll be essential for you to learn if you want to start implementing communication between a seperate frontend and your Django backend
Alright great ill get started on it then
An example API endpoint is similar to a view, they vary, this is a function based view:
@api_view(["POST]) # means this function only handles POST requests
def example_view(request):
if request.data["true"] == 1:
print("fired!")
okay thanks im going to research this more and ill give it a shot you have been a great help thanks!
Hello everyone!
I've been needing some help with a few things and don't really know where else to turn
I've just got a new machine, installed VS Code, Installed Node JS, messed with the settings since the bloody thing couldn't find the python .exe file, got that to work and finally got to the point where I can install django
Problem is, when I activate pipenv (pipenv shell) I don't see that the environment is activated like (environment_name)User@USER in my terminal
I'm attempting to take all the jQuery off of the django install and use VUE instead, in order to do that I needed to do some bollocks npm install vue or whatever
I have models.TextField() in my model but I want that only few characters to be seen in my browser, how can I achieve that? Django
@native tide so reading through this documentation and watching videos it seems we are taking the data and putting it into a model (fancy class) and from there we serialize that data to a database? from this point our frontend can get/post data to that database and our backend can work with the database? is that the basic idea or am I spitting out nonsense?
I’m trying to make a server that serves a static html file using django.
Is there any way I can just send that file without dealing with templates and stuff?
you could host it as a static file, similar to an image, and send it from the view using whitenoise.
don't think the builtin staticfiles can serve in deployment
@prisma jackal {{ value|truncatechars:7 }}
I am working with flask jwt extended and have a login route that looks like this:
@app.route('/Login', methods=['POST'])
def login():
try:
user = get_user_from_db(request.json['email'])
password_correct = check_password_match(request.json['password'], user.password)
if password_correct:
access_token = create_access_token(identity=request.json['email'])
refresh_token = create_refresh_token(identity=request.json['email'])
resp = jsonify({'login': True})
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp, 200
and a refresh route that looks like this:
@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
current_user = get_jwt_identity()
return jsonify(access_token_cookie=create_access_token(identity=current_user)), 200
But, I get a Missing CSRF token message
app.config['SECRET_KEY'] = os.getenv('JWT_KEY')
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
app.config['JWT_CSRF_IN_COOKIES'] = True
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(seconds=10)
I set my CSRF in cookies true
I checked my cookies to make sure they exist
cloritexcalcium
Anyone know a library for working with microsoft's oauth2
@swift heron that's correct!
Serializers translate the request data (from JSON to Python), which can then be saved to represent an object in the database.
A ModelSerializer serializer tries to replicate the model that it is linked to. I'd recommend using that.
okay great, just working on having jquery grab that data now but I havent looked to much into it yet
@night atlas There are good resources online. Just follow the tutorials for a couple of projects and you will be good to go. I actually prefer books, but the content can be daunting. So tutorials is a good way to go about it. Deciding on which library you want to learn is a harder task. I started from tkinter and moved on to pygame. There's pyqt5, wxpython and many more. Also, try out your own projects once you finish the tutorials. This will be the fun part!
@shell heath Do you know about python turtle ?
I haven't used it explicitly, but I know it.
@sonic cedar But haven't touched turtle since I learnt pygame.
@shell heathCan I speak with you in private?
@sonic cedar Sure
@shell heath so what should i mastering first? the GUI one or the basic one first
any python web developer here? I need to ask some question...
not about coding, pls dm me if there is a Python web dev

@night atlas If you know basics of coding, you can jump to gui to solidify your fundamentals. If not go over the begginer tutorials and try to master the basics first. Python Crash Course is an excellent book to start with basics and small scale projects
can anyone help me with a question?
Q: I want to learn pyhton web develeopement, so do i need to learn HTML, CSS, JAVA for web design?
I'm not a web developer by any means, but I learnt a bit of html and css before jumping into django. So yea, knowledge is never harmful
Yeah i know html css
but do i need to learn it advanced?
or when i work someone will do that for me?
Q: I want to learn pyhton web develeopement, so do i need to learn HTML, CSS, JAVA for web design?
@shy finch yeah if u want to work in frontend
but do i need to learn it advanced?
@shy finch or if u dont want learn advance u can learn there frameworks like bootstrap
Does anyone knows about django querys? I know that this one is easy but I'm so bad at it 😦 https://stackoverflow.com/questions/64861260/query-in-query-in-django/64861969#64861969
@swift heron Idk how it is with Jquery, but making requests from JS is really simple with axios and it's promise-based.
@primal kernel It looks like you're going to need to connect your models, right? Possibly set up a one-to-many relationship between "Courses" and your other models so you can access them directly.
They are connected, every consumption is related with a client and a course
@prisma jackal you can set a max-length to the textfield
Oh I see
So your course only has one field, its name, what attribute determines the number of courses sold?
Every consumption has a course associated, what I want is get the best selling courses, like: Course 1 1020 sold, Course 2 992 sold and so on
Like 1020 consumptions has that course associated
I think I could do it in 2 steps but I dont think that's the most elegant way to do it
Is "Consumptions" the orders of the course?
yeah
Could you do: (just paraphrasing)
courses = Consumption.objects.filter(course) # This gets you the list of courses
# Loop through the courses and sort by 10 most occuring.```
FLASK ?? someone to help me ??
You could setup a "amount_sold" or similar in the course model
and that would make it much easier
@hybrid patio Ask the question instead of asking to ask
ok but I have problem with templates
Yeah I could do that, i could get what I want in 2 steps
But thats not the best way
Anyway @native tide thank you so much for helping me, I think that I will do it in 2 stems till I get the knowledge to do it in a different way
{% extends "_main.html" %}
{% block title %} Article {{ id }} {% endblock %}
{% block body %}
<h2>{{ value.title }}</h2>
<p>{{ value.content }}</p>
{% endblock %}
article file
Yeah looping through the queryset isn't a good option, but ideally you would add a new column to the 'Course' model such as orders , and you can use decorators such as @post_save to increase the orders every time a Consumption is added. Then you can simply and quickly sort it.@primal kernel
Or add the order_numer to the Consumptions model and do the same.
@hybrid patio Show us the view
view? what do you mean?
wait
and that is being passed from the view (or the function if you will)
@shy finch or if u dont want learn advance u can learn there frameworks like bootstrap
@placid vale Bro I am trying to learn DJANGO so do i need to learn HTML, CSS, JS, etc?
{% extends "_main.html" %}
{% block title %} articles {% endblock %}
{% block body %} This page uses for something ... {% endblock %}
{% block foot %}
{% if articles %}
<ul>
{% for id, value in articles %}
<li>
<h2>{{ value.title }}</h2>
<p>{{ value.content }}</p>
</li>
{% endfor %}
</ul>
{% else %}
<p>No articles</p>
{% endif %}
{% endblock %}
vaule is define in loop
this is another file
from flask import render_template
from flask import Flask
from .data_base import articless
app = Flask(__name__)
@app.route("/")
def welcome_page():
return render_template("index.html")
@app.route("/admin/")
def admin():
return render_template("admin.html")
@app.route("/about/")
def about():
return render_template("about.html")
@app.route("/articles/")
def articles():
return render_template("articles.html", articles=articless.items())
@app.route("/articles/<int:art_id>")
def article(art_id):
article = articless[art_id]
return render_template("article.html", article=article)
{% extends "_main.html" %}
{% block title %} Article {{ id }} {% endblock %}
{% block body %}
<h2>{{ value.title }}</h2>
<p>{{ value.content }}</p>
{% endblock %}
But here it isn't
Yes I take from articles.html
@shy finch For a simple project all you need is HTML
@native tide Thanks bro but what about advanced project?
@hybrid patio Which function is linked to this code snippet, which one is rendering this:
{% extends "_main.html" %}
{% block title %} Article {{ id }} {% endblock %}
{% block body %}
<h2>{{ value.title }}</h2>
<p>{{ value.content }}</p>
{% endblock %}```
@app.route("/articles/<int:art_id>")
def article(art_id):
article = articless[art_id]
return render_template("article.html", article=article)
this one
nono
this is articles
and template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href={{url_for("static", filename="css/main.css")}}>
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<header>
<h1><a href="{{ url_for("welcome_page") }}">Tomas Balbinder</a></h1>
</header>
<nav>
<ul class="nav">
<li><a href="{{ url_for("admin") }}">Admin</a></li>
<li><a href="{{ url_for("about") }}">About me</a></li>
<li><a href="{{ url_for("articles") }}">Articles</a></li>
</ul>
</nav>
{% block body %} {% endblock %}
<foot>
{% block foot%} {% endblock %}
</foot>
</body>
</html>
articless = {
1: {
"title": "HELLO WORLD!",
"content" : "This is a article about..."
},
2: {
"title": "HELLO WORLD!",
"content": "This is a article about..."
},
3: {
"title": "HELLO WORLD!",
"content" : "This is a article about..."
},
}
and articless in articles
and I would like to show one article when i write url /1
so it would be
{% extends "_main.html" %}
{% block title %} Article {{ id }} {% endblock %}
{% block body %}
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
{% endblock %}
and you'd pass ID too
@shy finch For an advanced project sure, but if you have never used Django or JS or HTML why think about an advanced project
Idk what you're saying
@native tide just wanted to know
WOW
works
how it is possible?
{% extends "_main.html" %}
{% block title %} Article {{ article.title }} {% endblock %}
{% block body %}
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
{% endblock %}
@native tide i am learning Django so it popped in my mind
why article?
Because if you looked at your error... it literally says value is undefined
You are not passing a value to your HTML page, you are passing article
I know
def article(art_id):
article = articless[art_id]
return render_template("article.html", article=article)```
Look at the render_template, you are passing article=article to the HTML page
ah 😄
and article is in the form {"title": x, "content":y}
ok than you so much
👍
@shy finch If you want to learn a JS framework I'd recommend React
But save that for when you get to grips with Django
@native tide look
@shy finch If you want to learn a JS framework I'd recommend React
@native tide Thanks bro for letting me know..
@app.route("/articles/<int:art_id>")
def article(art_id):
article = articless[art_id]
return render_template("article.html", fuck=article)
yes work
s
why ping me for that...
I wanted to convice my self it works
How can I serializers (using django rest api) two models like
class A(models.Model):
name=Textfiled()
class B(models.Model):
book=Textfield()
name=Foreignkey(A)
startDate=Datetime()
endDate=Datetime()
this, so that I can create an api which gives json response like
{
"name":"tet",
"books":[
{
"book":"test",
"startDate":"2020-12-6",
"endDate":null
}
]
}
I want to understand how can I write serializers for these two models?
Guys, sorry if I'm wrong category in case you notify me and change.
I need to be able to assign this underlined value to a variable. However, this "content" text changes with each link, so the program must be able to fetch it every time
Can anyone help me?
@static harbor You can use DRF's modelSerializer
I'd recommend looking at the docs for that module
Then ask any questions if you don't understand something
Hello again >D
I have problem with alight center in CSS
so how can I get this to html tag?
<.nav> ??
Remove the .
nono
look
body {
padding: 0 20%;
}
header {
text-align: center;
}
.nav {
padding: 0;
list-style: none;
overflow: hidden;
text-align: center;
}
.nav li {
display: inline;
}
.nav a {
display: inline-block;
padding: 10px;
text-decoration: none;
}
footer {
text-align: center;
}
I need use something for this
but what is .nav??
using . represents a class name
If in the HTML I had a div with class example, in the CSS doing .example would target that div
I need center other text but i dont have enought css tags
Try justify-content: center
can session variables be changed from the client? So when i save a email or something to save the account a user logged in, can i be sure he can't change that?
then just ask the question and dont just say that you have one?
ok without answer
I want to know that I can watch the web as much as I want through Python
just..not seing
@hybrid patio Yes you can. Go on W3 to get a rundown of how CSS works
@round wave If the session ID is stored in the cookie, yes. They can change it.
umm..
so whats the best way to save in what account a player is logged in?
maybe save a hash of the password too?
save a list?
@round wave save a hash of the password where? as a cookie?
Session auth will work fine. If the user changes the session token to one that does not match with the account, they should be logged out.
im new with web developement, so can i just save the email now?
wdym by save the email?
if you're using Django and don't have a seperate frontend use session auth, it'll do it all for you
im using flask
Well flask should have a library which solves that for you
do you know the name?
A simple google search would get it for you. I haven't used Flask in some time
If you follow a signup/login tutorial for flask they'll probably cover it too
if anyone here ever used flask_restful/flask_restplus/flask_restx, what's the proper way to implement pagination and filtering on API resources?
How i can make Web Dashboard for discord.py Bot
Make API endpoints w/ Flask or Django
When I try to start gunicorn with "sudo systemctl start gunicorn" I get the error: "A dependency job for gunicorn.service failed. See 'journalctl -xe' for details."
did you check the details?
When I use that command for details it tells me: No journal files were found
hi .. I m new to Django framework and i m trying to make a Data table which should having fowling function , like filtering data with group by using Django Query set ....so if you having any resource regarding this Django query set please let me no thankyou
In django, how would you make dynamically added links
like with hastebin, where you get a link for every new document
I dont know what I should google for
@vapid acorn In your URLs you can have path('site/example/<id_of_something>/)
oh ok
Hey I am trying to setup Django REST Serialization, but for some reason the page is not found
Like a url that starts with api is is not recognized
path('login/', views.LoginView.as_view(), name='login'),
path('profile/', views.ProfileView.as_view(), name='profile-view', ),
path('plan/<int:pk>/', views.PlanView.as_view(), name='plan-view'),
path('create-plan/', views.CreatePlanView.as_view(), name='create-plan-view'),
path('logout/', views.LogoutView.as_view(), name='logout'),
path('auto_setup/', views.AutoPlanView.as_view(), name='auto-plan'),
path('edit_user/', views.EditProfileView.as_view(), name='edit-user'),
path('register/', views.RegisterView.as_view(), name='register'),
# REST Framework URLS
path('api/plan/', include('users.api.urls', 'plans_api'))
]
users/urls.py
app_name = 'users'
urlpatterns = [
path('<slug>', api_detail_plan_view, name='detail')
]
I have found my mistake, I needed to use users prefix as in my main app the prefix for users is users
In what case would I use serialization?
and api views
please any recommendations? I have problem recieving socket on server side created in flask-socketio
- I have client side in react native mobile app https://imgur.com/a/gpvxrox
- server running on raspberry pi trough flask-socketio
- I succesfully connect to server
- than after clicking on buttons I try to send socket socketio.emit 'data'
- in flask I have socketio.on 'data' print socket was connected but for some reason Im not getting that message
any recommendations?
my connectionscreen:https://pastebin.com/2W0cVrkc
main screen where I click buttons and send sockets: https://pastebin.com/WhQv1VbQ
simple flask-socketio server: https://pastebin.com/Uc50hxCz
Im trying to confirm recieving socket with print socket was connected on server side but it doesnt work, any recommendations please?
Please help, i need to obtain two values from a single checkbox. In a case below, i need to get food_name and price when a user check the box. Here's my code:
class Food(models.Model):
food_name = models.CharField(max_length=50)
food_image = models.ImageField(blank=True, null=True)
price = models.IntegerField()
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
slug = models.SlugField()
**views.py**
def menu(request):
Product = request.POST.getlist('food')
# here's where i need to get the values
food_list = Food.objects.all()
args = {
'food_list':food_list
}
return render(request, template_name='menu.html', context=args)
menu.html
{% for food in food_list %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<tr>
<td>{{ food.food_name }}</td>
<td>{{ food.price }}</td>
<td><input type="checkbox" name="food" value="{{ food.price && food.food_name }}"></td>
#Here's my checkbox with the two values i need
{% endfor %}
<button type="submit">Order Now</button>
</form>
Pardon my poor code-arrangement here on the discord
hello, i was looking to make a website. i don't wanna say too much of what it is exactly but it's gonna basically be a voice chat like chatroulette or similar
i had my eye on flask or cherrypy
but i honestly don't know anything on either
or python web frameworks in general
if anyone had any suggestions or tips, it would be much appreciated
what is the recommended fastest way to get the output of a python script displayed on a webpage? i am building an app that will only ever be run locally but i would like some qol UX features and figured a webpage would be the most convenient way. django seems like overkill and im unable to find a flask tutorial that simply outlines how to achieve my goal?
like, i just want to turn a python dict into some text on a webpage
well, you prob def want to use Flask
and Django is 100% overkill
what are you using for your Front-End @native tide
im fine using basic html/css for now
it's just a series of scripts that im running locally for myself
any framework seems like overkill tbh. i feel like im better off just exporting to csv or something else if i don't want to stare at the cli all day
also ty for the response
i mean; tahts True lol
but at least with Flask, you could just configure a simple end-point and have your Front-end smack that endpoint for the data
yeah
up to you; can be tackled all kinds of diff ways and you prob don't need a web-framework to do it
im functionally new to python so i feel like it's just too much to learn at once. i'd rather just focus on getting my scripts to do what i want rather than take on a web framework
yeah
thank you
helps to talk through it
Check out Tech With Tim's Flask Tutorial on YouTube
It explains how to use Flask
But I will include an example to do just what you want to do:
Hey has anyone ever had problems with css media queries not updating a web page when the mobile device orientation changes?
I'm having some problems with this, and I haven't found a solution after searching for some time on Google.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
dict = {"What is this?": "A dictionary", "Why is this here?": "It's an example"}
return render_template("index.html", dict=dict)
app.run()
index.html
<html>
<!-- Add some boilerplate here to get all the <head> tags -->
<body>
<p>{{dict}}</p>
</body>
</html>
@native tide ^
@topaz widget I've had that problem too, but I sadly don't know a solution
You could do some complex styling to the dictionary to get it in a table and etc., just remember that anything inside {{here}} is a reference to Python, so you can use Python code in there.
For example: {{dict["What is this?"]}} will just display A dictionary
that's perfect
More complex templating syntax (such as for loops and if statements - within your HTML code) are available... check out jinja2 if you want to learn more
I've had that problem too, but I sadly don't know a solution
@chrome onyx Well, thanks for the response. It's really strange. So much for the page being responsive.
Okay I am just learning on how to do post/get requests to the django database and when I run my page I am getting Forbidden (CSRF token missing or incorrect.)
Is there a way I can disable CSRF tokens for the moment until I can actually get Post/Get requests working? if anyone has a reply please @swift heron Thanks!
just say what's the issue dude
Is there any possible way to remove this info from djangos signup form? coz it's destroying my layout.
OK I try to use include
but my page doesnt works
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %} {% endblock %}</title>
{% include "_head.html"}
</head>
<body>
<header>
<h1><a href="{{ url_for("welcome_page") }}">Tomas Balbinder</a></h1>
</header>
<nav>
<ul class="nav">
<li><a href="{{ url_for("admin") }}">Admin</a></li>
<li><a href="{{ url_for("about") }}">About me</a></li>
<li><a href="{{ url_for("articles") }}">Articles</a></li>
</ul>
</nav>
<main>
{% block main %} {% endblock %}
</main>
{% block body %} {% endblock %}
<footer>
<p> (c) 2020 Tomas Balbinder</p>
</footer>
</body>
</html>
in head ... look
this is _head page
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href={{url_for("static", filename="css/main.css")}}>
error
@hybrid patio {% include "_head.html"} it is supposed to be {% include "_head.html"%} u just forgot the % sign at the end
I figured it out for testing when working with a class you need to use the following
@method_decorator(csrf_exempt, name='dispatch')
Hey, I'd like to create a basic online form to feed variables for my python program, what would be the fastest way to do so ? (Idc about fancy graphics) - I cannot use Streamlit as its work related and streamlit doesnt work with IE
As we'd alluded to above, sending form data is easy, but securing an application can be tricky. Just remember that a front-end developer is not the one who should define the security model of the data.It's possible to perform client-side form validation, but the server can't t...
oh sorry, you said online form
{% extends "_main.html" %}
{% block title %} Welcome Tomas pages {% endblock %}
{% block body %} Tohle je zkušební stránka Tomáše Balbindera.{% endblock %}
Oh tank you I am ... idiot >D
For some reason if statements in django work half the time
{% if owner.userid == user.id or user.staff == True %}
This is what im doing and the current user is not the owner but is staff, but what its supposed to do when staff is true, is not happening
Why don't u just put {% if user.staff %}, i suppose owner is staff as well.
@verbal snow
than instead doing {% if owner.userid == user.id or ... %} do {% if user.id == owner.userid or ... %}
Didn't change anything
It's like django can't parse anything
It'll parse half the statement in some cases
are u properly refering to an object?
I am indeed
no idea then
I dunno if my question ever got answered or not
But I've been having issues getting NodeJS and NPM to work well with my django project
I literally just want to use NPM to install stupid VueJS
I installed NodeJS and it literally broke VS Code
Any recommendations what am I doing wrong? I connect to server and try to send socket with socket.emit
BUT for some reason my server doesnt recieve socket, or it seems it doesnt because it wont print socket was connected
this is my client:https://pastebin.com/WhQv1VbQ
this is my server: https://pastebin.com/Uc50hxCz
I'm down for DMs/Side convos for someone who can just help me get setup so I don't have to fiddle for another 4 hours with trying to make sure everything works
In Django, why should I make a custom user model inheriting from AbstractUser? why cant i just get it from the AUTH_USER_MODEL thing? (im not 100% sure about the names here)
There should be one obvious way to do things, and inheriting from abstractuser to make your own custom one does not make a lot of sense to me.
I would love some insight into this?
for the record, I am using AbstractUser in my custom user model, but I wonder why.
@sturdy sapphire Iirc AUTH_USER_MODEL (by default is django.contrib.auth.models.User) has it's own attributes and methods such as is_authenticated, which other parts of Django will leverage. So, if you create your own model overriding this, some parts of Django won't work with your model (such as authentication).
https://docs.djangoproject.com/en/3.1/ref/contrib/auth/
So by inheriting from AbstractUser you keep all of the attributes / methods of Django's User model, and you essentially just add some custom data fields.
right, that makes sense. thanks @native tide
@verbal snow You said that the user is staff? So this will always run as it's truthy
{% if owner.userid == user.id or user.staff == True %}
right?
Yea but it wasn't showing what it should've. I got it tho
@native tide Hello just a quick question I did get post request to work so I can send data from the frontend to the backend how would I go about sending data from the backend to the frontend without reloading the page? say an additional model is loaded into the database after the page is loaded how can I get that info to javascript and then added to the frontend?
@swift heron your endpoint can return a Response, you'll have to import it, can't remember off the top off my head
And that will return JS which your frontend can handle
alright awesome will look into it, thanks again!
Django, API, REST, Responses
Also import status (which returns the status of the request back to the frontend, such as 200 (OK) or 404 (not found)
Django, API, REST, Status codes
An example would be this for your API endpoint
# import Response, status
def example_endpoint(request):
# do something with the request
data = {"success": "request was successful"} # the data you want to return to your frontend
return Response(data=data, status=status.200_OK) # specify data=<data you want to return> and status=<status you want to return>
Then in your frontend you can access the returned data
I'm using the erorr page example on the django site
def response_error_handler(request, exception=None):
return HttpResponse('Error handler content', status=404)
def permission_denied_view(request):
raise PermissionDenied
handler404 = response_error_handler
``` but it still renders the regular one
I'd recommend axios for the requests
Alright thanks Ill be trying that out after a short break 👍
Currently at the moment on django I am using generic class based views to CRUD my tables from the database. If I want to view them all on a homepage, should I still use class based views for that?
Currently using list view to view info
Maybe switch to FBV for what I’m trying to do
!pban @acoustic zealot spamming insults
:ok_hand: applied ban to @acoustic zealot permanently.
soup = BeautifulSoup(page.content, 'html.parser')
tree = soup.find('span', {'class': 'indexName'})
print(tree.next_sibling)
# None
is class=indexName not a sibling to class=indexValue or am I missing something?
Hi, I'm a total newb. I have a server that I'm renting. I'm looking for a tutorial on how to use python on my server to do things like respond to a POST request
The simpler the better. I'm only trying to do the most basic things.
@half vale Use a framework like Flask.
Django works, too, but is typically for more complicated stuff.
Flask is easier to get started with from what I understand.
@visual lake it is a sibling, are you sure that the class indexName is used only once on that page though? You might be getting a different element on accident
yea you're right the first one on the page actually doesn't have a sibling @indigo kettle
so you'll have to find a different way to access that element, maybe first finding a parent and then finding that class name afterwards
I can get to "DJ Italy" which is a child of indexName which inturn is a sibling of indexValue
would that work?
nevermind, thanks for the help @indigo kettle
oop, sorry. Np!
@topaz widget I don't really understand how to use Flask on a remote server. Do you know a good place for me to learn?
Learn on your local computer. I think Flask probably has a built-in local server. When you feel comfortable with your app, then transfer it over to your remote server and configure the server to run your Flask app. @half vale
I already understand how to program from my local computer. I'm looking for resources on how to do it remotely.
Corey Schafer has some tutorials on YouTube for Django. He might have some on deployment for Flask, too. I know he has Flask tutorials, just not sure if they cover deployment.
Do you have some server software like Apache or NGINX installed? You'll probably need that too unless you're using some pre-configured solution.
I have a server up and running. There's a terminal I can get to from cpanel. That's pretty much all I know.
I published a sample site and then replaced it with my own html and js files. But I don't know how to code actual server side code.
I will check out Corey Schafer.
Yeah, getting a server set up properly can be somewhat involved, but for simple stuff, there are ways to make it easier like Heroku. I'd recommend looking at Corey Schafer first. He's pretty good at explaining things that can be somewhat complicated.
I like the host that I have I just don't understand how to set up a server honestly. Or how to change one that's already been set up.
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 ...
Thank you.
I haven't used sqlalchemy but have used django often
I can try to help. Is it important to have referred_by and referred_to fields?
is the referred_to, not somehow related to referred_by
I think I understand
I think the issue is that you have multiple backrefs with the same name to the same model
dest_address = db.relationship('Address', backref='orders', lazy='select')
from_address = db.relationship('Address', backref='orders', lazy='select')
status = db.Column(db.String(MaxLengths.order_status), nullable=False, default="Pending")
products = db.relationship('Product', backref='orders', lazy='select')
subtotal = db.Column(db.Float(), nullable=False)
shipping_fee = db.Column(db.Float(), nullable=False)
tax_cost = db.Column(db.Float(), nullable=False)
total = db.Column(db.Float(), nullable=False)
discount_code = db.relationship('DiscountCode', backref='orders', uselist=False, lazy='select')
here you have 3 backref='orders'
I think these will have to be unique or else there will be no way to access them
actually, the discountcode should be fine
but the other two are both coming from Address
so those will have to be unique
you also have 2 reviews fields on the Product model
I'm not sure exactly how this works but for the referred_by thing I was asking about, I think this is the right time to use backref because referred_to, and referred_by should be kinds of mirrors of eachother
referred_by = db.relationship('User', backref='referred_to')
idk exactly how it should be written
just a thought
did you run a migration?
one of my first large web apps I wrote was an ecommerce app so this all looks very familiar
fun stuff!
another thing, here on Product
ordered_by = db.relationship('User', backref='product', lazy='select')
orders = db.relationship('Orders', backref='product', lazy='select')
you have ordered_by as a field, but users has a relation on the order, so you can access users through the order model
hm, I feel like it should be accessible without writing it again like this. But I don't know exactly what sqlalchemy is doing so I'm probably wrong
haha
yeah, you'll bang your head against a wall for a while before it all makes sense
I am trying to create a Flask application, however, my extend title isn't working. It was working in a different IDE, but I cannot use that one anymore.
My layout.html:
<head>
<title>{% block title %}{% endblock %} - My Webpage</title>
...
My index page (only one):
{% extends "layout.html" %}
{% block title %} Index {% endblock %}
{% block main %}
test
{% endblock %}
Any help would be appreciated. Thanks in advance!
^^ what it looks like now
It also appears that all other blocks do not work too
@native tide It's not obvious from what you posted what the problem is, and as bri said, changing your IDE shouldn't make any difference unless it's a tabs vs. spaces issue in your Python code. This does not seem like a Python issue, though.
wtf
Hey guys...I can't seem to get rid of this problem in django
I've installed Django in both the venv and on the system
But this problem still persists
I tried to delete the workspace and create a new one but still can't seem to get rid of this
Hey guys after deploying my django website how is it possible to access my django admin ui?
Hey guys after deploying my django website how is it possible to access my django admin ui?
@unborn mural Go to the/adminurl and enter your superuser credentials. If you have not created a superuser, the command to create one should bepython3 manage.py createsuperuserfrom the root directory of your Django site (the directory with yourmanage.pyfile in it).
no nooo
tht one is okayy
but like let's say i create a simple blog application
and then deploy it
Same deal
if i need tp create , edit or delete my db
then how do i access my admin of already deployed website
There are a number of commands to interact with your db.
I'm not exactly sure what you're trying to do.
I'm not exactly sure what you're trying to do.
@topaz widget bro there's this django admin ui ryt
how do i access tht after i deploy my website
are you talking about the admin page?
yes
Should be the same url
@topaz widget then anyone would be able to access it ryt
If they can guess your credentials, yes.
Django recommends changing the admin login page url to something only you know.
You can do that in your root url conf if you think you need the security.
(urls.py)
The default url is admin/
@unborn mural Make sure you register all your models in your admin page, too. Should be done in something like an admin.py file in each app.
yess okay
Quick question: free places to learn JS for WebDevs?
Any ideas why this error?
django.db.utils.OperationalError: (-1, 'MySQL Connection not available.', None)
I'm using mysql-connector-python and a remote DB
Oh btw, this happens when I try to create a super user only
@tranquil idol https://www.w3schools.com/js/DEFAULT.asp
@rapid bramble you said you have remote DB right? can you connect to the database? the error probably from timeout timer exceed when connect to the DB
try running in shell with python manage.py shell
and
import django
print(django.db.connection.ensure_connection())
if it return None then the connection is ok, else it will print out the error
I'm able to connect to the database remotely yes, and that is pretty obvious considering that error occurs only during super user creation and rest of the connections - login signup and other stuff involving dB is fine.
But I'll try the second portion of it when I'm back on the PC.
Also, it occurs randomly, like if I set CONN_MAX_AGE to 36000 sometimes it works and sometimes it doesn't
Pretty weird
Just put your problem here
Sure
I was practicing recursion
I wrote this code and the output should return "Babe Hi" but it is returning "ebaB iH"
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = "Hi Babe"
print(reverse(a))
@pulsar hinge
I don't think it's a problem for web dev, use channel for it but python is going thru a single letter not words
um, okay
https://www.geeksforgeeks.org/reverse-words-given-string-python/
Just to help you somehow. First of all, always try to look at google, coz recursion is pretty popular topic
I have tried this code of geeks. They are reversing the characters. I want to reverse the order of the words
No, they are putting last words at the beginning.
Input : str = "geeks quiz practice code"
Output : str = "code practice quiz geeks"
I see, thanks.
hello, this is a pre-development question, to clarify if my idea could workout - when i choose heroku as host for my little webapp i need to store the code that drives the app in a git(hub) repository and the data in a postgresql database, is that correct so far?
🚫
thats all you gonna give?
@native tide your code will be stored in both github and the heroku server in order to run, you would also need to set up your database on the server though
What woild be the use case if serialization?
@limber laurel Can you elaborate
Like when would I serialize a view and return it in a json format?
When you want to return data to your frontend
But like why would I want to do it that way?
Let's say that you make a request to your API endpoint with JSON and want to save it to your model... You can serialize it and then save the serialized data. That has advantages because you can add custom serializer validation (which is different to your model).
But if you want to just return some data, serializers just validate that the input is what is expected. For such views I usually don't use serializers (as all of my input validation is on the frontend anyway).
does anyone know how to make css work in django
i mean its working but when i save the page changes arent reflected after refresh
it only works when i restart the server
it worked initially but now it doesnt
sometimes it works sometimes doesnt
@green snow Ctrl + F5
If you check Django development server logs you'll see a 304 on the CSS file, which basically means that the CSS file has been cached by the browser and the latest copy isn't being fetched.
ctrl+f5 works thx @rapid bramble
👍
@app.route("/picture", methods=["GET", "POST"])
def picture():
if request.method == "GET":
return "Getting image\n"
else:
return "None\n"
how request knows what methos it was called?
is there some globals under mask ?
It's just the current request's method from the HTTP request
Was that module created from libcurl?
possibly
@upbeat umbra what module?
requests
can someone explain render and super() ? last sentece
@native monolith rendering is what the computer does when it decides what to display to the user and then displays that. super refers to the class which a certain class inherits or extends.
So if I have an Animal class then a Dog class which inherits properties and functions from Animal class, then I can use super in the Dog class to refer to properties or functions from the Animal class.
I think I got that right :)
in know python super, but is this the same in flask and html?
yes, but that's not html, it's a jinja2 template
ok, but written in html 😄
render in this context pretty much means that it will copy and paste some content
in the place where you called super()
hmmm
so it copies block head from parent and extend it ?
I see
thanks @slender moat
could you also give me short desc what is the difference? {% %} {{ }}
what I understand is that {% %} refers to conetxt, and {{ }} is code
or {%%} is escape for jina, and the other i do not know 😄
just check the docs
{{ }} are expressions and have some kind of output
{%..%} are statements and have no output
np
Hi i need some help regarding libxml12-python, when I tried to install django-dinggo into my project . It keep return the same error. ERROR: No matching distribution found for libxml2-python>=2.6.9 (from django-dingos>=0.1.0->django-mantis-core). When I check in PyPI, the only version is 2.6.9.
Hello, I would like to get User inputs through a very basic online form. What's the best way to do it ? (Streamlit felt amazing but wont work on internet explorer)
anyone with experience getting a pandas dataframe into postgresl?
Ok i am not the best at asking coding questions to be honest but I am trying to show a static file which is an image in my template. I have read a lot of things and i dont know what i am doing wrong. Here is my template code ```
<h1>Portfolio</h1>
{% load static %}
<img href="{% static 'portfolioapp/Placeholder.png' %}">
{% for project in projects %}
<h2>{{ project.title }}</h2>
<img src="{{ project.image.url }}">
<p>{{ project.description }}</p>
<br>
{% if project.url %}
<a href="{{ project.url }}">Link </a>
{% endif %}
{% endfor %}
let me know if there is anything else i need to copy and paste
its django btw
@stark plank do you have changes in settings.py ?
STATIC_URL = '/static/'
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/')
also in urls
@stark plank do you have changes in settings.py ?
@snow sierra yes
@stark plank using browser inspect?
I assume you are asking if the file appears in the network tab and the only thing that appears is my other placeholder image which is from the database and my web page
Ok i am not the best at asking coding questions to be honest but I am trying to show a static file which is an image in my template. I have read a lot of things and i dont know what i am doing wrong. Here is my template code ```
<h1>Portfolio</h1>
{% load static %}
<img href="{% static 'portfolioapp/Placeholder.png' %}">
{% for project in projects %}
<h2>{{ project.title }}</h2>
<img src="{{ project.image.url }}">
<p>{{ project.description }}</p>
<br>
{% if project.url %}
<a href="{{ project.url }}">Link </a>
{% endif %}{% endfor %}
let me know if there is anything else i need to copy and paste
@stark plank it is not enough :x
what should i also show
ok
and folders hierarchy
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from portfolioapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('blog/', include('blog.urls'))
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)```
did you restart server after changes>?
yes
mine works fine .. :/
thats really odd
can you paste HTML source code? where your img is..
i'm not too sure what you mean
Like this i mean...
like what i pasted earlier? This? ```
{% load static %}
<h1>John's Portfolio</h1>
<img href="{% static 'portfolioapp/Placeholder.png' %}">
{% for project in projects %}
<h2>{{ project.title }}</h2>
<img src="{{ project.image.url }}">
<p>{{ project.description }}</p>
<br>
{% if project.url %}
<a href="{{ project.url }}">Link </a>
{% endif %}
{% endfor %}
open web page > right click on image place > inspect
yes, and when you click on link /Placeholder.png what is happening?
nothing
i put it in the url
and the image shows
huh
this is confusing 😅
i fixed it
🙂
i changed href to src
lol yes :d d
thanks for your patience haha
<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
</div>
hey, so where can I find common or most functional classes to use like this topnav? 😄
How can I host static files in my fastapi?
I mean I have folder
pics and I want people to be able to see them
example
http://website.com/pics/1.jpg
@stark plank isnt it convention to name ur media files "media" and add as sub directories whatever u want
Is there a way to force the execution of a parent block before my block?
I inherit a template and jinja keeps putting my block after the parents despite calling super after my block
And idk how to fix it
you should call it before i think, not sure
I want my block executed first
So that it's overwritten should someone pass an option to the parent
I want to call table_styles block from the parent before my default_table_styles block
then call it in this block
How do I call a block from the parent without calling the entire thing?
?
{% block default_table_styles %}
#T_{{uuid}} th {
font-size: 100%;
text-align: center;
background-color: blue;
color: white;
border: black solid thin;
} #T_{{uuid}} td {
font-size: 100%;
text-align: center;
background-color: white;
color: black;
border: black solid thin;
} #T_{{uuid}} th:empty {
border-width: 0;
}
{{ super() }}
{% endblock %}
<!-- {{ super() }} />
you also try using css
instead of formating every row and col
@slender whale did it worked?
Not exactly but you lead me enough to the correct solution
Thank you very much
Pandas has an empty block called before_style and I just shoved my css in that
Outside of table block
I didn't know I could do that
So thank you again @native monolith
does css style link must be in head ?
Yeah
also why css keeps upadting so long?
sometimes i reload page, or even start private brower mode it still remebers old css
What is the best django vote API
another flask and css question, #help-dumpling message
I have a django question
I am looking at a model
and i see an attribute (member associated with it) but i cannot find where that attribute is being initiated
It is being referred to as self.attribute
but attribute was never initialized in the class definition of the model. Where else can attributes be defined?
Hi All, I'm in need of django regroup tag template.
I'm trying to group an image into a specific attributes
@naive oar wdym by that
who use brython ? dm me pls !!
@native tide Here's what I have so far '<div class="row">
<div class="uni-popular-cars-item">
{% regroup detailwheels by wheel_image.wheel as wheel_list %}
{% for wheel in wheel_list %}
<div class="col-md-3 col-sm-6 col-xs-6 col-unisp-12 item new">
<div class="item-img">
<img src="{{ wheel.grouper }}" alt="" class="img-responsive">
<div class="item-img-caption">
</div>
</div>
{% for detwheel in wheel.list %}
<div class="item-info">
<h3><a href="">{{ detwheel.name }}</a></h3>
<div class="uni-divider"></div>
<h4>Model: {{ detwheel.model }}</h4>
<h4>Available Sizes: {{ detwheel.sizes }}</h4>
<h5>Finish: {{ detwheel.finish }}</h5>
</div>
{% endfor %}
</div>
{% endfor %}`
I'm trying to get the image to display here but I'm not seeing anything? ' <img src="{{ wheel.grouper }}" alt="" class="img-responsive">'
Aren't you supposed to do {% url 'static/img' %}?
Wait
I usually do {% load static %} before everything else
So like:
{% load static %} <link rel="stylesheet" type...
Then I put all my HTML underneath it
Here's what I'm trying to do, I want to group the images and only display the model number and sizes and only return 1 image.
I might be missing something
maybe there is something easier that regroup, I'm still new to Django
Same here
Almost seems like it would be easier if you could load the image as a variable and then just call the variable
Or you know.... go the old route and just copy/pasta the same img code
I'm trying to make this dynamic from a csv file, this csv file can have the same image to multiple model numbers
I know how to do it in SQL but I'm trying to do it with Django tags
so I clicked a button and I checked the Network Tab but it shows values like this in the Request Payload.
choices: ["5c52b1f391a06c64660050f8"],
question_id: "5dd34bf75f0ed65e8b31195f",
session_key: "5dd34bf75f0ed65e8b31176RT",
stuff like that so I was wondering how would I get these values because I know whend I send a Post Request in Python then the session key would be different and I wouldnt know the question_id because there would be different questions.
I tried viewing the source of the page to look for the value of one of the keys above but I couldnt find any because if I did then I would just use Web Scraping to find the IDs for the question and choices.
Anyone know how I could format text to the colors of lets say python?
Does anyone know how I can fix this error when trying to connect with a foreign redis server?
[2020-11-19 01:51:54,727: CRITICAL/MainProcess] Unrecoverable error: ModuleNotFoundError("No module named 'redistest-ro'")
I have literally 0 idea on how to fix it
And I cannot find anything related to redistest-ro
same here but i'll try to help u
Same with me? @inland stirrup
i mean i have no idea too
ah alright
I think I figured it out
I had forgot to add redis:// before the server url
ok lol good to hear
for flask when i render webpage with images which one is good practice
use the usual img tag
or
use the url_for to create a field for the image
@naive oar I just found out how to get the question_id it was stored in an HTML element, now my question is how do I get the session_key? I tried checking my cookies
@safe oasis nice, that you can usually find in the network tab, I dont believe that's stored in the html.
@naive oar how? would it be a get request? can you show an example screenshot of what it may look like
@safe oasis this can be done with selenium I believe, its been a while since I've done web scrapping.
This might help you. https://stackoverflow.com/questions/19944745/how-to-get-session-id-on-selenium-webdriver-using-python
I am trying to create a Flask application, however, my extend blocks aren't working
My layout.html:<head> <title>{% block title %}{% endblock %} - My Webpage</title> ...My index page (only one):
{% extends "layout.html" %} {% block title %} Index {% endblock %} {% block main %} test {% endblock %}Any help would be appreciated. Thanks in advance!
I said this yesterday and someone replied with "this shouldn't be a python issue" Any idea what is messing up? Maybe like a Flask setting or something? It seems as if Jinja is just reading the first line and not reading the rest
Hey, I am having trouble accessing a flask app outside of a docker container.
More info: https://stackoverflow.com/questions/64904750/dockerized-flask-app-is-not-accessible-in-localhost
Hey, I want to preload some data on one of my webpages, I dont want to use a dataframe however because that slows down the server a lot if their is traffic.
I was wondering, if a dictionary of dataframes solves the above?
instead of one giant DF, allow for a dictionary of an estimated 900 Dataframes?
If one dataframe slows down your server how would 900 dataframes make it faster? @glass badger
The differences is the dataframe would be parsed, and if a user wanted to look for an item located in my dataframe, they wouldnt have to look through 100,000 rows
Instead they would locate the key index
making it much faster
I said this yesterday and someone replied with "this shouldn't be a python issue" Any idea what is messing up? Maybe like a Flask setting or something? It seems as if Jinja is just reading the first line and not reading the rest
@native tide technically this should work ...is your file structure proper
What do you mean by that?
The differences is the dataframe would be parsed, and if a user wanted to look for an item located in my dataframe, they wouldnt have to look through 100,000 rows
@glass badger I am not sure what you mean
If that's the case why not have a local db with all the dataframes and then just a route that the user can make requests to
That would be the fastest
i mean all the html files should be in templates folder and all other python files should be in a level above the template directory @native tide
@rustic pebble to my understanding, doing a "look-up" on multiple rows is always much more extensive then not having to look through rows if they dont have too
Play with a dictionary of dataframes and you will see what i mean in terms of speed. However I don't know about the RAM issues with a dictionary
which is why I ask 🙂
That is what they are at. https://xenophoxic.is-a-virg.in/3c9Jzc
I think that is what you mean
@rustic pebble I have a dB that I write queries too, not sure if thats what you meant.
You can load the dict you are talking about in the server memory, assign a unique id to each one of them or something to identify them and then you can create a route like this:
@app.route('/get-df/<df_id>', methods=['GET'])
def get_df(df_id):
return {'data': dataframe_dict[df_id]}
@native tide dm me like the whole file ....
are u in a venv?
wait that shouldnt matter
You can load the dict you are talking about in the server memory, assign a unique id to each one of them or something to identify them and then you can create a route like this:
@app.route('/get-df/<df_id>', methods=['GET']) def get_df(df_id): return {'data': dataframe_dict[df_id]}
@rustic pebble interesting
Did you understand what I am saying?
Yes I do, thank you for the example. So would the server calls be made client side?
@rustic pebble
Yup, a really simple fetch api
This method would really make your load times faster since all you would need to do is get the keys
I have a question, would this be a similar networking to a rest api?
So you would have something like this:
@app.route('/')
def home():
return render_template('index.html', dataframe_keys=dataframe_dict.keys())
Now you would have to iterate through the dataframe_keys list to fill the frontend using Jinja2 server-side rendering. Now if you want to make a client-side request you can do the following:
async function get_dataframe_data(dataframe_id){
let url = "/get-df" + dataframe_id;
const resp = await fetch(url, {method: 'GET'});
const dataframe = await resp.json().data //or await resp.json()['data'] JSON can be accessed either as an object or as a dict
return dataframe
@glass badger
I have a question, would this be a similar networking to a rest api?
@glass badger Yes
@rustic pebble ohhh okay I see now, thank you so much!
No problem!
Hello
So I have a django rest api
and a reactjs app which consumes it
so I want to access the authenticated user's info from the reactjs frontend
whats the best way to do this?
Right now I have an api view like this to access it is this right?
class CurrentUserView(APIView):
"""
An APIView to get the current user
[authenticated user]
"""
permission_classes = [permissions.IsAuthenticated]
def get(self, request):
user = request.user
serializer = CurrentUserSerializer(user)
return Response(data=serializer.data)
seems fine to me
is this how its generally done
how do i read static files
okay if theres any other better practice
someone pls tell me I have no idea
thanks @indigo kettle
yeah if someone else is more familiar hopefully they can answer, seems perfectly good to me though!
@naive oar Is there any way I can do this with requests? Because there is a thing called
requests.Session()
But no idea on how to get its id
@safe oasis I'm sorry not sure about getting the session id?
h
guys what should i start to learn, flask or django?
this is not a hiring place sorry
@peak locust
guys what should i start to learn, flask or django?
@wet heath Django
I have a doubt with Django.
So my media files are saved in a directory called media
here's my settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I want to display my files on the website, like
If theres a file with the path /media/images/default.jpg
then when I go to my_url/media/images/default.jpg The image should be displayed on the browser
how can I do this?
discord does the same thing, but how?
see?
@twilit needle yes thx 😊
I'm trying to do an if statement inside of an html file for django, would someone be able to look at my code and see whatsup?
Its just outputting the lines rather than performing them
hlo
hlo i need help regarding Flask
i have doubt in flask it is i am making a web development using flask and html so my doubt is i want my web app users to navigate between pages and in particular order . Example i have A,B,c pages i want users to go to c when they have visited A.B
this is my doubt
i hope i find answer soon
<div class="navbar" id="TopNavBar"> is this bootstrap? or its js element
I added some enum types in flask, but when I update the object, it says this enum type was not found
is editing enums not possible in flask sqlalchemy?
@twilit needle What authentication method are you using
You shouldn't be serializing request.user. You should be serializing request.data which contains an Authorization header with your user token.
Which (on sign up / login) you should be sending a token to your frontend which then saves it as a cookie.
@merry kelp on page A have a link to page B. On page B have a link to page C.
I want to implement reddit upvote/downvote blog post but I don't want to reinvent the wheel. I need a help, I use django.
Really quick question. Is there a way to define a column in a models thatll take in a number and make it negative?
@prisma jackal just add an 'upvote' field to your model and handle the rest on the frontend.
@plucky tapir wdym by that
@prisma jackal just add an 'upvote' field to your model and handle the rest on the frontend.
@native tide that and I would recommend running your view asynchronously
how could you do that? make it AJAX?
@twilit needle What authentication method are you using
@native tide hello
How can I make this possible
any ideas
Make what possible again?
sending the data and saving it as a cookie
how could you do that? make it AJAX?
@native tide both platforms
frontend and backend
@stone wren Oh yea I gotchu. Frequent API requests from the frontend to update the counter async
@twilit needle So... do you have a separate frontend, or are you just using Django templates?
Wait that doesn't matter
import SideBar from './components/anchored/sideBar';
import './staticFiles/css/app.css';
import React from 'react';
import axios from 'axios';
import api_url from './configuration.js';
import RegistrationForm from './components/forms/authenticationForms';
class App extends React.Component {
constructor(){
super();
this.state = {
loggedIn: false,
user: {}
};
this.handleLogin = this.handleLogin.bind(this)
}
checkLoginStatus() {
axios.get({api_url}+'users/current-user/', {withCredentials: true})
.then(response =>{
if (this.state.loggedIn === false) {
this.setState({
loggedIn: true,
user: response.data.user
})
}
})
.catch(error => {
if (error.response.status === (403 || 401) && this.state.loggedIn === true) {
this.setState({
loggedIn: false
/*the api raises an 403 NotAuthenticated error when trying to
fetch current-user data as an anonymous user */
});
} else {
console.log(error);
}
})
}
handleLogin(data) {
this.setState(
{loggedIn: true,
user: data.user}
);
}
componentDidMount() {
this.checkLoginStatus();
}
render() {
if (this.state.loggedIn === true) {
return (
<div className="app-container">
<div className="app-mount">
</div>
<SideBar />
</div>
);
} else {
return <RegistrationForm />
// bring up authentication container
}
}
}
export default App;
So this is what I am doing right now for the app.
I make a api get request for the current-user data and then if the api responds with an error [which means user isnt authenticated] then I bring up a login container
Nice, React, I like it
I am using reactjs for frontend
Okay, so what authentication method are you using?
idk sorry whats that
For example, session authentication or token authentication
In Django you have to specify your authentication method, and isAuthenticated checks against that.
So this is what I am doing right now for the app.
I make a api get request for the current-user data and then if the api responds with an error [which means user isnt authenticated] then I bring up a login container
@twilit needle is this best practice? like checking all those stuff, bringing up a login container and then after login deleting the container and finally bringing the app cointainer?
Ohh
is it in settings.py
Yeah, it's covered in Django authentication docs.
okay
For a React frontend I'd recommend token auth
class CurrentUserView(APIView):
"""
An APIView to get the current user
[authenticated user]
"""
permission_classes = [permissions.IsAuthenticated]
def get(self, request):
serializer = CurrentUserSerializer(request.data)
return Response(data=serializer.data)```
So setup that authentication, and whenever a user is added to your database, give them a token.
is this what I should do?
earlier I had this ```py
class CurrentUserView(APIView):
"""
An APIView to get the current user
[authenticated user]
"""
permission_classes = [permissions.IsAuthenticated]
def get(self, request):
user = request.user
serializer = CurrentUserSerializer(user)
return Response(data=serializer.data)```
Yep
okay
is this best practice
do you recommend doing this
something seems wrong to me thats why I am not used to this type of coding
how do I setup authentication? can u pls link the docs
and @native tide should I implement the auth for the whole project or only specific api views
When you set the authentication method in settings.py, it is the default auth for every view which has the isAuthenticated permission (which can also be set as a default).
So you're setting it for the whole entire project
And if you want views without any auth, you can use a different decorator (forgot what it is, it's in the docs)
yeah I get it now thanks
omg my project will be so insecure if u didnt tell me this thanks
one sec il finish auth then what should I do
Have a look through Django auth docs. (or maybe it's DRF, can't remember) then ask any questions if you have any
I'll be back later and I can help you with the React stuff
but I got a lesson to go to
okay thanks
one last thing
so the token you told me, thats where Ill store my user object right
I don't understand the question
Each user in the database will have a token field associated with it
okay
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
'email': user.email
})```
like this custom one what should my token have
so when you make a request to the API, it will have the token in the header, so the backend can know which user it is (from request.user which it handles)
hey guys i did homework from flask from pirple but they rejected it third time and not answering me ....can u look at it what should be bad or where should be mistake bcs i think it's right ...maybe i didnt understand something right
note(i did change home with about...want to have about things in home page so bcs taht i change that)
this is what they want(picture)
this is what i send them -->https://drive.google.com/drive/u/0/folders/1V8nWd549asD79QprRmxvMbxhcY4-IUax
Google Drive is a free way to keep your files backed up and easy to reach from any phone, tablet, or computer. Start with 15GB of Google storage – free.
