#web-development
2 messages · Page 123 of 1
Class based
gotcha
i'd recommend trying out the function based components though. w/ some react libraries class based components are incompatible
Hi guys
I built a small web server with Flask that connects YouTube PubSub to a Discord webhook.
Now I would like to add commands to subscribe or unsubscribe to a channel. Like "flask youtube subscribe Idh234had" I have seen that Flask even offers CLI command features. Is this possible with a running Flask app or how does this work?
Thank you, so just to be sure, the expected outcome of using IsAuthenticated is to stop users who are not authenticated from accessing api endpoints?
Yep. If a user is not authenticated the browser will return an Unauthorized response status. (401)
Since there are different types of authentication (session, token), you need to set you DEFAULT_AUTHENTICATION_CLASSES so that Django knows what type of authentication must be checked.
Just tested it again with postman and it seems to be working, Thank you. Not sure why it was not working before, I might have needed to restart my server.
How safe are JWTs? I looked online and people seem to have mixed opinions on them. what is the standard best practice for having an api backend? cookies? JWTs? something else?
I use token authentication (storing the token via a cookie)
one reason for this is that I can invalidate the tokens while JWTs can't really be invalidated on your end
but I don't really know much about JWTs, when I asked I was told to avoid them at all costs by some pretty senior people.
Hi. Guys I am currently working on a Django project which is a gaming website. (It is for a minecraft server) My client asked me to do authentication with xbox account.
Thank God there is api in python.
But the question is how to integrate this to an Django project.
Here is the website
Does anyone can help me make my html friendly to mobile user? I am still kind new to html
Thanks
@karmic egret you can use bootstrap
can you give me more specific detail and instruction? I can send my code to you.Thank you very much @native tide .
Got it 😀...i know html and css but not that good with js. Will learn it..
id probably focus on learning a js framework if u wanna develop a big app or many webapps and get ahead of the game a bit
otherwise, go ahead and develop in vanilla js using dom API
Thank you 😀
Why is the search bar yellow when i open it with python
http://prntscr.com/w5xqom
because of the roboter?
Yee. I think using REST framework might make our lives a bit easier but it can be done without that as well. I will try it without django REST framework. Thanks :))
hello
hi
I'm a beginner at django and I need some help
from django.contrib import admin
from .models import Product, Offer
class OfferAdmin(admin.ModelAdmin):
list_display = ('code', 'discount')
class ProductAdmin(admin.ModelAdmin):
list_display = ('tag', 'price', 'stock')
admin.site.register(Offer, OfferAdmin)
admin.site.register(Product, ProductAdmin)```
this is a practice that I did
and this is the error I keep getting
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Batata\PycharmProjects\Using_Django2\products\admin.py", line 1
4, in <module>
admin.site.register(Product, ProductAdmin)
File "C:\Users\Batata\PycharmProjects\Using_Django2\venv\lib\site-packages\dja
ngo\contrib\admin\sites.py", line 119, in register
raise AlreadyRegistered(msg)
django.contrib.admin.sites.AlreadyRegistered: The model Product is already regis
tered with 'products.OfferAdmin'.```
can anyone help??
Did you register the Products class anywhere else?
yep in the modules file
I think that why you are getting an error. you have aldredy registered it in another place
so shall i not register it?
Unregister it from anywhere else you have registered it. It should work
yeaaa... it didn't work
You cannot register more than one ModelAdmin for the same model (this results in an AlreadyRegistered exception). -google
@warm shoal did it work?.
ummmm.... well this is weird... i tried it a couple different times and then exited the server and rewrote what was written before...... i ran the server again to find it working...??
Did you get any error
nope
though i am confused...
why did it work now if it gave me an error before?
well anyways thanks a lot for your help 😄
it sometimes happens to me also. I get get an error but when I run it again the error goes. wierd
suppose I have list of something like this
[
0: {id: 5, itemName: "test", quantity: 2},
1: {id: 7, itemName: "test1", quantity: 1},
2: {id: 2, itemName: "test2", quantity: 3},
]
how can I convert them to this list? I want to extract quantity
[
0: {
quantity: 2,
product: {
{id: 5, itemName: "test"
},
1: {
quantity: 2,
product: {
{id: 7, itemName: "test1"
},
2: {
quantity: 2,
product: {
{id: 2, itemName: "test2"
},
]
Anyone know a good way to reference static files with Django?
When not in templates
@devout coral doesn't it have url_for?
I do not quite follow
from django.templatetags.static import static This is what I am currently using @quick cargo But I am getting access denied.
Do you mean referencing them in terms of their paths?
I want the url since it is in S3.
I could download it into temp and then use it but that seems kinda meh.
I'm pretty sure django has a url_for function which given X static file name will produce the relevant path for it but I don't entirely get what you want
You know how in templates you use the static tag to reference a static file and it returns the full url. That is what I need.
I just need the url so then I can use it in reportlab to put it on a PDF.
You want url_for then iirc
But note it returns a relative path based of the location of the main file
That is saying to use the method I am using now.... But I get an error.
logo_url = static('\main\\MV_Transportation_logo.png')
That is how I am implementing it in my code.
@quick cargo Any idea on why I would be receiving that error?
Can anyone suggest me how can I make a django form dynamic. I mean I need to accept a response through a from and then check if the input already exists in the database. If no then I will simply save the response to the database. But if it already exists then I need to make another field(previously hidden input in HTML form) visible within the form along with the data last input pre-filled. I am a newbie in django and it would me nice if someone could help me.
If you're on Linux it could possibly due to running it with sudo last time and the files now need sudo?
If its Windows then it's normally only raised if its open in another process
But mostly a shot in the dark
The thing is all the files are in S3...
Also this is all containerized and it is running on a debian based image.
You could use ajax to post the form after they edit a field.
maybe you can have a two-step process, so in the view which receives the response of the first form you return a page which shows another form with some fields prefilled so you can implement your logic in the views.
Good thing about ajax is it is asynchronous so the user would not be waiting and it should be a good user experience
@quick cargo Also, I thought it could be my S3 policy but the static file I am trying to serve is the logo which is being used in the page already.
Alright, I will try for a little longer then I will just resort to downloading it and storing it temporarily.
Thanks @devout coral but I don't know much about Js. Thanks @native tide I will try this out as it is much easier. Later on I will try AJAX to make this async.
great! If you want to try the AJAX-like client-side request approach I recommend fetch API, because it's pretty easy to use:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Uploading_JSON_data
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
Hi, not sure if this is the best channel for this since this is a deployment question, but I'm trying to deploy a flask app via uwsgi and I'm having trouble figuring out how to get uwsgi to run as python 3.7. It defaults to 3.6. Has anyone dealt with that before?
All this is happening in a venv:
(venv) ➜ venv which python
/apps/venv/bin/python
(venv) ➜ venv python --version
Python 3.7.5
(venv) ➜ venv which uwsgi
/apps/venv/bin/uwsgi
(venv) ➜ venv uwsgi --python-version
3.6.9
How do I use the gmail api during development?
It’s in order for me to create client id or authentication, it’s forcing me to provide a public url
I keep getting AttributeError: 'User' object has no attribute 'pk' when trying to use django admin site
Which fraemwork is good to use for web development, like php has some laravel, CI ?
MVC framework for Python
@simple kite are u good?
yes sar, i em wery good
mahk sure to subribe to my channal at click notification beell
zebra goes chirp chirp
hi everyone, i'm trying to send a post request to my django server using rest through react/axios, but the database never seems to get updated (request succeeds, returns 200 but the database doesn't update when i check on frontend): https://github.com/hanyuone/kanban
django server is on localhost:8000, react frontend is on localhost:3000
request is sent in frontend/index.jsx
sorry if i can't reduce the project down to a minimal example, not exactly sure how to reduce the problem by much since i'm new to webdev
check the database through the backend
did it get updated?
Not sure how to do that, what exactly do I print if anything
do I set up a breakpoint or smth?
like it does show the request going through for the PUT and GET afterwards when i fetch /api/boards but i'm not really sure how to check the full db
a comment section to a non blog flask application ....any idea how to approach this?
how do i set up mongo Db ?
ive been struggling with settting it up for sometime now ?
hmmm
how do i check it from the backend? where do i put the print/breakpoint/etc.
cause i did check the request coming in and the data all seemed fine, in the views section
but how would i make sure the data is updated after
access the database directly
How do I do that
do you know SQL?
alterantive
alternatively
just run the shell app and query the model objects
Yeah I know a little, should I just run the sql commands in shell?
There isn’t a place for me to query as python code is there
like i tried displaying the data that was sent and retrieved (console.log in axios in frontend/index.js), the put request seemed fine and the data seemed fine when i printed it out in views.py, but the actual PUT request doesn't actually update the database for some reason
yes
there is
look up
the shell management command
as in pipenv shell?
ok i think the issue might be that PrimaryKeyRelatedField has a specific order and can't be swapped around
is it possible to swap around the order of keys displayed in PrimaryKeyRelatedField? because i have a kanban-like app, and i want to switch the order of certain tasks around on a specific board by dragging/dropping them
can anyone tell how to style the dropdown menu in django?? I want to give a custom text in a select filter field instead of the ----(dashes)
Show us the code please...models and views
yes, to generate tables and list
use choices in your model then add a default in that field
in your models.py
MY_CHOICES = (
('ORANGE', 'Orange'),
('BANANA', 'Banana'),
)
class Fruit(models.Model):
fruit = models.CharField(default='MANGO',
choices=MY_CHOICES, max_length=20)
@steel reef try the code above
@open owl ok
@open owl the default is 'MANGO' and you don't have a 'MANGO' choice
How about this:
PROPOSED = 'Proposed' ACTIVE = 'Active' ONHOLD = 'On Hold' COMPLETED = 'Completed' CANCELED = 'Canceled' STATUS = [ (PROPOSED, 'Proposed'), (ACTIVE, 'Active'), (ONHOLD, 'On Hold'), (COMPLETED, 'Completed'), (CANCELED, 'Canceled'), ] status = models.CharField(max_length=9, choices=STATUS, default=PROPOSED, null=True)
dont think if its necessary for default to be in choice. Thats not the point at all
HOW TO START READING DJANGO CODE? because i want to code in Google summer of code ..HELP
Thank you very much !!!!!!!
is there a way to "order" a serializers.PrimaryKeyRelatedField? i have a kanban-like application with a bunch of Tasks linked by primary key to Boards, and i want to reorder the Tasks by dragging and dropping
my models:
class Board(models.Model):
title = models.CharField(max_length=120)
def __str__(self):
return self.title
class Task(models.Model):
board = models.ForeignKey(Board, default=1, related_name="tasks", on_delete=models.CASCADE)
title = models.CharField(max_length=120)
description = models.TextField()
order = models.IntegerField()
def __str__(self):
return self.title
my serializers:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ["id", "title", "description", "order"]
ordering = ["order"]
class BoardSerializer(serializers.ModelSerializer):
tasks = serializers.PrimaryKeyRelatedField(many=True, queryset=Task.objects.all())
class Meta:
model = Board
fields = ["id", "title", "tasks"]
what i originally did was PUT requests, but i didn't realise that the tasks prop of BoardSerializer can't be updated
error starts from here, I am trying to access my model method (get_packages_by_package_state_value), then this happens
File "/home/kenan/exbir/exbir-api/exbir/database/models/package.py", line 113, in get_packages_by_package_state_value
return cls.query.filter_by(current_state=PackageState(package_state_value)).all()
File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 514, in __get__
return type.query_class(mapper, session=self.sa.session())
File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py", line 78, in __call__
return self.registry()
File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 1022, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 3286, in __call__
return self.class_(**local_kw)
File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 136, in __init__
self.app = app = db.get_app()
File "/home/kenan/exbir/exbir-api/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 987, in get_app
raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
what i originally did was
PUTrequests, but i didn't realise that thetasksprop ofBoardSerializercan't be updated
@final sequoia why not PATCH the order field
I decided to close my submenu when a user clicks on a link inside. So now, when they navigate back a page, the submenu isn't still open. However, the focus is still inside the submenu(which is closed, display: none;). Was I wrong to close the submenu onclick?
@final sequoia if you don't know SQL you can get a visual DB browser, e.g. SQLite DB Browser and see what rows are in your DB
Hello, can i ask here for raw discord api?
I have this line: user = User(*request.data) Is there any way that I can set user to equal request.data only for empty fields? so basically, get request.user and request.data check if there are any null values in request.data and replace them with whatever is under the same attribute in request.user without needing an if statement for each single attribute
html??
Вы не возражаете, если я воспользуюсь гугл переводчиком
how do I install django python 3.9.1
I tried
python -m pip install Django==3.9.1
it didnt work
@deep bloom what happened
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
...is Python installed?
🥴
I am using django and getting this error ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine can anyone help?
are you using ajax?
Thanks. I found a way
ok
нет
не возражаю
алё, ты куда пропал?
Hello there, i am searching for someone who had used a reusable apps in django
i have been up all night trying to figure this out... help please why can't i cal postUser inside the else but i can call it before the addEeventListener?
let postUser = async (name, email, password) => {
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
email: email,
password: password
})
};
try {
const response = await fetch(`http://localhost:80/register`, options)
const json = await response.json();
console.log(json)
return json
} catch (err) {
// TODO: put a toaster
console.log('Error getting documents', err)
}
}
let Register = {
render: async () => {
return /*html*/ `
<section class="section">
...
</section>
`
}
, after_render: async () => {
// TODO: add event listner for email checker on type
document.getElementById("register_submit_btn").addEventListener("click", () => {
let name = document.getElementById("name_input");
let email = document.getElementById("email_input");
let pass = document.getElementById("pass_input");
let repeatPass = document.getElementById("repeat_pass_input");
if (pass.value != repeatPass.value) {
alert (`passwords don't match`)
} else if (name.value =='' | email.value =='' | pass.value == '' | repeatPass == '') {
alert (`fields can't be empty`)
}
else {
// XXX: HERE IS THE ERRORRRRRR
let resp = await postUser(name, email, password);
// TODO: call api register
// TODO: show details if any
// TODO: add token to Auth header
// TODO: redirect to /
alert(`email ${email.value} registered`)
}
})
}
}
export default Register;```
I have a question about no such table error or even better known as (main.auth_user_old)...
How should I fix it?
guys if for example i want to build a website, what languages do i need to learn?
in a venv git add . is not working what should i do ?
There are many languages to make a website but the most websites use html,javascript and css
The html is used for the contend the css is used for styling and javascript is used for back end or front end
Yea is from the Django version
Just downgrade to 2.1.5 version and it should work
I hope I helped you
Good luck!
I keep getting a json decode error here when using oauth with authlib can someone tell me what the issue is.
@app.route('/glogin')
def login():
google = oauth.create_client('google')
redirect_uri = url_for('authorize',_external=True)
return google.authorize_redirect(redirect_uri)
@app.route('/authorize')
def authorize():
google = oauth.create_client('google')
token = google.authorize_access_token() #JSON DECODER ERROR
resp = google.get('userinfo')
user_info = resp.json()
session['email'] = user_info['email']
session.permanent = True
return redirect(url_for('index'))
anyone knows best way to show the picture png as canvas streaming for live streaming?
which python module is good to work with png streaming?
picture should update automatically as latest file
clear your database or just delete db.sqlite3 then makemigraions and migrate
try to re-initialize git and repeat the command
I did it's still not able to stage all the files
yo so assume i have this folder structure with these files
folder-
main.py
foo.py
foo.json
``` I can read the `foo.json` file inside of `foo.py` , and then import the variable that holds the parsed json value in `main.py` as `from foo import jsonval` .
But now if I move `main.py` outside of the `folder` directory,
main.py
folder-
foo.py
foo.json
``` I change nothing in foo.py and foo.json except I change the import statement in main.py to from foo.foo import jsonval now, the read file line inside foo.py which reads foo.json throws an no such file or directory "foo.json" which don't really make sense to me, does anyone know why?
even git add -A doesnt work?
It doesn't .... Is it common... Should I do this while I am not in venv ....I tried that to but didn't happen
it has the same meaning, just give it a try and then tell us if it helped
I did.... It got stuck there and that went on for 15 mins....I tried vs codes git and GitHub. Extension it says that index.dl is already existing so it can't create one and then a bunch of errors in the output console
can you try to follow along this
https://stackoverflow.com/questions/10859632/git-add-still-nothing-to-commit-with-new-files
so i tried this and tried manually adding everything
and found my venv folder is not getting added
everything else is good
can ignore my venv folder and yet be able to deploy it using github ?
I want to style my home.html template
{%extends '_base.html'%}
{%block title%}Home{%endblock title%}
{% block content %}
<h1>Homepage</h1>
{% if user.is_authenticated %}
<p>Hi {{user.email}}</p>
<a href="{% url 'logout' %}">Log Out</a>
{%else%}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'signup' %}">SignUp</a>
{%endif%}
{% endblock content%}
that inherits from _base.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href='{% static "css\base.css" %}'>
<title>{% block title %}Bookstore{% endblock title %}</title>
</head>
<body>
<div class="container">
{% block content %}
{% endblock content %}
</div>
</body>
</html>```
with the base.css file
body{
background-color: rgb(39, 39, 39);
color: white;
}
h1{
color: red;
}```
But it doesn't work
The styling doesn't apply
This are in my settings.py
STATIC_URL = '/static/'
STATIC_FILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_FINDER = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]```
i hope it doesn't work buddy don't jump the line just because u want help
🤨
Anyone experience in google maps polygon circles in python backend and js frontend?
@native tide why is your STATIC_FILES_DIRS a list? Is that normal?
@inland stirrup I don't think that's a rule.
Also @native tide why is there a backslash here "css\base.css" is that normal too?
#rules don't jump in with your question if one is already going being discussed
@inland stirrup this is a topical channel...
Are u saying yes to my post or what??
My question was almost resolved and then came that huge question tell me what do I do spam the server?
Are u saying yes to my post or what??
My question was almost resolved and then came that huge question tell me what do I do spam the server?
@inland stirrup if someone was already helping you, I don’t think they’re going to forget about that...
Scroll up
if you want a channel that is exclusively for your usage, open a help channel.
Lets leave it here
Scroll up
@inland stirrup I read everything already
Good for you
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)``` I want to loop through a JSON sent through a request, for each item in the JSON I want to add to my filter, how would I go about doing this?
Coders block is not letting me figure this out.
Having an if statement included to check that it is not null
what does your JSON look like
{"role":this.state.role, "field":this.state.field, "stack":this.state.stack, "language":this.state.language}
When I load it this is what its going to be
so you want e.g.
role=this.state.role, field=this.state.field etc.?
@haughty turtle
In my models I have availabeTag = models.JSONField()
So if availableTag contains all of the values that I am going to be receiving from the dict
so you want to filter a JSON field?
yeaup
which model
Blog?
because I see no Course here
and that looks like something from the Django tutorial
course is the Model in which contains availableTag which is a JSONField
it is, was just an example
then
well
I would say
when you're asking for help
ask something that is as close to what you want as possible
because at first you didn't mention the JSON field and your model is named something different
anyway, you can access the values of a JSON field using double underscore notation
exactly as if they were chained lookups of a model
e.g. available_tag__role=this.state.role
so what you need to do is remap the keys of the query JSON
and then use ** to spread it into keyword arguments
I mean I would be able to edit it, just need a working example py ContactInfo.objects.filter( data__name='John', data__pets__has_key='dogs', data__cities__contains='London', ) from the django docs is similar to the other filter method I sent
the point is
it's harder for people to understand what you want
if you don't explain yourself clearly?
ok so my keys I need to make sure matches how filter would look for the value?
like your original question suggested 1. you have a Blog model and 2. you were filtering on the model's fields, as opposed to the contents of one of its JSON fields
yes
{data__role:this.state.role, data__field:this.state.field, data__stack:this.state.stack, data__language:this.state.language}
but how would it convertdata__role:this.state.role to data__role=this.state.role
and all my other key values?
like I said
this
do you know how ** works when passing arguments to a function?
I have been reading this
I know it unpacks it, but I do not see how ** convert key:value to key=value
@vestal hound
Default python thing
Hi guys i have a problem in flask i tried to get subdomain effect like subdomain.domain.com do you know how to do it
That is not a problem with flask, that is a server responsability
You can setup that in NGINX
let me see your urls.py
using flask, domain.com/manage/guildID/control/ makes stuff like not clickable, like stuff works, but like when u click stuff, it doesnt do what its supposed to, but when i do domain.com/manage/guildID it works
like without the 3rd argument
I am unable to add my django app to installed apps. I get this exeption: '''ModuleNotFoundError: No module named 'user_chat' '''.
@eternal blade user_chat and member_login app should be in same directory as the manage.py
ok
@native tide thanks it is working now
Hello i need help with hosting my website
uwsgi gives me error that i can't understand
this is error
can someone pls help me here?
thanks a lot!
hey
i want to make something like that blue field for app name just where i painted that black line
i already have something like 70tables that only main admin can access to
but i have to devide them somehow because thats too ugly if i show up 70models under one app name
@onyx flume you can override the index template of django admin to make changes that you want https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#overriding-admin-templates
ty
Can someone tell what's wrong with this jQuery code?
var arr = [5, 4, 3, 2, 1, 0];
$(".countdown").each(function (index) {
console.log(index);
$(this).html(arr[index]);
});
// Logs `0`
// h1 with a value of 5. No rewritting
/* HTML
<h1 class="countdown"></h1>
*/
I just want a basic countdown, counting from 5 to 0.
I would help u but jquery is not my thing...
firstly, i haven't touch javascript for a long time but shouldn't you be using forEach() instead ?
second you can just use sleep(1) in each iteration to wait and run html()
I think forEach() is not included in jQuery but I figured it out anyways. I used setInterval() and conditional statements.
that sound like much more hard work then using sleep()
I didn't know about sleep() lol.
well it's basic stuff in JS 😕
var arr = [5, 4, 3, 2, 1];
var i = 0;
timer = setInterval(function () {
if (i < arr.length) {
$(".countdown").html(arr[i]);
i++;
} else {
clearInterval(timer);
$(".countdown").remove();
$('<img src="https://i.gifer.com/7b7F.gif" id="rickroll-img">').appendTo("body");
}
}, 750);
lol you can just set default value of i =5 or something, loop each and i-- . Don't even need to use array
Hey, I am new to web development and Django and am trying to make a login/register system. I do not want to use Django's built in system, so that I can learn and also understand how to do the same for other apps I create in the future. I have a template created but am unable to find a way to save the data a user enters. It would be great if someone could help me out with saving this data. (I am using bootstrap)
Template(register.html):
<nav class="mx-auto card w-25" style=text-align:center;border:none;padding-top:12%>
<form action="." method="POST">{% csrf_token %}
<h3 style="padding-bottom: 10px">Register</h3>
<div class="form-group">
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Username" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Repeat Password" required>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</form>
<p style="text-align: left">Already registered? <a href="{% url 'user_system:login' %}">Login</a></p>
</nav>
views.py:
return render(request, 'user_system/register.html')
models.py:
class userss(models.Model):
username = models.TextField()
password = models.TextField()
@quick bay Django have a good docs on how to handle data with form https://docs.djangoproject.com/en/3.1/topics/forms/
I will read through once again, but last time I did I didnt find anything useful
if you want your own authentication system, i'm not recommend because that is for advance uses, the base django authentication perfectly handled it already https://docs.djangoproject.com/en/3.1/topics/auth/customizing/
where is your forms.py file ? and your views.py is incomplete as well
i bet you should learn how to handle forms first.....youtube, google, read some docs
Alright thanks
@quick bay you probably missed this part in that docs where they described how to get data from your form
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Thanks a lot @gaunt marlin. I'll read through and try making some changes
@quick bay in your html the form need to have action url to your views url -> this part <form action="." after that you can get the data from request.POST['your_input_name'] in the views.py
man why this is not working
def todo_add(request):
added_date = timezone.now()
content = request.POST["content"]
print(added_date)
print(content)
return render(request, 'todo.html')
that was views.py
<form action="todo/" method="post" class="form-inline">
<input type="text" name="content" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>
that was todo.html
It says theres problem in views.py
content = request.POST["content"]
MultiValueDictKeyError
You'll also need your view to handle it correctly. That doc should have the info you need.
the problem is not here
When I click submit
I want it to reload the page
the tutor made it reload the page in a stupid way
it doesn't work properly to me
reload the page with new information?
no the same page
So just page refresh when you press a button?
You could just link the button to that page.
so <a href="{% url 'your_url' %}"><button>Press Here</button></a>
or just do:
def todo_add(request):
return render(request, 'todo.html')
and link the button to the function
wait
@dense slate that's how views.py looks rn
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .forms import todo
from django.utils import timezone
@csrf_exempt
def todo_add(request):
added_date = timezone.now()
content = request.POST.get("content", False)
print(added_date)
print(content)
return render(request, 'todo.html')
and that's forms.py
from django import forms
class todo(forms.Form):
added_date = forms.DateTimeField
text = forms.CharField(max_length=255)
{% extends 'base.html' %}
{% block content %}
<div class="row mt-4">
<div class="col">
<h2>Add Item</h2>
<form action="add_todo/" method="post" class="form-inline">
<input type="text" name="content" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>
</div>
</div>
{% end block %}
that was todo.html
You're missing things you need from forms.py and your view. Go look at the link I sent you.
ok
Please I need help I maked a multiple choice quiz without a GUI but I need to make one that has a GUI?
if im looking into start python web developement, what other languages do i need to know except python
and html
none, but css and javascript will be helpful sometimes.
hm ok, also do you know any docs and yt's that i can watch to learn python website dev
Do u want to see?
Djangogirls tutorial is really good. One of the first ones I did.
Should i do Django or Flask
Your choice. Django has more stuff built-in.
Flask is just leaner. I don't know much about Flask.
I really enjoy using it, yea.
ok.
You can easily find job with django too
oo ok
@dense slate It gave me this error
https://gyazo.com/c637869b8cba331c59728b148b3bd303
thats views.py
def todo_add(request):
if request.method == 'POST':
form = todo(request.POST)
if form.is_valid():
added_date = timezone.now()
content = request.POST.get("add_todos", False)
print(added_date)
print(content)
return render(request, 'todo.html')
else:
form = todo()
return render(request, 'todo.html', {'form': form})
my code is a mess, im lost between the tutorial and the doc lol
Your form is probably not valid and so you're not getting to any return statement.
DId you fix your forms.py? You were missing things there.
like meta
from django import forms
class todo(forms.Form):
added_date = forms.DateTimeField
text = forms.CharField(label="add_todos", max_length=255)
nope
I saw meta once but I don't know what it is
I don't think it's necessary actually.
Put a different print('something') after each if and see what it prints.
it didn't print anything
def todo_fun(request):
print("hello")
return render(request, 'todo.html')
@csrf_exempt
def todo_add(request):
if request.method == 'POST':
form = todo(request.POST)
print("if1")
if form.is_valid():
print("if2")
added_date = timezone.now()
content = request.POST.get("add_todos", False)
print(added_date)
print(content)
return render(request, 'todo.html')
else:
print("else2")
form = todo()
return render(request, 'todo.html', {'form': form})```
the django debugger says
ValueError at /todo/add_todos/
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://127.0.0.1:8000/todo/add_todos/
Django Version: 3.1.4
Exception Type: ValueError
Exception Value:
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
Exception Location: D:\python\lib\site-packages\django\core\handlers\base.py, line 307, in check_response
Python Executable: D:\python\python.exe
Python Version: 3.8.6
Python Path:
['D:\\Eshop\\pyshop',
'D:\\python\\python38.zip',
'D:\\python\\DLLs',
'D:\\python\\lib',
'D:\\python',
'C:\\Users\\Fw admin\\AppData\\Roaming\\Python\\Python38\\site-packages',
'D:\\python\\lib\\site-packages',
'D:\\python\\lib\\site-packages\\win32',
'D:\\python\\lib\\site-packages\\win32\\lib',
value error at /todo/add_todos :/
I saw the console
it didnt print anything
Oh, your form also is not referencing a correct URL.
Is javascript necessary for web development?
it should be {% 'your_url' %} in the action
Ayyy it gave me if1
@icy basalt No, but you won't get much farther than basic html without it.
What do I need to learn for web development?
@vernal furnace Yea do you are getting the POST through but it's not valid. What's the error now
Html5, css, and what else?
still the same error
how to validate it
I don't want to create another html tho
@icy basalt Django Or Flask if u are interested in python, and React.js if u are interested in Javascript
from .forms import todo
@icy basalt Yea, React, Angular, or Vue are the main front end choices.
isnt that how u import it? @dense slate
Put this outside your second if, and before the else:
return render(request, 'todo.html')
that will at least return it
but your form is not valid for some reason
You can use print() to help yourself debug things.
oh, you're trying to collect date in your forms.py, but you don't have a date field in your form.
remove it from your forms.py
That's why it's not validating.
You also have text= in your forms.py, but your form has a field called "content"
You need to match those. This is why some tutorials might help you get the basics here.
lol still the same error
ValueError at /todo/add_todos/
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
def todo_add(request):
if request.method == 'POST':
form = Todo(request.POST)
print("if1")
if form.is_valid():
print("if2")
added_date = timezone.now()
text = request.POST.get("add_todos", False)
print(added_date)
print(text)
return render(request, 'todo.html')
else:
print("else2")
form = Todo()
return render(request, 'todo.html', {'form': form})
something is wrong
Its mainly because im confused
the tutor was so bad man he confused everything I learned
in your second if statement, unindent the return once
are you getting it to print "if2"?
nope it printed if1
so it's still not valid, change the first print to print(form)
see where your error is
if you're not getting "if2" it's not valid
It returned me to the add_todo/ path
unindenting the return just removed it from the if and now doesn't require it to be valid
oh yea
ok now it gave me something new
[22/Dec/2020 16:01:46] "GET /todo/ HTTP/1.1" 200 2722
<tr><th><label for="id_added_date">Added date:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="added_date" required id="id_added_date"></td></tr>
<tr><th><label for="id_text">add_todos:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="text" maxlength="255" required id="id_text"></td></tr>
[22/Dec/2020 16:01:48] "POST /todo/add_todos/ HTTP/1.1" 200 2722
{% extends 'base.html' %}
{% block content %}
<div class="row mt-4">
<div class="col">
<h2>Add Item</h2>
<form action="add_todos/" method="post" class="form-inline">
<label for="add_todos/">Your name: </label>
<input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
</form>
</div>
</div>
<div class="row">
<div class="col">
<ul class="list-group">
<li class="list-group-item">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Morbi leo risus</li>
<li class="list-group-item">Porta ac consectetur ac</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
</div>
</div>
{% endblock %}
that's how my todo.html looks
I'm 100% sure the problem is here
ValueError: 'myproject.sock' is not a socket
how do i solve this
i am using gunicorn
You're still trying to get date. Did you remove that?
Ok so I removed added date completely
the page is not validating
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
There was a bug in my form a week ago, It was one line of code and I had to struggle 3 days to fix it
hope this one is not the same lol
#help-mango somebody please
Just wanted to say thanks guys I asked questions frequently throughout the semester. I had no web development experience and had a huge project, this place kept me from flying off the loose end
@vernal furnace What is the issue you're having?
what is the difference between HS256 and RS256 for JWT? Is one more secure than the other? should I use one over the other? also what do the numbers signify? there are versions with 512 instead of 256.
any reason you chose JWTs over cookies?
does django use processes or threads for handling "threads"?
using flask, domain.com/manage/guildID/control/ makes stuff like not clickable, like stuff works, but like when u click stuff, it doesnt do what its supposed to, but when i do domain.com/manage/guildID it works
like without the 3rd argument
Hey everyone
I'm wondering what is the best practices to unit test file fields in a Django Application
I'm building a project that uses Azure Storage, but I wish there was a way to use the default system storage when testing.
anyone knows how can I accomplish this?
@native tide Hope u are here, my problem is the form is not validating
Yeah I'm here (kinda), what's the error message?
ValueError at /todo/add_todos/
The view todo.views.todo_add didn't return an HttpResponse object. It returned None instead.
And your view?
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import Todo
from django.utils import timezone
def todo_fun(request):
print("hello")
return render(request, 'todo.html')
@csrf_exempt
def todo_add(request):
if request.method == 'POST':
form = Todo(request.POST)
print(form)
if form.is_valid():
print("if2")
text = request.POST.get("add_todos", False)
print(text)
return render(request, 'todo.html')
else:
print("else2")
form = Todo()
return render(request, 'todo.html', {'form': form})
Did you remember to include the csrf token in your form
no
Oh its csrf exempt
so should I?
{% extends 'base.html' %}
{% block content %}
<div class="row mt-4">
<div class="col">
<h2>Add Item</h2>
<form action="add_todos/" method="post" class="form-inline">
<label for="add_todos">Your name: </label>
<input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
</form>
</div>
</div>
{% endblock %}
that's how todo.html looks
you should (generally speaking), but it won't change the error you're getting.
Could you try this?
def todo_add(request):
if request.method == "POST":
form = Todo(request.POST) # this "inserts" the POST data into this form instance, which then can be used to check whether it's valid or not
if form.is_valid():
# do what you want with the form's data
else:
errors = form.errors
print(errors)
# show forms errors
else:
form = Todo()
return render(request, 'todo.html', {'form': form})
# make sure you're returning something within the if statements too.
btw I don't work with Django forms but can't you render it into your template without having to write all the HTML yourself?
wait its giving me syntax error at the else:
my indentations are wrong
nvm fixed it
@vernal furnace You still have that return statement indentation that I told you to remove before.
It's not validating, and you are not getting to the "else" part of the statement.
Therefore it doesn't hit any return statement.
I removed it but I thought it was for test purposes
No, unindenting it is the right move, but you have a validation problem to fix.
Print your form and look at which item it is saying "blah blah is required"
That is what is invalidating the form.
{% extends 'base.html' %}
{% block content %}
<div class="row mt-4">
<div class="col">
<h2>Add Item</h2>
<form action="add_todos/" method="post" class="form-inline">
<label for="add_todos">Your name: </label>
<input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
</form>
</div>
</div>
{% endblock %}
Is this writing your own form? Shouldn't the form instance be passed through the context? Otherwise it will never validate
Yea, why is "action" still not using your URL like we talked about?
Its?
although
Might not be necessary. Maybe you can route that way.
It is? Ok, because it's not showing it above. Unless that's the old code.
I just want to get it working now, its another problem (action="add_todos/")
But can you correct me on this... how is that HTML bound at all to your form instance
How would you view know if the form is being submitted if it's not being rendered in your template
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
Yea, Nut is right. I am used to using widget-tweaks so I thought he was doing it manually.
You can just use {{form}} to make it easier.
Because he passed form in the context and then did not use it in the template, so it will always be invalid.
If they want to stick with their custom form I think they need an API to handle the validation
which is more work than required 🙂
That might be my fault. I don't think he had it setup that way originally but I sent him to the forms docs.
Wait guys
But that still is the way it should be done with forms.
why do I have to validate my form?
I don't think you have to, I am so used to doing that with every form that I forgot you can probably skip that step.
Sorry!
Well, in this case you are trying to validate your Todo form, and that may have some validators such as required=True, so you have to ensure that your inputs are valid or the form will not submit
So should I skip the problem or fix it?
<li>This field is required.</li>
it says this fieldd is required @dense slate
<li class="list-group-item">{{ text }}</li>
Well you can't "skip" the problem, that is the problem
@vernal furnace do you understand why your form is not validating?
Ok so tell me if you don't understand this, I'll try to explain:
You're trying to validate your form when you say form.is_valid().
What is the form you might ask?
form = Todo()
It's an instance of your Todo() form.
So for the view to be able to validate the form, it must be rendered. But you are not rendering your form, you are rendering something else with the HTML you sent. The form in your HTML does not correspond to the Todo() instance so it will never validate.
How to make it respond?
Well you have to render the form. So remove the HTML you have
You understand that right?
Talk me through which parts you aren't getting
so do u want me to remove "todo.html" from return render?
No.
The form that you wrote in the HTML is not at all linked to the Todo() instance
When you say form = Todo() and then check its validity with form.is_valid() that form is the Todo() instance. You're trying to submit a different form and the view doesn't know what it is.
Here's a good time to read through the docs and watch a YT video on django forms
But above in the text I've shown how to fix it
You wrote the Todo form right? So then all you have to do is render it.
when I click submit it sends me to add_todo/
its doesn't give me value error
idk while u were talking with demi I did some stuff
def todo_add(request):
if request.method == 'POST':
form = Todo(request.POST)
print(form)
if form.is_valid():
print("if2")
text = request.POST.get("add_todos", False)
context = {
"text": text
}
print(text)
return render(request, 'todo.html', context)
else:
print("else2")
form = Todo()
return render(request, 'todo.html')
oh
I have to remove return render right?
so is your form validating now?
look
if I indent the last render under else
it will give me value error
if I keep it outside else it will work fine
I mean idk how fine it is, since it doesn't return any value to me lol
how do i pass a bool in a post req
yeah it gives you a value error because your form is not validating
you submit your "form - which is not linked to your Todo instance", it redirects to your add_todos/ with a POST request. But, your form is not valid and there is no else statement to return anything.
and if i remove type=bool it makes it a str
any flask person here?
You've already linked it, form = Todo(), I've explained that, now you have to render it, which I have explained too above
@fresh sand what doesn't work about it, is premium null?
Can you print the request data that you're sending?
def updateCreds(
uid,
avatarUrl,
email,
userName,
followers,
following,
moderator,
premium,
notifications,
profession,
token,
verified,
notification,
posts
):
uid = request.form.get("uid")
avatarurl = request.form.get("avatarurl")
email = request.form.get("email")
premium = request.form.get("premium", type=bool)
followers = request.form.getlist("followers")
following = request.form.getlist("following")
moderator = request.form.get("moderator", type=bool)
notifications = request.form.get("notifications", type=bool)
profession = request.form.get("profession")
token = request.form.get("token")
verified = request.form.get("verified", type=bool)
notification = request.form.getlist("notification")
posts = request.form.getlist("posts")
listAll = {
'avatarurl': avatarurl,
'email': email,
"followers": followers,
"following": following,
"moderator": moderator,
"notification": notification,
"notifications": notifications,
"posts": posts,
"premium": premium,
"profession": profession,
"token": token,
"userName": userName,
"verified": verified,
'uid': uid,
}
try:
print(notification)
for key, value in listAll.items():
if value is not None and key != "uid":
users.update_one({"uid": uid}, {"$set": {key: value}})
# print(users.find({"uid": uid}))
# return "hwello"
return pjson({"data": list(users.find({"uid": uid}))})
if uid is None:
return {"error": "must provide uid"}
except Exception as e:
return jsonify(
{
"status": "error", "error": e
}
)
this is the complete function
hey, with flask, using <var> and getitng var in def routevar(var): breaks the page! anyone got any ideas?
do all of the other variables w/ type=bool work?
{{ form }} you mean rendering it like this?
yes
@native tide no
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
but where would I render it, I have some code there already
Ok, so I'd suggest printing your request to see what datatype they are. I think they are strings in this case within the JSON
like just type {{form}} in the middle of todo.html lol
@vernal furnace what code is there already?
{% extends 'base.html' %}
{% block content %}
<div class="row mt-4">
<div class="col">
<h2>Add Item</h2>
<form action="add_todos/" method="post" class="form-inline">
<label for="add_todos">Your name: </label>
<input id="add_todos" type="text" name="add_todos" value="{{ text }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
</form>
</div>
</div>
<div class="row">
<div class="col">
<ul class="list-group">
<li class="list-group-item">{{ text }}</li>
</ul>
</div>
</div>
{% endblock %}
Why do you need that form, what purpose does it serve
yes if i remove type=bool and make it
premium = request.form.get("premium")
it makes it string
which i dont want
Yeah, so your form is sending data as a string. Are you using WTforms?
But... why do you need that form that you wrote in HTML?
I've explained why in this case it serves 0 purpose
oh its because when I type it receives data
hey, with flask, using <var> and getitng var in def routevar(var): breaks the page! anyone got any ideas?
But... that's the wrong form. You have to render {{form}} and not that HTML form, it serves no purpose. This is what I'm trying to explain, you understand right?
so ill create a whole new html file?
@copper lagoon so you passed a var, did you change the URL to reflect that?
@vernal furnace Why would you create a new html file
then where do I pass {{form}} ;-;
You need to render {{form}} instead of the form you wrote in html
<form action="some action" method="post">
<!-- csrf token usually goes here -->
{{form}}
</form>
clicking nothing happens @app.route("/<log>/<pog>/test") def _45589675(log, pog): return render_template("profile.html") but and same issue happens when i have more than 1 argument
def _45589675():
return render_template("profile.html")```
this works
if i have like /pog/log/test
same output
I don't get you
Do you want me to create a form under the form in my html file
Like
Why are you trying to create 2 forms
One of your forms is invalid
Get rid of it
And replace it with the valid one, {{form}}
I only have 1 form
Ok can you show us the code for your Todo form?
from django import forms
class Todo(forms.Form):
text = forms.CharField(label="add_todos", max_length=255)
Hey @native tide!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Ok, there's one form. You have another which you wrote in HTML (which is the invalid one), so you have 2
Now get rid of the invalid one, and replace it with {{form}}
Bruhhh thats html file
@copper lagoon Tbh I don't know why that doesn't work, is profile.html dependent on log or pog?
If i remove it the text will go to nowhere and it will not trigger the todo_add function
and you passed log and pog into the template as template variables right?
you didn't though
well, if the template is trying to access log or pog and you didn't pass them, it can't access them so it would be an issue
apart from that I actually don't know what could be the issue
might need to see the real thing to grasp what's going on
because from the example that's the only thing I can see.
@vernal furnace so can you explain what you think you need to do at this moment in time?
I don't know, I literally don't understand anything you are saying
You are saying I have 2 forms
Yep.
Well, which do you think is your first one?
Yep, which is this:
from django import forms
class Todo(forms.Form):
text = forms.CharField(label="add_todos", max_length=255)
Then look in your HTML file
You have another form
Paste it
Yeah that's a HTML tag, that represents another form.
And that form which you have in the HTML is not linked to your form=Todo()
<div class="row mt-4">
<div class="col">
<h2>Add Item</h2>
<form action="add_todos/" method="post" class="form-inline">
<label for="add_todos">Your name: </label>
<input id="add_todos" type="text" name="add_todos" value="{{ form }}" class="form-control mb-2 mr-sm-2" placeholder="Jane Doe">
<button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
</form>
</div>
</div>
Yep there's your other form
So get rid of everything between the <form> tags
and replace everything between those tags with {{form}}
and make sure you pass {"form": form} in your context
You need to give these a read and watch a yt video if you don't get it
Get the right form rendered first, then worry about styling
the form you wrote in the HTML will never validate when you say form.is_valid because what you wrote in the HTML is not form!!! it is not a Todo instance!
so that's how it should look?
<form action="add_todos/" method="post" class="form-inline">
{{ form }}
</form>
and add a submit button
<form action="add_todos/" method="post" class="form-inline">
{{ form }}
<button type="submit" value="OK" class="btn btn-primary mb-2">Submit</button>
</form>```
sure
Idk where to type
def todo_add(request):
if request.method == 'POST':
form = Todo(request.POST or None)
print(form)
if form.is_valid():
print("if2")
text = request.POST.get("add_todos", False)
context = {
"text": text
}
print(text)
return render(request, 'todo.html', context)
else:
print("else2")
form = Todo()
context = {
"form": form
}
return render(request, 'todo.html', context)
so wait
Hope you didn't ragequit ;-;
Thank you tbh, you stayed with me 2 hours ❤️
What would be a good data structure with python to capture the directed graph as generated by a moderately sized (less than 10,000 notes) directy graph (let's say up to around 5 edged between any two graphs) wiki database (think of the graph generated by the Wikipedia pages on a certain subject and all its interlinks)?
And so some searching and graph manipulation with it
@native tide ```py
@app.route("/profile/view/<id>/")
@requires_authorization
def seeprofile(id):
user = discord.fetch_user()
name = f"{user.name}#{user.discriminator}"
avatar = user.avatar_url
return render_template("showprofile.html", user=name, avatar=avatar, id=id)```
this is one of the ones that dont work
as u can see, nothing is different here / its meaningless
like the buttons dont work
and i suspect its due to the route
a dedicated graph data structure?
look into networkx
does the amount of "args" in a flask route make a difference?
im having an issue where having more than 1 argument breaks the page, and same with having any variables
@copper lagoon I've never had an issue with multiple variables in the route. One thing that you could try (but probably won't make a difference) is setting the type of the variable.
e.g. ```py
@app.route("/profile/view<int: id>/<path: username>/")
not even that
like i cant even have more than 1 arg in the page
so you can't pass more than 1 variable to your template?
oh, so even if it's static like /path/example/ it won't work?
mhm
that's really weird
but you are visiting the route right? in your logs you get 200 response status' when you visit the page?
yes
lmk if u want pictures
but basically when i press x
and the route is just /poggers/
it works
but when the route is /poggers/something/
it doesnt
and a var is the same as "something" in this way
so it just stops
/ doesnt work
so just / as the route doesn't work either?
Okay yeah I've playfully used networkx before, although I don't know if it can conveniently search things
@copper lagoon Nothing about the route seems to scream "I'm broken", could this be something to do with auth?
ive been testing it with this
def testtestlog():
return render_template("control_panel.html")```
and no route needed
no auth*
look u seem to be really helpful
would you want me to send u the website?
so u can actually see what i mean?
tho i gtg eat rn
ill be back in a bit, want me to ping u?
You could, but I actually have 0 idea why there's such a problem, I've never ran into it before and I couldn't find anything online about it
sure
maybe show the html file to check if there's anything out of the ordinary
well i mean u can just check the inspect element
i can tho
like this
<span class="alert-text"><b>Vanity URL Updated!</b></span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>```
this is the alrt
lemme get u the css
.alert
{
position: relative;
margin-bottom: 1rem;
padding: 1rem 1.5rem;
border: 1px solid transparent;
border-radius: .375rem;
}```
.alert-success
{
color: #fff;
border-color: #2dce89;
background-color: #2dce89;
color: #FDFEFC;
}```
{
padding-right: 4.5rem;
}```
.alert-dismissible
{
position: absolute;
top: 0;
right: 0;
padding: 1rem 1.5rem;
color: inherit;
}```
{
transition: opacity .15s linear;
}```
.fade
i honestly think it COULD be the html
but i doubt it
cuz why would it work with 1 /thing/
but not 2
@native tide
anyone know how to use django
@native tide awesome, can you help me out with a problem im having
i dont think so
every time I try to add image to my html template the image comes up broken
and the css isn't working either. The background image isn't working either
ok have you specified STATICFILES_DIRS in your settings.py
me?
@native tide i have in my installed_app section 'django.contrib.staticfiles',
and at the bottom
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'reviews/static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'imagesite/media')
no i dont
look imma send u it
@dry bridge ok and when you attempt to provide the src for the image, do you do the following:
{% load static %}
<img src="{% static <your_path> %} > </>
alright, could you show us your filestructure?
imma head off for now its midnight so yea
GMT, I'll have a look at this tomorrow, see ya for now 🙂
idrk where to put this, this is probably the channel most closely related, how would you guys go about scraping a html <math> tag, and convert it to something wolfram alpha can understand?
If you're using beautiful soup you should be able to do something like:
results = soup.find_all("math")
that should return a list with all the math tags and u can iterate through it than clean it however u want to work with wolfram
it's preference but here are some good answers https://stackoverflow.com/questions/22841764/best-practice-for-django-project-working-directory-structure
can any of yall help me with selenium
what might be the possible cause for this flask (werkzeug more specifically) error?
CSRF Warning! State not equal in request and response.
I am using the google api, and then after getting the consent from the user, I gonna get the authentication server response on the callback page after the consent screen then this happens
I'm running in development btw
@hybrid bobcat are you sure you using django with domain localhost name match with your google app redirect url?
I’m using flask
Sorry for the late response btw
And also yes, the domain name matches with the redirect uri
hello
I would like to use the django permissions system
class LocalRole(models.Model):
"""
Represents a Local-Role object.
An one-to-one related model with Global role.
Roles have their own:
- Hex Color Code [Integer Representation]
- Name [&]
- Permissions.
Role permissions for individual datasheets override global parent permissions.
"""
objects = RolesManager()
id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True)
global_role = models.OneToOneField('api_backend.GlobalRole', on_delete=models.CASCADE)
parent = models.ForeignKey('api_backend.DataSheet', on_delete=models.CASCADE, db_index=True)
created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)
REQUIRED_FIELDS = [global_role, parent]
so I have this model
this model named role should have permissions
and these roles should be given to user
class GlobalRole(models.Model):
"""
Represents a Global-Role object.
Roles have their own:
- Hex Color Code [Integer Representation]
- Name [&]
- Permissions.
"""
objects = RolesManager()
id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True)
name = models.CharField(max_length=512, db_index=True)
hex_color_code = models.IntegerField(db_index=True)
position = models.IntegerField(db_index=True)
parent = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, db_index=True, editable=False)
created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True)
REQUIRED_FIELDS = [name, parent, position]
how can I implement this?
can somebody please help?
thanks a lot! please ping me when help
this is my code for my first diashow, i want to create more than one diashow how do i do it
<button>
<a href="home.html"><img src="../images/logo/the_rationals.png" width=50></a>
</button>
<h1><strong>The Rationals</strong></h1>
this is my code, and
this is the result, is there a way to make it so that The Rationals would appear beside the picture
i know how to use beautifulsoup, i meant to ask if there was some way to convert it to actual math markup, beacuse if you just use get_text() something like x^2 will look like x2, because of the way the math tag works. Thanks for answering tho
@granite loom make the image an h1 inline elements
anyway this could be inverted?
add the image before h1 in html
So I've got two models structed like:
class DataSheetsCluster(models.Model):
"""
Represents a group of datasheets made by the owner.
Has it's own icon, name and description.
A parent can only have one owner at a time.
"""
class Meta:
permissions = [
('GLOBAL_READ_DATA', 'can read cluster data'),
('GLOBAL_WRITE_DATA', 'can write to cluster'),
('GLOBAL_MANAGE_CLUSTER', 'can manage cluster'),
('GLOBAL_MANAGE_FIELD_DATA', "can manage cluster's field data"),
('GLOBAL_MANAGE_DATASHEETS', "can manage cluster's datasheets"),
('GLOBAL_MANAGE_ROLES', "can manage cluster's roles"),
('GLOBAL_MANAGE_FIELDS', "can manage cluster's fields")
]
...
roles = models.ManyToManyField('api_backend.Role')
...
class DataSheet(models.Model):
"""
Represents a single dataSheet.
dataSheets have their own model at the core. Model data is added to
the dataSheets in the form of separate records.
"""
class Meta:
permissions = [
('LOCAL_READ_DATA', 'can read datasheet data'),
('LOCAL_WRITE_DATA', 'can write to datasheet'),
('LOCAL_MANAGE_FIELD_DATA', "can manage datasheet's field data"),
('LOCAL_MANAGE_ROLES', "can manage datasheet's roles"),
('LOCAL_MANAGE_FIELDS', "can manage datasheet's fields")
]
...
roles = models.ManyToManyField('api_backend.Role')
...
I want to make sure that the DataSheet model's roles field reference the DataSheetsClusters model's roles field, like a foreign key. How can I achieve this? Can someone please help me?
Thanks a lot!
hey I am trying to get a user's info with flask , well I read the discord's oauth2 docs & some stackoverflow and I somehow managed to get the access token from discord. Now I want to know how to fetch the user's data now with that access token. I couldn't find anything about how to fetch user object with the access token so I am completely struck here and Idk how to proceed .
Here's the code
from flask import Flask, render_template, request, session, redirect
from config import *
import requests
app = Flask(__name__)
API_ENDPOINT = 'https://discord.com/api/v6'
app.config["SECRET_KEY"] = "ac1bf18a8db34e15c2dba713802b347e89625413c4a31e53"
@app.route('/')
def homepage():
return render_template('index.html', url=oauth_url)
@app.route('/callback')
def callback():
code = request.args.get('code')
data = {
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri,
'scope': 'identify'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('https://discord.com/api/v6/oauth2/token',
data=data, headers=headers)
r.raise_for_status()
session["token"] = r.json()["access_token"]
return redirect("/dashboard")
@app.route("/dashboard")
def dashboard():
return render_template('dashboard.html', )
if __name__ == '__main__':
app.run(debug=True)
if its off-topic here , please direct me where should I ask about this
#web-development can anyone help me with roadmap
Hey so
@import url('https://fonts.googleapis.com/css2?family=Lato:ital,wght@1,300;1,400&display=swap');
* {
box-sizing: border-box;
padding: 0;
margin: 0
}
body {
font-family: 'Lato', 'sans-serif'
}
this is my css, but the font isn't changing why is that?
The link you have is not the same as the one Google provide for @import
You misspelled weight also? Never imported text but if you can assign weight in the URL might have to do with that.
Might want to hide your secret key first no???
thats not a secret key thats just a random string I generated
Ah ok
uh yes it is
@import url('https://fonts.googleapis.com/css2?family=Lato:ital,wght@1,300;1,400&display=swap');
my link
Thanks 00kem, your link helped a lot!
Does anyone have experience setting up an environment with flask and react, where react is precompiled to a static folder? I'm having issues setting up the react part
hey how to remove the white spaces?
This was cause because of css, but i have a class for that logo only, but idk how to remove those white spaces
Hi, how would I be able to wrap my check if user has access to document in a decorator ?
@documents_bp.route("/documents/<doc_id>", methods=["GET"])
@jwt_required
def get_one_document(doc_id: int):
try:
document = Document.get_by_id(doc_id)
except Document.DoesNotExist:
raise NotFoundError("Document not found.")
if not document.owner.email == current_user.email:
contributor_emails = [
user.email
for user in (User.select().join(DocumentContributors).join(Document).where(Document.id == document.id))
]
if current_user.email not in contributor_emails:
raise UnauthorizedError("User doesn't have access to this project.")
@compact lion did you use create-react-app?
yeah, but I'm trying to turn each .jsx file in this folder into its own .html file @native tide
why would you want to do that? you're having an MPA with react?
Well, we'd like to just have all files serverside-rendered, and running both flask and react servers would create another connection where things could break
Ok, but I don't think turning each .jsx file into their own .html file is how it works. Can't you just have a <script> tag in your server-side templates to have some React components in your templates?
You can just npm run build and then CRA will webpack your static files and then your backend can serve your index.html
Then the rest is handled by your frontend, like an SPA
Also with an SPA you aren't hosting your backend and your frontend separately, you just use your backend as an API. It's not really an extra connection which might break unexpectedly.
Hello, how to find with selenium the element, who's xPath changes everytime.
<button type="submit" class="wbutton btn btn-dark rounded-0 font-weight-bold p-2"><i class="fa fa-video-camera text-danger fa-lg"></i> 808</button>
Please someone explain what is happening here:
print(user.active)
user.active = True
print(user.active)
first print is false, second print is true, but the database still shows false..... what am I doing wrong?
your not saving it to the database
depending on what you are using for your program there will be probably be some save function to save it to the database e.g. user.active.save()
I am using django, Thank you so much, works now
np
I need some help with django: I'm getting this error "NOT NULL constraint failed: homeworkApp_homework.object_id". I have a homework model that has a generic relation with a student model. I created a homework form from the model and am now trying to save it. I have this piece of code in the views ```python
form = homeworkForm(request.POST)
if form.is_valid():
#This tells the homework which student to relate itself with
form.cleaned_data['content_object'] = request.user.student
form.save()
do you have a student column for your User model?
no but it is a onetoonefield
i have modified the abstract user
ok, and did you set that model as your DEFAULT_USER_MODEL?
for web dev do i have a choice in between java script and python
you do
at least for the backend
for the frontend, you dont have much of a choice
most people usually end up using javascript
okay, thanks
is it possible to do single checkbox using wtforms?
i made a widget for multi check box already
is this for django
you know the way in django when you get a group of objects it returns it like this "<joe: joe1>" how does one remove the <> and joe bit
You can access the field on the model and print that
@modest scaffold sorry I forgot to reply to your issue, did you get it fixed?
@compact lion CRA is not what you want then, there are other packages to deploy react that will achieve what you want, just that it's not the norm not much documentation and I haven't tried it and others prob haven't either.
@native tide you ever got to use Session Storage in Django with React on the DB instead of using Cookies?
@haughty turtle Nope, you mean cookie-based sessions?
Yeah last time we where talking about Django using the default of DB stored sessions. Said you where going to look into it, seeing that with React I have to route my login from React to Django was wondering if you ever got to it.
Ah, no, I don't really fully understand it at the moment but I haven't looked into it that much. Rn I'm stuck on understanding the difference between session-based and token-based authentication. I think that session-based auth is just token + session information in a seperate cookie. Or something like that
I just used token auth for all of mine and it works fine
<select type="text" class="form-control" id="bot" name="bot" required>
<option disabled value="Select a bot..." selected hidden>Select a bot...</option>
{% for x in bots %}
<option type="text" value="{{x.name}}">{{x.name}}</option>
{% endfor %}
</select>
``` Is there a reason the select is not required?
Even with the required attribute
I don't see any reason for that. Try to remove the options and dynamic parts and adding one by one to see if you can figure out what is causing the problem
I don't know whats causing it
I remove the Select a bot... and its fine
No values fill up an option neither since theres no valid bots
@verbal snow Just a thought, I'm probably wrong, but would selected auto-select an option before the page loads, therefore making the select always required?
In django, does anyone know a trick to reboot a server?
i.e.
class MyModel(models.Model):
...
def save():
...
restart_server()
I've got a model who has fields in admin that show/hide depending on the status of another model. The fields in admin only update upon reboot. Maybe there is another trick?
via api with subprocess?
@modest scaffold sorry I forgot to reply to your issue, did you get it fixed?
No but it's fine
example I have the following models, and I want to parse 3 jsons with the following structure hhttps://dpaste.org/1zf2 ,and populate data over api or other without user interaction
...that sounds like an antipattern
you mean in production?
I don't think you can from within Django
i am trying to put this into html with flask, anyone know how ?for i in how_many: guess = input(f'input your '+ str(i) +' guest: ') for j in guess: your_answer.append(j) for l in range(0, len(your_answer)): your_answer[l] = int(your_answer[l]) @ me if you do please
can someone please help me? thanks!
does anyone know flask?
hello, you can pass variable to template by using render_template() function of flask https://flask.palletsprojects.com/en/1.1.x/quickstart/#rendering-templates
is there away to save input from html into a variable in pyhton flask
yes if you read the part about request data in the link above https://flask.palletsprojects.com/en/1.1.x/quickstart/#the-request-object, you can get data from html by using input in form
I am trying to migrate migrations in django, and its trying to migrate the initial migration file
Which obviously Errors
Even though i have 43 migrations https://i.adiscorduser.com/vhHtTN5.png
can you post the error traceback?
Hello!
So I am creating a roles and permissions system in django. I think that I need some help here,
So the basic concept is that:
-
there are objects known as clusters
-
clusters can have their own roles
-
members of the cluster are assigned roles.
-
roles also have a positional value,
smallest positional value indicates highest role. -
based on this certain permissions are determined for the user [member]
I have implemented this a bit roughly, and think that I can improve a lot, maybe am using the wrong logic here.
here's my backend code:
https://mystb.in/JamaicaInclFinal.python
here are my models:
https://mystb.in/EthicalAlertWhom.python
the roles system is very similar to discord roles system.
So I have an object called cluster - referred to discord server
and an object called datasheet - referred to as discord channel
Datasheets have their own role overwrites too [role overwrite object given in above link], which can overwrite the permissions the roles have at cluster-level.
The main thing here is that for the positional value, each role can have only one unique positional value in its parent cluster.
so for every update to role positions, I am rotating the whole role positions for every role in the cluster [given in code link]
Is this the best way to go about this? can someone pls help me?
its going to take sometime to read my code, if you are willing to spare that time and help then thanks a lot!!
if you have question about sql then #databases is a good place to ask
can someone pls help me
@twilit needle someone will help you if they know the answer
okay
how to get started on flask
@native tide flask has it own tutorial https://flask.palletsprojects.com/en/1.1.x/tutorial/
k
for flask and sqlalchemy, is there a standard way to serialize sqlalchemy object to return a dictionary?
basically i performed a query, and want to get the output as a dictionary to send back as JSON
@api.route('/send_dummy_data', methods=['GET', 'POST'])
def send_dummy_data():
data = request.json
print(data)
# data_query = db.session.query(CableResistance).filter_by(size='12').first()
data_query = CableResistance.query.filter_by(size='12').first()
pdb.set_trace()
return jsonify(data_query)``` something like this
where CableResistance is a sqlalchemy database model
if you are using sqlalchemy i suggest using marshmallow for serialization of data https://marshmallow.readthedocs.io/en/stable/ it's really stable i used it for some of my projects already
basically you write a schema for the serialization
@gaunt marlin i am suprised sqlalchemy doesn't have a baked in solution already
you can just jsonfy the objects and it would still would(just take more time to do). That why i suggest using marshmallow because it ease the pain of converting
i got an error when I tried to just use jsonify directly on the object
unless i was supposed to use it on a class attribute or i am just missing something
what is the error?
@grizzled meteor i think because you using filter it will return a list and that can't be jsonfy, you have to access index 0 of that list first
i did not realize the filter returns a list
and i also did not realize i cannot jsonify a list
good to know
TypeError: Object of type CableResistance is not JSON serializable
this was the error so that kind of lines up what you're saying
is 0 of that list; the first column in the "row"?
can you print out the query result?
so it's not a list but a class
yeah
from flask_sqlalchemy import SQLAlchemy
from .database import db
class CableResistance(db.Model):
__tablename__ = "CableResistance"
id = db.Column(db.Integer(), primary_key=True)
size = db.Column(db.String(8))
conductor_material = db.Column(db.String(2))
conduit_material = db.Column(db.String(5))
reactance = db.Column(db.Float(precision='5,3'))
resistance = db.Column(db.Float(precision='5,3'))
jsonify is only use when you set the attribute for example jsonify(name="abc", description="a") because it's a wrapper of python json.dumps()
ah, i see
@grizzled meteor try this instead
from flask.json import dumps
....
#other codes
...
return dumps(data_query)
flask.json.dumps(obj, app=None, **kwargs)
Serialize obj to a JSON-formatted string.
same error, was expecting that though
that is why you should use marshmallow for serialization, if you look at these answer it's hard to do it manually https://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask
I'm trying to jsonify a SQLAlchemy result set in Flask/Python.
The Flask mailing list suggested the following method http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-
the top answer even suggest it 🙂
for single instance of class one of the answer
def serialize(self):
return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
for the class itself, for list query you have to write different implementation :/
actually marshmallow is really easy to use
the docs is not that long to read either
Hello!!! I want to start learning about interactive web, particularly with python. Any advice to begin? Or maybe sources like a YouTube channel or learning web?
Anyone here good with Shopify dev?
anyone know a website that provide free icon to use for website?
I have found some but they afraid to use them cause of copyright
Are you talking about general icons like bookmark icon, add icon or like/unlike icons?
If yes, you can use materializecss or fontawesome icons in websites. They have plenty of options with simple implementation.
Materializecss- 'https://materializecss.com/icons.html'
Font awesome- 'https://fontawesome.com/v4.7.0/icons/'
If you were not talking about general icons hen please elaborate your question :)))
what i cant to import requests?
@native tide Have you pip installed it?
Yeah I thought it was standard at first too 🤣
with how common is it. You would think.
thx
Yeah me too lol
Ikr I am glad I am not the only numpty 🤣
Hey guys so if I have a navbar for my project, and it is made with css and html only.
Is there a way to apply that navbar to every single page, without copy pasting it?
no, the entire website is html and css only
You can use includes to reduce how much you have to edit, but I don't think html supports a way to extend html files the way you want.
That's why Django, for example, has templating that allows for extending a base html file.
shouldnt the equal sign after navSlide be purple?
if its not does it mean its not properly defined?
i'm using vscode insider
can i use morethan 1 form in a view
yo, has anyone else also faced a problem with their postgres db when trying to migrate the migrations on a custom user model for a new project?
I just keep getting this and apparently, no relations get created in the first place
this is the error I get when trying to create a superuser
p.s this is django
my custom user model is pretty simple rn
How can i execute a python script on click of a button in flask ?
basically i want a page where it shows all the python scripts
a user can select the script he wants to run
and the result of the script execution should show up on another page
While i can get he other pieces, but how should i tell flask to run another python script on button click
I see a lot of results telling to use AJAX but i can't understand it
can't i keep it pure python ?
the route function should call another function that processes the python script that user selected And returns a result which is further returned to the render template and the result is showed to user
@require_GET
@discord_.login_required
@utils.route(["user/me/", "user/me"])
def user_page_self(request):
``` So I have 3 decorators on a function, however, the route for some reason has to be on the bottom to get the function name, but that causes login_required to not even work. Im so confused. This is in Django.
Why are the difference in WTForms between
wtforms.form.Form.formdata
To
wtforms.form.Form.data
?
I am trying to make a form that has a dropdown menu in Django. However, the labels for the form are not what I want. How can I choose what comes in the labels? (I am using Bootstrap)
Forms.py:
class BookForm(ModelForm):
class Meta:
model = drones
fields = ['origin', 'destination']
widgets = {
'origin': forms.Select(
attrs={
'class': 'my-1 mr-2',
},
)
}
Models.py(Origin):
origin = models.ForeignKey('locations', models.PROTECT, null=True, related_name='destination_id')
Models.py(Locations model):
class locations(models.Model):
id = models.AutoField(primary_key=True)
location = models.TextField()
The labels I get are as follows:
locations object(1)
locations object(2)
...and so on
However, I would like the location's name. Their name is also stored in the location model.
So you want origin.location as your label?
