#web-development
2 messages ยท Page 126 of 1
yes, but at some point, you converted stuff in memory to be saved to the big CSV, yes?
I actually wanted to read the csv file from the javascript. But the javascript refuses to find my csv file, whereas my python(flask) can find it and "send" it to my javascript
that stuff in memory is still there right after you save to the big CSV. so filter that one down to the two columns you need and save again.
javascript in browser shouldn't be accessing local files
that's kinda dangerous, if i send you a malicious javascript file, i guess where the file is downloaded and make your browser open it
correct. So in summary you recommend to filter the historic data and filter the current data so it can be directly used for the chart and be saved at the same time right?
oww ok good to know. You are a treasure
oh, lol, we need to keep these things separate
we're going to get confused if we mash everything together
step 1: save all data into two CSVs every time we hit the API, one complete CSV and one smaller CSV with only the data the javascript needs.
step 2: separate CSVs that have already been loaded (I'm assuming that's what you mean by historic data) and CSVs that haven't been loaded (current data?) to send even less to the javascript
Yeah so the javascript receives the historic data at once and the loaded data immediately. That's what you are saying right?
So then you don't have the issue of sending the CSV file again and again
i mean ... i think your first step is to try to load the full (two column) CSV every time first
let's get over that hump first ๐
there are many many ways to optimize it after that, but maybe that should be your first step
see what the performance is
imagine if your two column CSV goes from 50mb to 50k
you're not really going to worry about 50k
even 500k is like, well. not too bad.
I agree haha, I just need to make the chart work before I refactor the rest
if i was doing it, i would probably get that working first
even if it's a proof of concept
plenty of time to optimize after it works
Yeah so that's what I'm stuck with for days hahaha
And strangly enough I cannot find a preceding project that uses something similar
Which is weird
Thank you so much for educating me on the databases
no problem, that's what we're here for ๐
if you're a super keener ... you might be interested in the big three frameworks: react/angular/vue
Vuejs is usually regarded as one of the easier to learn libraries (of the three)
what it can do is reload (the entire CSV) on a timer, and if there's a change, they will update the chart
but ... it's going to be a bit of a rabbit hole, and i don't know how much time you have
That's a wicked idea and would love to learn it eventually but I unfortunately don't have much time anymore. My main goal is to get dots plotted on a chart at this point... hahaha
yeah. no problem ๐ thought i'd throw it out there in case you're interested
what is the difference between odoo framework and django ?
Idk why it gives me templatedoesnotexit error in Django
here's how the folders are arranged https://gyazo.com/60e01c65dc3344fc585ef84dca213f13
@vernal furnace how are your templates setup?
You need to remove 'base/' from your template name.
It gives me this error now https://gyazo.com/e9b054f40e1a07db868e7f6796d1de9f
even tho im not rendering it
Replace "base/base.html" with "base.html".
I don't have anything like that whatsoever
There is no directory called 'base'. You are telling Django that your template is in the 'base' directory.
This is why you are getting a "TemplateDoesNotExist" error.
I'm not telling django anything tho
That's all I have in my views.py https://gyazo.com/4e441cc45e49d00aa431842eb395e30c
Refresh the web page.
Yeah the same thing happens
Create the 'base' directory inside the 'templates' folder. Then move both .html files into the 'base' directory and return to the origin code: return render(request, 'base/home.html', {})
No problem! I've only worked with project-level and not app-level templates so apologies for the initial confusion!
how do I get rid of html elements in a list???
what's the difference between Apache, Nginx, and Gunicorn?
Not much but a friend of mine prefers Nginx over Apache due to functionality
@native tide Maybe D3 would help? It's a JS data-visualization library which can create all sorts of graphs.
and you can load .csv
Thanks @native tide I also just found something similar called Papaparse
Cannot get it to work either
Never heard of it tbh, but I do know that D3 is very popular and should have lots of writeups on stuff you are encountering.
thanks, will look into it
If you want to show/hide HTML elements based on variables/state, look into some frontend frameworks. React is good
How can you remove html elements with react?
By manipulating the DOM
You can also do it in vanilla JS
I'm trying d3 now @native tide but I get the same problem again. My file is not found... error 404
Could it be because the file you're trying to access is relative to your .html file's location? It doesn't seem like your path is.
looks like your cwd is higher than userinterface
is projects the top level file
like this
nope it's DT
is python serving the file or r u just clicking the html
Ehhhhh, so how do I do it relative to the index.html file?
I'm using a javascript command to read csv data inside an html file
I basically run the website I made locally, then look at the console through inspect
but how are you running it
I'm using pycharm
So basically I run the app using flask which gives me a link to the local website
Does that answer your question? I'm sorry I'm a real noob
First time using flask
So by running a python file, I'm running a server locally that hosts my website. And then I just edit the scripts, refresh the browser, check the console
Do you think my file is badly positioned?
i think it's pycharm running it at the top level
import os
print(os.cwd())```
put that at the top of your file
of which file?
and send here what it prints
the main file
of python
hmm interesting
oh wait
in your file for the csv
remove the userinterface bit of your path to the csv
/ltc.csv?
Accessing it relative to the .html file, I don't know if it is though! https://realpython.com/absolute-vs-relative-python-imports/
it's looking for C:/Users/alaed/Google Drive/Subjects/Minor CS/DT/project/userinterface/userinterface/ltc.csv
also it's trying to get flask to serve the file
in which case it needs to be in your static folder i believe by default
Failed to load resource: the server responded with a status of 404 (NOT FOUND)
send a ss of the browser terminal
what needs to be in the static folder?
When I run the code git init in my console to put it inside my workspace in VS code, it says 'git' is not recognized as an internal or external command, operable program or batch file. Do I need to download something? I'm on Windows 10.
Thank you so much @quick cargo and @native tide
ahhhhh makes sense but what if I keep updating my csv file. Does that make it dynamic?
@quick cargo can u help me with my error?
yeah you'll wanna installgit
Have you installed git
doing so rn
just follow the install, if it asks if you want it in PATH say yes
it might do it by defualt though and not ask which is fine
it worked, thanks!
then you should be able to a) use git bash which is a better cmd and then use git
@native tide sweeeeeeeeeeeeeeeeeeeet d3 csv is now finally working
OMFG
I've been working on this for over a week
You guys are saints
thank you so much
๐
How can I select the first child of an element only if that element is of a certain type in CSS?
This is not the same as :first-child or :first-of-type as far as I can tell
The element must strictly be the first child overall, not the first of a specific type.
I need to check the type after I select the first child
./manage.py startapp tweets just doesn't create anything. Anybody got a solution?
Hmm wait I think it just just div:first-child lol. Need to play around with it more
anyone know why this is my api response?
{
"detail": "Not found."
}
not getting a 404 page, just that as a response
i guess if you have 2 slashes in your router url it doesnt work, but only 1 slash works. makes zero sense
how does Django know which html template file to use for each class based view?
checks template_name
anyone know why im getting a method not allowed on an axios.post? i know it works from postman. thats how i got my first 2 messages into it. so i know its not a backend issue
maybe this will help you https://stackoverflow.com/a/46836144/11225821
i think you need to enable CORS on your backend
cors is enabled
no, i have a prebuilt header script for all posts containing the token and the content-type to application/json. it just doesnt make sense. ive being looking at every other post request both front end and backend. everything matches. and i supplied the same headers to postman and used the exact same data for both. it just doesnt make any sense
what in the hell, maybe its just node.js being slow compiling again. reset it all back to what i had originally after trying a few things and it works now ๐
hello guys, I want a Django projects to contribute to? any suggestions?
can someone please help me here?
thanks a lot!
please ping me when help or there
Can someone explain how can I populate a WTForms FieldList using Flask?
I tried the google answers but I have a strange thing happening
I make sure to delete the previous data of the form and then change the data to the new data but it just reverts back to the old data even though when I check after the "Delete" it is delete and nothing exists there
@app.route('/whatever', methods=['GET'])
def whatever():
return render_template('/whatever.html', email='dskdkj@gmail.com')
{{form.email(value=email)
Um not exactly what I meant
I have a fieldList of Selects
I saw how the .data is looking like
maybe you want to use querySelectField to prepopulate the select fields
I have separated model file and using app factory. The project structure is
like this:
project/
|-- config.py
|-- core.py # app factory definition which calls db.init_app(app)
|-- database.py...
This is my site
it's a schedule of school clases
I have buttons and selects to choose a grade and a class
that when GETing the site (I set it to default pull from the first class) it works great
but when I use the buttons to choose a class the functions get all the correct parameters and the correct data is recevied form the DB but it just doesn't update it
I'll try the queryySelectFioeld
I'm not sure I understand how to use this QuerySelectField
Let me give an example
lets say you have a class for the classform, and you have a selectfield, queryselecy will query the database, and use the result as the selectfield options
i'll help in ten mins if you're still struggling, g2g
ty
I'll try that
my database is a remote Firebase database and I'm getting my values as a string
it says this is for django and I'm using Flask
django seriously frustrates the crap out of me... lmao
same here with Flask and WTForms
create a function to query the db, add each string to a list
then use query field on the classform
{'TwoDTable': [{'Lesson': 'ืื ืืืืช'}, {'Lesson': 'ืกืคืืจื'}, {'Lesson': 'ืืืื_ืืฉื ืืช'}, {'Lesson': 'ืืื ืื'}, {'Lesson': 'ืืื ืฉืืขืืจ'}, {'Lesson': 'ืชืื ืืช ืืื ืื ืขืฆืืื'}], 'changed': None, 'submitToDB': False}
That's my pulled data
I tried to make it the same as the .data of the form
This is it nah:?
so you can call the function with required paramters, and get the result as a list
That is the pulled data
brother, I've just told you what you need to do...
I didn't understand that sorry ๐ฆ
right, so this is the pulled data:
{'TwoDTable': [{'Lesson': 'ืื ืืืืช'}, {'Lesson': 'ืกืคืืจื'}, {'Lesson': 'ืืืื_ืืฉื ืืช'}, {'Lesson': 'ืืื ืื'}, {'Lesson': 'ืืื ืฉืืขืืจ'}, {'Lesson': 'ืชืื ืืช ืืื ืื ืขืฆืืื'}], 'changed': None, 'submitToDB': False}
And you only want the lesson name to appear in the select field, right? Like ืื ืืืืช
I want it to be selected
but when you click the select it will have the other normal options
how do I provide the QuerySelectField is the dataset?
IntegrityError at /api/comments/
NOT NULL constraint failed: web_comments.post_owner_id
Request Method: POST
Request URL: http://127.0.0.1:8000/api/comments/
Django Version: 3.1.4
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: web_comments.post_owner_id
why am i getting this? im supplying everything it needs... the post owner id matchs to something in the database its linked to. i dont understand. ive tried multiple different things and end up with different errors everytime
{
"post_ref": "5",
"user_comment": "2",
"post_owner": "1",
"comment": "Such a pretty place to visit!"
}
``` data submitted through postman
can someone please help me here?
am stuck with this for two days...
https://stackoverflow.com/questions/65626527/valueerror-cannot-assign-integer-to-foreign-key-during-put-request
thanks!
its not post owner id. thats the foreign key. the model name is post_owner links to id in profile.
well your error is saying that table web_comments is missing a post_owner_id as part of the lookup and failing the constraint
its saying that it doesnt exist in the Profile table i think, not that its actually missing. it has to do with ForeignKeys, not a simple post query
class Comments(models.Model):
post_ref = models.ForeignKey(Posts, related_name="post_ref", on_delete=models.CASCADE)
user_comment = models.ForeignKey(Profile, related_name="commenter", on_delete=models.CASCADE)
post_owner = models.ForeignKey(Profile, related_name="poster", on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
comment = models.TextField()
``` thats the model
it isnt null though, theres a profile row with an id of 1 and 2... i know for a fact
why? i didnt change anything, just seperated it into its own app instead of being apart of the main app without changing anything else and works like a charm now...
Having trouble with using comparison operators on a jsonfield, like json__count__gt=1000 - it returns nothing, I believe it may be evaluated as string somehow.
.Packages > * .dark-mode {
background-color: black;
color: white;
}
i cant seem to get the color switch working
anyone here?
how to place an element a a particular place?
you mean using css ?
yes
Take a look into the position propery.
if you want to place a element respective to the window., you can you position: fixed and change the left, right, top, bottom attribs
ok
or use position: absolute if you want to change the position respective to a non - static positioned parent elelment.
actually I need to place an image
.mic{
color: white;
width: auto;
height: auto;
top: 10vh;
margin-left: 200px;
margin-top: 50px;
position: right;
}
```this is what I have
the image is not moving when using this
try position: fixed;
.mic{
position: absolute;
width: auto;
height: auto;
left: 300px;
top: 270px;
}```this?
works but what if I resize the screen?
it stays there
does position: fixed; work for you ? it places elements with respect to the screen.
the element won't change position even when you scroll the page
Is there anything about Django here?
@primal sonnet Yeah, you have a question about it?
Yes
Sure, go ahead and ask
So the scenario is like this. Iโm trying to build this website for the college club.
I wanna know how to structure it. Are โAppsโ supposed to be pages?
@primal sonnet apps are essentially different parts of your entire application. Think of them as individual pieces of a puzzle. You can have one app deal with the dashboard, another for user accounts/logins, etc.
It's just a way of splitting up your project into different sections
I see.
Just one more thing
Could you suggest any resource to help me dig into django further ?
The only way I learn new frameworks is making projects
I will read about the framework, watch some youtube videos about it to know what's possible
I'll say "I'm going to create such a project"
And I will just research, learn, and create
Nut, Since when did u learn Django ๐
I'm still learning it I'm a noob tbh
I started a few months ago
Then learnt React because of it
how do you put a label inside a django widget?
you need to set placeholder on the formfield
is there a way I can do that for a TextField?
I got unexpected keyword argument 'label'
can I see what you're writing?
I don't think you need the label argument
anyway
and use widget.Textarea
guys I have a doubt in making of a zoom clone
My host camera is working, but when I'm connecting with another device for the same meeting, I can only see one
what should I do?
This is my form```py
class CreateNewShortURL(forms.ModelForm):
class Meta:
model=ShortURL
fields = {'original_url'}
widgets = {
'original_url': forms.TextInput(attrs={'class': 'form-control'})
}
@indigo kettle โฌ๏ธ
Are you sending the video?
Hello, I have an error in a module (quart_discord) that I did not have before. I am using python3.8. Here is the error:
>>> %Run test_app.py
* Serving Quart app 'test_app'
* Environment: production
* Debug mode: True
[2021-01-08 21:08:54,303] Running on http://127.0.0.1:5000 (CTRL + C to quit)
[2021-01-08 21:08:57,498] ERROR in app: Exception on request GET /
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1862, in handle_request
return await self.full_dispatch_request(request_context)
File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1887, in full_dispatch_request
result = await self.handle_user_exception(error)
File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1104, in handle_user_exception
raise error
File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1885, in full_dispatch_request
result = await self.dispatch_request(request_context)
File "/home/pi/.local/lib/python3.8/site-packages/quart/app.py", line 1933, in dispatch_request
return await handler(**request_.view_args)
File "/usr/local/lib/python3.8/site-packages/tests/test_app.py", line 25, in index
if not await discord.authorized:
File "/usr/local/lib/python3.8/site-packages/quart_discord/client.py", line 184, in authorized
async with await self._make_session() as discord_:
File "/usr/local/lib/python3.8/site-packages/quart_discord/_http.py", line 93, in _make_session
return OAuth2Session(
File "/home/pi/.local/lib/python3.8/site-packages/async_oauthlib/oauth2_session.py", line 91, in __init__
self.auth = lambda r: r
AttributeError: can't set attribute```
I know this is not an error of my code because even the given example with the correct information does not work. The error occurs when an interaction with discord occurs.There was no error before (operating system reset)
Let's say you have a client (be it a person, artist, org or small shop) who is interested in having a website for him on the internet, something basic with html, css for example, maybe 2 or 3 pages maximum or a landing page Who wants nothing more than to have visibility, provide access to their social networks and direct contact, is it also good to follow all these practices, for example the creation of a userflow?
does anyone know a way to load a chunk of html from another file using flask/jinja? i have all my files already made, but when i make a new one i have to update my navbar every time. i was wondering if i could insert the whole value of my navbar.html inside a certain location of another html document
<!-- navbar.html -->
<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
</a>
</div>
<!-- homepage.html -->
<html>
<head>
<title>homepage</title>
</head>
<body>
<!-- navbar.html goes here -->
<p>content of home page blah blah blah</p>
</body>
</html>
{% extends "layout.html" %}
So put navbar.html instead of layout in the files you wanna use your navbar in, at the top of the page
sry wrong channel
does building a website cost money?
does building a website cost money?
@elder girder you mean the code?
not unless you pay someone to do it for you
or do you mean hosting?
then it depends on how good a plan you want
certainly there are free hosting plans
thank you!
can someone please please please help me
am stuck with this for 3 days now
please...
It would mean a lot for a solution...
how do i download folium in python?
guys I fixed it!
Hope someone can also find the answer and not waste their time like me.
here it is...
https://stackoverflow.com/questions/65626527/valueerror-cannot-assign-integer-to-foreign-key-during-put-request-lookup-fie
hiii
Stop Pinging Me
I'm trying to use a | list filter to transform a generator to a list but for some reason I get a very weird error
jinja2.exceptions.TemplateRuntimeError: no test named 'ืื ืืืืช'
that in the line {% set removedChoices = removedChoices | list %}
removed choices is define as a generator created using | reject 'ืื ืืืืช' is what the value of the the generator is suppsoed to give
I'm really new to Flask, Jinja2 and WTForms overall but from what I seen it's not supposed to use tests?
is my terminal facing reading issues or what
I'm in the process of making a youtube download-er which uses PyTube and want to host it on a web server. But the issue is that I have clue what would be the most cost effective way of downloading the videos from Youtube and then allowing the user to download the video on their end, all with not using a ton of storage and bandwidth as paying for hosting isn't quite an option at the moment.
Using Django as my framework
can someone please help me here?
https://stackoverflow.com/questions/65642067/django-check-contraint-boolean-expression
thanks a lot for your time!
How do i use the | list filter in Jinja2
In my JS file I am grabbing the cookie value but its null, in order to send a CSRF to Django
getCookie = (name) => {
let cookieValue = null;
console.log(document.cookie)
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}``` of course its returning a null value to Django and in Django when using a POST request I get `Forbidden (CSRF cookie not set.): /filter/
[09/Jan/2021 07:45:24] "POST /filter/ HTTP/1.1" 403 2864` This worked fine for me exactly as code was before, but I transferred my Django files to a different PC and now its returning me with this problem
Ah upon further reading as I am using React+Django, React rendering my page thus my CSRF cookie is not initially provided on render as no contact with Django has been made. Have to set this initially on set up if none set...
I'm struggling with WTForms and jinja2
{% set removedChoices = template_choices|reject("eq", template_previousSchedule[6 * (hour - 1) + day]['Lesson']) %}
{% set removedChoices = removedChoices | list %}
{% set newList = [template_previousSchedule[6 * (hour - 1) + day]['Lesson']] %}
{% set currentChoices = newList + removedChoices %}
{{ template_previousSchedule[6 * (hour - 1) + day]['Lesson'] }}
{{ template_form['schedule'].TwoDTable[6 * (hour - 1) + day](default=currentChoices)}}
I'm trying to place select fields from a field list and set each one's default to some kind of element but I don't understand how to do so
is there something like document.getElementById from JS in Python using Flask?
I do not think that Jinja is meant to interact with the DOM is it
then how can I do it? I'm trying to set the selected of every select field based on some data
Use Fetch to send a request to your server in JS to do what you want based on the data the server sends
is there no way to do that in Python?
Hi I need help in django models. In which user can add Ingredients of the Dish by three ways - by images(can be multiple), by blog link, and can add manually by text(it also can be multiple ).
User can add any one way of three.
guys why is command error
const socket = io('/')
const myPeer = new Peer(undefined, {
host: '/',
port: '3001'
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
socket.on('user-connected', userId => {
console.log('User connected' + userId)
})```
this is the full code
Hey guys! Not 100% sure where to put this, but basically this is what I need help with:
I am making a program that can tell me whether an item is in stock or not on the IKEA website by checking the color of a pixel on the screen. My question is; Is it possible to somehow only grab the pixel color of a window instead of the whole screen?
hello everyone
@lilac lintel If the stock indicator is a html element such as a div you can access its background color
then you can determine whether it's in stock or out of stock
@lilac lintel You could probably use Selenium for this
and then access the DOM element, and find its background color
You can use requests and download the HTML. Then you can use XPATH to target the specific element.
What database are you using?
PostgresQL
After a quick google search, you could add a FileField() to the Dish model for images. You can use a CharField for the text and hyperlink.
It can't be stored in the same field as they're different data types.
I know it but I need to use only one way. I can upload multiple images for ingredients or a single blog link or by manually typing the multiple ingredients ingredients. I need a perfect models structure for it.
So you're only allowing 1 option and not all 3?
There's way of doing this... Iโm unsure what is the most โperfectโ way โ which often leads to over-engineering and never solving the problem. But, for your scenario, you could have a CharField (in the Dish model) with CHOICES: Image, hyperlink, or text. You would then create three different models with the respective fields (CharField, FileField, and URLField), each has a ForeignKey to a Dish. The choice selected dictates which model you will use; this logic can be handle in the save() (or clean()) method.
Use imagefield
ImageField is more logical for storing the image but the issue is how he's designing this implementation.
Nvm I got it
is possible to order the cveid per id number, and keep the newest at the first , but keeping the ordering?
class Vulnerabilities(models.Model):
cveid = models.CharField(max_length=255)
last_modified = date
class Meta:
ordering = ('-last_modified',) # the newest cve at the beginning
There's way of doing this... Iโm unsure what is the most โperfectโ way โ which often leads to over-engineering and never solving the problem. But, for your scenario, you could have a CharField (in the Dish model) with CHOICES: Image, hyperlink, or text. You would then create three different models with the respective fields (CharField, FileField, and URLField), each has a ForeignKey to a Dish. The choice selected dictates which model you will use; this logic can be handle in the save() (or clean()) method.
@hollow jay I think this works
hm anyone know how to use a CSS animation to create the effect of something moving from a static position to a fixed position?
Can someone help me with this? I'm just starting with code and can't seem to figure this one out.
Hey guys, I'm new at code at all, knowing only Python which is my entry language. I've thinking about getting into web development but haven't seen much about python in the front end. Is it really worth learning Flask/Django or should I just go back to the beginning and try JavaScript instead? I may be sounding stupid right now and if so I'm sorry
uum my opinion isnt really accurate cause i dont do javascript, but I think if you are good with python, then learn flask/django
and if u want to build better websites, you'll eventually be forced to learn javascript (my current situation)
Hey guys, could you let me know if I'm doing this right? Any other ways of doing it, any decorators?
class Suite(models.Model):
suite_id = models.CharField(max_length=5, primary_key=True)
def __str__(self):
return f"{self.suite_id}"
class Customer(AbstractUser):
suite = models.OneToOneField(Suite, on_delete=models.CASCADE)
def assign_suite(self):
self.suite = Suite(suite_id = get_random_string(4, "AB123456789"))
I want to create a customer then assign them a suite.
a = Customer()
a.assign_suite()
Anyone uses selenium and pylance? This is the first module for which I get 0 autocompletion, for some reason it doesn't recognise it
you could use @property decorator and assign a setter for suite
@lucid vine is there any way to set Suite based on whenever I save a customer?
if you use @property and write a setter method it will set it during __init__
Thank u very much.
I think youโll eventually end up having to play with JS if youโre working on front end stuff. Iโve had to work with it and know basically zero about it. Donโt fight it lol
!ask
hey guys
so, i'm looking for a tutorial / doc where it is explained how to serve different type of media files(mainly mp4) to a web aplication
I don't really know the correct terminology, so i come here to ask how it is called.
Something like this
@native tide you import Post already so i think you can just call objects.all()
lemme look over it again
@native tide it's django request right ?
you have to do
request.POST
to access all params within the request
is it what you want to do ?
I'm looking at your code on github : https://github.com/joonaditya/Blogger/blob/master/blogger/blog/views.py
to me it seems good
maybe it's just your editor that couldn't resolve the object reference
you can use PyCharm ๐
nah don't worry, it has as much as vscode features at least
the only benefit of the pro version is the ability to access your databases from pycharm
i access my database through vscode
the nice thing is theres a nice plugin for everything
what kind of plugin do you use ?
can someone please help me here? thanks!
https://stackoverflow.com/questions/65653914/django-rest-framework-access-field-inside-serializer
SQlite
Can heroku be used to deploy python web apps in any framework or only django / flask?
hello guys, I cant view my image in html
what should I do?
this is what it is showing..
hello?
@native tide get the gitHub educational pack
I have a m2m field in my Post model called votes, I'm trying to only return the vote fields that match the user making the request, as a sort of optional field. So excluding all the votes that don't match the user making the request. I'm not sure how I can achieve this in Django.
post = Post.objects.filter(id=post_id, votes__user=self.request.user)
if you are a student
or have access to a school email
you can get PyCharm Pro for free etc, gives you boilerplates for Flask/Django applications and all sorts
You don't need an ID, just a school email
And if you really need one you can just buy .edu emails online for $1
is the link correct?
check ur img link and see if u have lnked it right
When playing with your models within the shell python manage.py shell, will my signal functions still work?
like this one
@receiver(pre_save, sender=Suite)
def create_suite(sender, instance):
instance.suite_id = get_random_string(5, "ABC123456789")
instance.save()
Because when I try it's not, I'm not sure if it should be picking it up.
Ok I got my projects done for my portfolio, its 3 websites, I want to display them in one, whats the way to go about this?
@native tide No reason why it should not o.o
Just as you typed that message, I found that if I put my signals in their own file, e.g. signals.py, it wouldn't work
But if I put the signals in the same file as my models, models.py, it does work
Oh
Probably because when I'm in the shell I forgot to import the signals
๐คฆโโ๏ธ
more detailed explanation of my question from earlier : https://stackoverflow.com/questions/65656967/query-that-excludes-irrelevant-manytomany-fields-django
So you want to loop through the Votes objects returned?
yeah, think I've figured it out though by using .set() maybe there is a better way though
post = Post.objects.filter(
id=post_id)
votes = post[0].votes.filter(user=self.request.user)
post[0].votes.set(votes)
use exclude instead of filter
to exclude the votes you do not want
will do, thanks
post[0] will only return the first object
is there only ever one at a time? then use get instead of filter
post.objects.get().votes.exclude()
hmm yeah I tried that but I'm getting errors using get
Whats the error ?
class GetPost(viewsets.ModelViewSet):
serializer_class = GetPostSerializer
http_method_names = ['get']
def get_queryset(self):
name = self.request.GET.get('subreddit', None)
post_id = self.request.GET.get('post_id', None)
# try:
if name is not None and post_id is not None:
if Subreddit.objects.filter(name__icontains=name).exists():
post = Post.objects.get(
id=post_id)
return post
'Post' object is not iterable
hi everybody
i have question
can i write a game at web browser ?
if i can, how ?
@haughty turtle think i have to use this to return a single instance https://www.django-rest-framework.org/api-guide/generic-views/#retrievemodelmixin
Django, API, REST, Generic views
One sec in a match ๐
haha all good
Ah your using REST framework havent touched that
Right so I am using Flask + Requests to send a POST request to a external server and its returning "TypeError: 'Request' object is not iterable" the traceback leads to this:
@main.route('/send/ban', methods=['POST'])
def send_ban():
r = requests.post('http://localhost:5001/upload/ban', data=request, timeout=5) # This is the traceback line
if r.status_code == 200:
if not r.text.find('Uploaded'):
flash('Successfully Banned User', 'primary')
return redirect('/ban')
elif r.status_code == 404:
flash('Unable to ban user, server appears to be offline', 'danger')
return redirect('/ban')
elif r.status_code == 500:
flash('Unable to ban user, server appears to be having issues', 'danger')
return redirect('/ban')
Amazon free 1 year VPS?
It asks for credit card
@noble smelt But it does not charge you
Thanks guys
@haughty turtle that worked, thanks!! is there a way to upvote you? sorry I'm new here.
Is there a way to design a website with Python (front end), or code the functionality of the website with Python (back end)?
Flask for backend
And frontend just use normal stuff like HTML, CSS, JS
ok thx
No problem.
Simple Youtube videos will suffice.
What type of game would you like to create?
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
so the email doesnt save
is there anyway to fix it?
@toxic flame where does the email not save? In the database? Have you checked that your view is receiving a value for email? You need to be more specific.
@toxic flame All you are showing is the model not how you are saving it in your view
Show more code
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
Client.objects.create(
user=user,
first_name=username
) ```
dont have to mind the others, it's just a .save() like the default.
Does any other data get saved?
so the email does not save in the User table?
@toxic flame Print out the email part of the form check what you are getting
Is the form even valid?
Hi, i am doing my Django project and now am dealing with creating cart. At this point i am creating by every click on "add to cart" button new OrderItem object and saving that to database. Is that ok ? or should i use session to store my cart ? Thanks for help
should i ask about this in help channel or is this ok here ?
You should use Javascript, localstorage for shopping carts
Print out the email stored in form just as you grabbed the username and check what it printed
well but this is great because i can then use ListView to render whole cart just by OrderItem from db
im lookign up how ot print the email
Just print as normal
In debug it works out the box I believe
Prints to the cmd
damn
<tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" value="JohnDOe2" maxlength="150" autocapitalize="none" autocomplete="username" autofocus required id="id_username"><br><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></td></tr>
<tr><th><label for="id_password1">Password:</label></th><td><input type="password" name="password1" autocomplete="new-password" required id="id_password1"><br><span class="helptext"><ul><li>Your password canโt be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password canโt be a commonly used password.</li><li>Your password canโt be entirely numeric.</li></ul></span></td></tr>
<tr><th><label for="id_password2">Password confirmation:</label></th><td><input type="password" name="password2" autocomplete="new-password" required id="id_password2"><br><span class="helptext">Enter the same password as before, for verification.</span></td></tr>```
yep messy afk
Dude your printing out the whole form.
ill just parse the email by its id and add it manualy
Get the cleansed email version as you did for username
Do what you did for username and get email and print it out
Your forms does not have an email section.
.
Look at the messy code that you printed before
Your email input is not in there.
i see i will have to debug my code further
I have one more question. I need to develop filters for my restaurants and i need to be able to filter by city and at the same time by category like vegetarian and stuff. Now i can select just by city or by category
Create those under your restaurant model, city and categories. To then filter it by chaining both filter searches togethee
well my restaurant has city and category, but how i cant pass both of category and city to my ListView ?
on page there is an input field for city and buttons for category
Send this as a form
Input and Selections
Upon submitting the form you have the city entered and the category you then filter based on those results
Although city should be a selection element also, as you likely won't have a restaurant in every city and there are multiple ways to write a city. So you would need to control this through a selection element
I have a question about Django, Do people normally just use pure Django or do they use it with other "framework" like react or anyother stuff?
by people i mean like if a company was to use django
not like beginner
@zinc hill django is just a backend framework
so yes if you wanted to make a website you'd think about the frontend too, and if you want to do that well, you'd use a framework like React
React/Vue/Angular etc.
ok I just wanna make sure
@zinc hill If you're wondering if it's worth to learn frontend frameworks, I think it definitely is ๐
If you want a job then a frontend framework is required.
If you just want to focus on Django (and Python lets say), use something like Bootstrap or Tailwind to make it pretty.
I have been learning but I dont know if people just use pure django where everything is in django like the templates, static
my current one is a front-end that just request stuff from djago
You can build a website many different ways. Depends on the situation.
People switched fron static to rich JS websites; then SPA; now some are converting back to static.
Again, depends on the product.
ok thanks glad that im not wasitng time
I'd say React + Typescript is pretty hype rn
So there's good opportunity with those technologies
yeah I saw that
@zinc hill if you are looking for a pure backend job no need to learn js
No need for fancy designs, etc. Just get what you need working on the page. If you want to be a full stack learn js sure.
yeah the reason why I ask that question is because from my research, alot of fullstack django+react tutorial was not decouple like react was sitting in the template instead of its own folder. So I not sure if that was the way to do it or decouple everything was the way.
my approach was create a django backend and have a separate project for a front-end and just request the data
instead of passing "parameter" to html or something idk
Hi guys, I am writing a little something on django vs flask vs FastAPI. would love to get what the community thinks is better for small, medium, and large proj.
it depends also
on what kind of project?
and other requirements
but I would defo say check out FastAPI, it's p cool
the main thing about Django is convenience
it has more or less everything you need
but some of its patterns are a bit dated
Flask is better for smaller projects IMO
@gm thanks for your input. I have, infact, worked on fastapi in a few projects. I am trying to conclude my views and hence I'm gathering the community's perspective.
I want to know what you mean by 'kind of project' and other requirements? Can you give an example. Lets consider we need to make a REST api and obviously, be connected with a db
I also want to point out, that thought DRF is really powerful especially with the serializers, ORM, and generics. FastAPI seems really interesting too. It reminds me of the simplicity of Flask. Additionally, the native support of asgi pydantic and openai means better testing, validation, and response time. Do you think Django is a better choice when we need to aim for the moon and think of scaling the project in the future?
I agree its ORM is hands down the best, but I believe with a good crud.py and schema validation using pydantic in FastAPI, it is superior to django.
yes it is correct
FastAPI defo has better async support
being a newer framework and built with ASGI in mind
which also means you can use SQLAlchemy with it, which in its most recent release is (experimentally) supporting async
on the other hand, Django was always built for sync
and is now transitioning...but the ORM in particular isn't async-ready
Yes. Asgi > wsgi
The community should be accepting FastAPI soon enough. But if Django is able to somehow bring in async natively, there's no stopping Django bois ๐
in terms of power for sure
How?
Don't you need to write raw sql in alchemy?
nope
it's an ORM
in particular when you want to write queries involving joins and subqueries
SQLAlchemy starts to shine
the equivalent in Django can be messy at best
and impossible at worst (without raw SQL)
Yes agreed. I tried making joins in Django ORM and it wasn't fun.
Good to learn more about SQLaclhemy
If that's the case, big scalable projects specially with async, will adopt FastAPI.
Thanks @vestal hound .
I'll include the stuffs i learned from our conversation in the article.
yw
thank you ๐
like chess, tictactoe
man why is django so overly complicated... why cant one class do both get and post with ForeignKeys
hey so how can i check if a row already exists in the database? like the whole row not just fields....
for example table is this:
id: 1,
user1: A,
user2: B
i need to check if this combination exists already. so the next rows cant be:
id:2,
user1: B,
user2: A
or,
id:3,
user1: A,
user2: B
and i dont want repeats in the database of the same group
i mean i suppose i could simply run a validation field with unique set to true
@wicked elbow use django constrain for the checking of duplicate record https://docs.djangoproject.com/en/3.1/ref/models/constraints/
yea, was already looking at that... but, that just makes it so they cant equal each other. been trying multiple things. theres gotta be a simple answer. been looking at validate_unique and and clean as well without much luck
!!!Help
Any body can help for cloudinary custom uploader for models in django? Thank you !!
im getting this now, {"non_field_errors":["The fields user1, user2 must make a unique set."]} but thats still not checking all possible combinations so i cant do user1: a, user2: b twice, but i can do user1: b, user2: a even though a, b and b, a are the same set
@wicked elbow what model is this
my model, trying to uniquely group individuals for direct messages. that are then linked to the messages using a foriegn key to easily sort the messages out
show me your model definition
actually, you know what
what I would do is
when creating an instance
enforce user1.id < user2.id
with a check constraint
and then the abovementioned unique constraint
that said
it seems like you could just use a recursive ManyToManyField...?
if I understand you correctly
class MessageGroups(models.Model):
user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE)
user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE)
class Meta:
constraints = [
models.UniqueConstraint(fields=['user1', 'user2'], name="UniqueGroup")
]
class Messages(models.Model):
msg_group = models.ForeignKey(MessageGroups, related_name='msg_group', on_delete=models.CASCADE, null=True)
sender = models.ForeignKey(Profile, related_name="owner", on_delete=models.CASCADE, null=True)
recipient = models.ForeignKey(Profile, related_name="recipient", on_delete=models.CASCADE, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
message = models.TextField(null=False, blank=False)
those are the models. just trying to check both ways so a new group isnt created
hm.
yeah, I think you want a self M2M field
through an explicit model
if you want to use its PK as a FK
i know, its the sender and reciever are repetive but it allows to id who sent the message
that is more or less what I did for my chat
except
well, some slight differences but nothing big
anyway yeah think about my suggestion
this almost works, but its not truly unique_together because AB needs to be equal to BA. still trying to figure out how to do it.
and yea databases in django arent exactly easy. many ways to check, but how to do it in django is a different story.
Why is it, when you urllib.parse.quote/encode strings before sending to a route, they look double quoted in address bar?
So for example:
<a href="{{ url_for('test', username='El Niรฑo'|urlencode) }}">testing</a>
shows: localhost:5000/test/El%2520Ni%25C3%25B1o in address bar,
but username is El%20Ni%C3%B1o inside the route function?
when i do the create, i could force the smaller user id to always be first right? so therefore if user id of one is 1 and user id of the other is 2, and the query sent 2 and 1 as the ids it would force id number 1 into user1 and id number 2 into user2 correct?
so for instance:
def create(self, validated_data):
if validated_data['user1'] < validated_data['user2']:
user1 = validated_data['user1']
user2 = validated_data['user2']
else:
user1 = validated_data['user2']
user2 = validated_data['user1']
group_create = MessageGroups.objects.create(
user1=user1,
user2=user2
)
return group_create
yes
that's what I said
it IS unique together
because
of the additional constraint
this
alright, had to do some modifications because its a Foreign key, but this works
class MessageGroupPostSerializer(serializers.ModelSerializer):
class Meta:
model = MessageGroups
fields = ['id', 'user1', 'user2']
def create(self, validated_data):
if validated_data['user1'].id < validated_data['user2'].id:
user1 = validated_data['user1']
user2 = validated_data['user2']
else:
user1 = validated_data['user2']
user2 = validated_data['user1']
group_create = MessageGroups.objects.create(
user1=user1,
user2=user2
)
return group_create
thats way to overly complicated for a simple solution lmao but here we are lmao
@vestal hound do you know where to put the try: except to catch the integrity error thrown when it fails? so i dont get the error
not really helpful in the front end if it already exists and i get the django help page back
wherever you call .save() on the serializer
ah ok, i did it on the raise_exception haha. one line higher and it didnt work lmao thanks
Can anyone tell me what all things to take care of before building a project in Django that will be hosted on domain.
Like makin sure that web server support python...
Anything else?
Here what does class Person(models.Model) mean?
Model is a class, but what is "model" and in the official django repository i am not able to find Charset method in Model class
You can create that with JavaScript.
Django adheres to the MVC patterns and bases its db scheme behind models. So when you create a Person class which inherits Model, you are telling Django to create a scheme for a Person.
The equivalent to charset is charfield.
It's your database table, each model you create, create a table in your DB and each attribute is a field stored under that table in your DB
So i must learn js
Start easy.
To create games with Django yes, as changes are made without reloading the page.
flask
Each change you make with Django for it to take effect you have to reload the page
i will do with flask
Same with flask .
oh okok
but i cant understand
chess interface
how can i create it
with js
or flask ?
Both.
o_0
If you are creating an online game.
As you need to store the data in your server(flask, django)
i can do this
thank you guyd
guys
can someone please help me here?
https://stackoverflow.com/questions/65668887/best-practice-to-add-remove-single-objects-from-a-many-to-many-field-via-generic
thanks a lot guys
@modest shale For a simple online game like tictactoe, you can just do it with JS.
If you need to store backend information like account information, etc. then that is where a backend framework comes in (django/flask/express.js)
app = Flask(__name__)
@app.route('/')
def hello():
return render_template("index.html", name="Jerry")
if __name__ == '__main__':
app.run()```
why i cant load index.html file
???
hey, in using django to make a website and when i try to run i get this error https://hastebin.com/axetohoqov.sql
the error is too long to paste
THANK YOU A LOT
@tacit anvil show your ModelSerializer
from rest_framework import serializers
from .models import Room
class RoomSerializer(serializers.ModelSerializer):
class Meta:
model = Room
feilds = ('id', 'code')
fields
if someone can help me why i cant render this termplate plz help me
guys I've been getting this error and I don't really understand what to do, I've been trying to search it up and I can't understand/know what is happening here:
django.db.utils.OperationalError: foreign key mismatch - "api_customer" referencing "api_suite"
This only occurred when I tried to set suite_number of my Packages table to be my primary_key, is there any reason why this is not allowed?
Suite:
class Suite(models.Model):
suite_number = models.CharField(max_length=5, primary_key=True)
@property
def suite(self):
return f"{self.suite_number}"
Customer:
class Customer(AbstractUser):
suite = models.OneToOneField(to=Suite, on_delete=models.CASCADE, null=True)
premium = models.BooleanField(null=False, default=False)
can you show us your file structure please?
Exception Value: UNIQUE constraint failed: api_room.admin
It's working, it's just that the data you inputted already exists and is not unique in your table
oh ok thanks
You need a templates folder, flask serves templates from there
I think this was a migrations issue... I deleted all my migrations + database and now that's fine.
Oh, and the previous issue was a naming issue. I was trying to setup a foreign key with the name suite within Packages and it was hard to spot because I had suite already as a class property...
class Suite(models.Model):
suite_number = models.CharField(max_length=5, primary_key=True)
class Packages(models.Model):
suite = models.ForeignKey(Suite, on_delete=models.CASCADE, null=True)```
How can I access Packages from Suite?
Packages.objects.filter(suite=...).
I want to access packages from suite, not suite from packages
You cant (as far as I'm aware) because there's no connection from Suite to Package; only Package to Suit.
Would there be any way to create that relationship?
Am I understanding this right? The foreignkey provides a ManyToOne relationship, with the "One" being the Suite and the "Many" being the Packages?
I found a way to access the reverse relationship, using TableName_set followed by .filter(), .all(), etc.
Hey @fickle fox!
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:
hey, so im makign a website with django and react and when i try to run the website i get no errors but nothing shows up. i have the urls correct but nothing shows up
im using this vid https://www.youtube.com/watch?v=6c2NqDyxppU&t=233s
This django and react tutorial covers how to integrate react with django and perform all of the necessary setup steps. We will be using webpack and babel to bundle our react app and have the django backend render a template that react will control.
๐ป AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify i...
Is it possible to show matplotlib graph and customise them with html css ?
So I am making a Todo app and when I render the tasks I get https://gyazo.com/1a6d5edbe0cec244ba4600e46dbb4ca5
It should print
complete the app
oh so stupid, I figured it out
Hey
I was looking into the django repository
https://github.com/django/django/tree/master/django/db/models -- Into the models package
And there is a init.py file present in the models package
Is is possble instead of downloading the entire django framework, i can just use the models package and work with it?
Will it work?
@fickle fox you need to follow some sort of guide
Hi, I have a Django Project and thought about renaming my root folder to mysite.tld - which unfortunately confuses Python -
I tried to refer to it as from mysite.tld.somepackage import something - which Python understands as a folder named tld that exists inside mysite. I saw that there are some modules that allow imports from dotted paths. Question is: Should I use 1 of these packages or instead either
A: cut that idea of naming the root folder like it was a URL
root
--somepackage
B: change the folding to java style ->
www
--mysite
----tld
------somepackage
why not just remove the .tld or just replace it with _tld
@boreal galleon what would the reasoning be?
When using DRF,
request.user```
refers to a User instance. However, what if I have a different model as my `AUTH_USER_MODEL`? What can I do to change request.user to reflect my `AUTH_USER_MODEL` instead of User by default?
I have a webapp with Flask, SQLalchemy and celery.
Some information is put in a database, with db.session.add(info) & db.session.commit(). Then, a long task is send to Celery. This task would use the information from the database, but the Celery worker says the database is empty.
When I query the database from Flask, it says the information is in there.
It seems as though the changes don't get saved to the database correctly. Does anyone have a clue what the problem could be?
For django what actually is a primary key field and what is its purpose e.g. model.pk
Hey guys! I'm running a flask-app where I have some custom JS-files in my static folder. I also import some JS files from modules installed with node. The installed JS modules in turn import other JS components.
The problem I'm facing is that the imports in the javascript files are required to have .js file endings. But the imports in the installed node modules don't use file endings. One can ofcourse manually append the file endings but that's obviously hacky and not feasible in long term. What I wonder is why this happens? Why is the file ending required? Is there any way to allow imports without the .js extension?
Example:
myCustomJS.js
import { SomeComponent} from 'node_modules/some_module/SomeComponent.js'; // Works so far```
SomeComponent.js
```js
import { SomeOtherComponent } from 'some_other_module/SomeOtherComponent'; // Does not work```
Everything then works if i append `.js` to `'some_other_module/SomeOtherComponent'`, but that's not feasible to do with every node module I install. Please @ me if you know why this happens, where I can read more, if you straight up know a solution! Thanks
does anybody know how to have your foreign keys updated automatically, when data is inserted in the parent table in oracle ??
hi everyone is there someone who can help me with flask jwt. i am building a webshop with python and flask-restful. as far as i know you need a def authenticate and def identify. the def authenticate gives me a token. so that one works. but the def identity should give me the current logged in user how can I get the identity function to work?
print("User successfully authenticated")
user = UserModel.login(email, password)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
print("Something went wrong. Authentication doesn't work")```
con = sqlite3.connect("db/webshop.db")
cur = con.cursor()
cur.execute("SELECT * FROM users")
user_row = cur.fetchone()
user_id = payload['identity']
print(user_id)
return userid_table.get(user_id, None)``` these are my current def's. the authenticate function works because i get a token from it but the identity doesn't work at all. I tried putting a simple print in it but nothing shows up
@native tide i used to code in flask but after some time i forgot some things xD
Hi, sorry if this is the wrong place to ask, but when using js in my flask templates, i need to use { and }. are there any things i should do to escape them out?
How do i set env variables for Python? I need to hide a secret key for a django project
You can easily access env variables with os.getenv (e.g. os.getenv('PATH'))
so if i use os.getenv('SECRET_KEY') it'll work?
yes absolutely, if the env var is defined in the environment where the python process lives
if you use: os.environ['SECRET_KEY'], the difference is that it will crash in the case where the var is NOT defined, which might be desirable in your context
also, os.getenv('SECRET_KEY', 'bla') will default to bla in the case where it's not found
sounds cool! i'll try that rn
Is there anyway to check for web update faster except downloading its html and scan (if any update) every minute
Anyone know how to use sessions with Heroku? Mine get cleared after a redirect. I heard that Heroku Redis might help, but I don't know what that is.
Thanks!
what is causing this???all my python files are proper with zero error
Review your urls.py. You need a url to match /wiki/css
Got it
if i wanted connect the search form i've built in layout.html to the form class in view.py how would i do that .... a general idea would suffice
yo, how do I get form data in quart?
def transferred(sender, instance, **kwargs):
transfer = instance
to = transfer.to_user
fromu = transfer.from_user
amount = transfer.amount
transfernow = Transfer(
amount=amount, to_user = to, from_user = fromu)
balance = to.profile.balance
balance =
post_save.connect(transferred, sender=Transfer)```
what should i add in the balance part so that that the existing balance of the user gets updated with the amount we sent
balance =(fromu.profile.balance - amount)
idk what i am doing wrong but the profile isn't updating with the balance, here is my models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=400, default='Hi! I am new :D')
image = models.ImageField(
default='default.png', upload_to='profile_pics')
balance = models.IntegerField(User, default=10)
class Transfer(models.Model):
amount = models.IntegerField(default=0)
to_user = models.ForeignKey(User, related_name='rec', on_delete=models.CASCADE)
from_user = models.ForeignKey(User, related_name='sen', on_delete=models.CASCADE)
def transferred(sender, instance, **kwargs):
transfer = instance
to = transfer.to_user
fromu = transfer.from_user
amount = transfer.amount
transfernow = Transfer(
amount=amount, to_user = to, from_user = fromu)
balance = to.profile.balance
balance =(fromu.profile.balance - amount)
post_save.connect(transferred, sender=Transfer)```
def transferpage(request):
if request.method == 'POST':
t_form = TransferForm(request.POST, instance=request.user.profile)
if t_form.is_valid():
t_form.save()
else:
t_form = TransferForm(instance=request.user.profile)
context = locals()
return render(request, 'transfer.html', context)```
i think there is some problem with views.py (or maybe the signal), can anyone eksplane?
will js fetch() requests contain cookie data ? so that authentication status can be checked ?
Template:
<p>{{ today_date|timeuntil:product.added }}</p>
In view:
today_date = datetime.now()
context['today_date'] = today_date
Model:
added = models.DateTimeField(auto_now_add=True)
Can anyone explain why the paragraph ain't showing anything?
what would happened if you do
context['today_date'] = "something"
would <p></p> show up
yes each date show up but when i use |timeuntil it does not work
Hi guys!
Do you guys know repositories which have a good example of a big django project
Ive done a couple of courses for Django but still I feel I lack the expertise in Django
Django!
use the axios library for requests
how many of you know react?
I'm trying to reread a csv file everytime I refresh the page, however, somehow the data is being cached. This does not allow me to enter new data into the csv file in order to show it on a chart. How do I prevent caching? I already tried generating unique URLs based on a time stamp. That works once but not every time I refresh the webpage. I'm using Flask
maybe try ask this in help channel, more chance that someone answer
Thanks ๐
hi
i am new to django , how to redirect to other page when button is pressed from html page in django
no wait
you can add it in src={% url 'urlname' %} if you are using link (you can use padding to make it look like button) if you are using button tag itself then you gotta configure your views.py
return redirect(request, 'redirectpage.html')```
show it
<button type="submit" class="btn-lg btn-block btn btn-primary mb-5"> Predict </button>
this is how i create a button in html file
this is
yes
show it
how to upload file in discord
ohk
Hey @glad patrol!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
this is view.py
this is my diabteses.html
i want to add another button in diabteses.html to redirect to my home page
but it return as soon as it predict the result
this is the html file i enter all the fields then i press predict button then it predict result and show the result on same paeg
i need to add new button when i press then it redirect
i don't understand :/
see
like when you click the button, what should happen exactly
i have predict button
okay
when i press i need to go my home page
so return redirect(request, 'home.html')
isn't working?
i dont know but i need to achive this when i press button
i need to add new button name home under predict
when i click home it redirect to home.html
i have home.html file
return redirect(request, 'home.html')```
you need to add python return redirect(request, 'home.html') in your views.py diabetes function
oh wait
there is already return
what happens
when you click the button
after this python return redirect(request, 'home.html') function
i dontt have button
thats what i am trying to achive
i have function which redirect to home.html
but i dont have button on html pae
page
hmm
okay
see i add red color which is basically home button i need to add in diabetes.html
when i press red button it redirect me to my home page
so you need both predict and home button?
oh why don't you use navbar for homepage button tho?
ohk, for the home button, make it a link, that would be easier, just use <a> tag, and edit it with css and add some padding then background colour to make it look like a button and set the href of the link to be {% url 'home' %}
should i create the button the same i create predict 1
like this
<button type="submit" class="btn-lg btn-block btn btn-primary mb-5"> Predict </button>
nono, use <a> tag and style it with css a little bit and it will look like a button
wait
show me your urls.py
ok 1 mint
urlpatterns = [ path('admin/', admin.site.urls), path('heart', views.heart, name="heart"), path('diabetes', views.diabetes, name="diabetes"), path('breast', views.breast, name="breast"), path('', views.home, name="home"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<a href="{% url 'home' %}">Home</a>```
add this
to the page
and then use css to make it look like button
yes
yeah, what is it
ok i elaboreate what i am doing so you get better idea
see i enter my data in fields then i predict it which give me result
okay
as soon as i do this in parallel i get all the fields data
and send it to database
to store the result
this is the part
if request.method == 'POST':
pregnancies = float(request.POST['pregnancies'])
glucose = float(request.POST['glucose'])
bloodpressure = float(request.POST['bloodpressure'])
skinthickness = float(request.POST['skinthickness'])
bmi = float(request.POST['bmi'])
insulin = float(request.POST['insulin'])
pedigree = float(request.POST['pedigree'])
age = float(request.POST['age'])
name=str(request.POST['name'])
date=str(request.POST['date'])
mydb = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='mdss',
port='3306'
)
mycursor = mydb.cursor()
sql = "INSERT INTO diab (name,date,pregnancies,glucose,bloodpressure,skinthickness,bmi,insulin,pedigree,age) VALUES (%s,%s,%s, %s,%s, %s,%s, %s,%s, %s)"
val = (name,date,pregnancies,glucose,bloodpressure,skinthickness,bmi,insulin,pedigree,age)
mycursor.execute(sql, val)```
i get all the fields and add them into sql database
oh i don't know how to add them to the database like this, i usually use a different method (using Models)
i add them into database
but here i need to add 1 more field which is gender male and female dropdown list
i add it previsouly but when i select gender it dont get selected value from drop down list
@supple bramble
no
oh :/
i put all the fields direclty into database
now when i select gender it input all the data into database except geneder
it is not get the secleted value
lemme find something
bmi = float(request.POST['bmi']) like this give me bmi
how to get the selected gender
ok
@glad patrol https://stackoverflow.com/questions/15048289/dropdown-menu-html-code-with-select-options-from-django this might help
you have to make a forms.py file where you will put the options
see the answer
tough
guys
I created a form in django
and when I click on submit it should redirect me to the same page right?
it appends the redirection like this https://gyazo.com/df3a8a1c906f8e0ebae853c2eb55ea0b
@vernal furnace the url should have forward slash at the end, not in the beginning
todo/
not /todo
neither /todo/
@supple bramble https://gyazo.com/d92422f6e0084628f7586a19c820fd83
shouldn't the drop down have both?
yes
it has both
yes
but i need 1 what i select
shouldn't it display both from which you can select one?
@vernal furnace show me your urls.py
urlpatterns = [
path('', index)
]
your todo app's urls.py
yeah that was it
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('todo/', include('tasks.urls')),
]
forgot to copy the imports in the first one so no worries
@vernal furnace add backslash to the return redirect
wait
@vernal furnace oh wait actually just leave it with slash
don't add /todo
just /
try different patterns, using slashes and notice what happens, it shouldn't be hard to figure it out
url patterns are easy
just play with them a bit
@supple bramble i did it
niceeee
thing is there is no difference between my code and his code

like I didnt change anything yet lolo
haha weird
check desc if there is a source code
and see if copypaste works
@supple bramble can we set field value by multiplying two fields value
like how exactly
what type of field is it
like bmi = height x weight
i enter bmi directly
i want when i enter height and weight the value of bmi auto set
what is the value of height?
are they different fields?
so you have a function which calculates bmi by multiplying height and weight you entered and when you enter bmi it shows the result because bmi was the variable right?
correct me if im wrong
right now i dont have any fucntion which calulate bmi
see this
i have bmi on form
i create 2 more fields height and weight
right now i enter bmi manuall
iwant bmi is set as soon as user enter weight and height
so you will replace bmi with height and weight right?