#web-development
2 messages ยท Page 176 of 1
Where is that JS code located? Is it on the actual HTML, or is it in a JS file that is getting brought in via script src=...?
it started working now, javascript had an error
but now I have new questions now
NoReverseMatch at /dashboard/
Reverse for '<WSGIRequest: GET '/dashboard/'>' not found. '<WSGIRequest: GET '/dashboard/'>' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://localhost:8000/dashboard/
Django Version: 3.2.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for '<WSGIRequest: GET '/dashboard/'>' not found. '<WSGIRequest: GET '/dashboard/'>' is not a valid view function or pattern name.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.5
Python Path:
['C:\Users\User\Desktop\PentaBot Webiste\WebSite',
'C:\Users\User\AppData\Local\Programs\Python\Python39\python39.zip',
'C:\Users\User\AppData\Local\Programs\Python\Python39\DLLs',
'C:\Users\User\AppData\Local\Programs\Python\Python39\lib',
'C:\Users\User\AppData\Local\Programs\Python\Python39',
'C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages']
Server time: Wed, 28 Jul 2021 23:18:58 +0200
def Usersx(request):
if request.user.is_authenticated:
context = {
'users': User.objects.all(),
}
return render(request, 'dashboard/admin/pages/tables/basic-table.html', context)
else:
return redirect('/dashboard/')
what i did wrong
Has anyone here experienced any weird flexbox or nested flexbox issues in newer versions of Chrome? I had a web page's formatting break when I updated Chrome (and other Chromium-based browsers) recently. Still looks fine in Firefox.
from django.urls import path
from . import views
app_name = 'dashboard'
urlpatterns = [
path('dashboard/', views.Dashboard, name='dashboard'),
path('dashboard/users/', views.Usersx, name='users')
]
yea so it should be 'dashboard'
i tried without /
but nothing
i'll ttry agai n
fixed
def Dashboard(request):
if not request.user.is_authenticated:
return redirect(request, '/login/')
i added request to redirect
Correct one :
def Dashboard(request):
if not request.user.is_authenticated:
return redirect('/login/')
Which one is working?
You didn't have request in your original code.
hello, does anyone have any recommendations for what i should use to make a front end for a flask server? Im new to web development and need something i can use with flask and then host on a cloud server, in my case linode
React is great. I'm using it with Django.
alright sounds good, thats what i saw popping up a lot on google, was curious to know if anyone had experience with it
glad to hear that its a good choice
Vue is another good choice.
a random person can just install Django at any time of
Interesting statement.
where is chat please ?
it's is?
I second this statement 
// content-script.js
access_token = "";
let myPort = browser.runtime.connect({name:"port-from-cs"});
myPort.onMessage.addListener((m) => {
access_token = m.access_token;
});
console.log(access_token)
this is printing <empty string>, why?
when i console.log(m.access_token) inside of the function, it works fine
but it is not updating my global variable
the addListener function sounds very much like it's adding something to be invoked asynchronously, which means that if you console.log right after defining your listener, it's probably not going to have invoked that already
oh
do you know how would I be able to access the m.access_token in a global scope?
@dense slate i saw tutorials for putting it on aws right but none of them seem to work do you have any suggestions
or inside another function for a fetch requesdt
Um, tutorials generally work. If none of them work I'm not sure how to help you. I don't have AWS experience.
would it be possible to move the fetch request into the listener?
or is this something you only want to do once?
if you want to do it as soon as you have the access token, then I think that would be the best way to do it. just make sure to set a flag to not run another request
got it, thank you
im planning to make a community section for my web app, is there already a django class for this?
ok i got it working but its not running on port 80 do you have an idea on how to do that
What are you using as the web server, nginx?
nothing?
idk
the tutorial guy his went straight to port 80
i think i may have figured out a way tho
ugh i hate promises
does this mean the promise is resolved or is it still pending
do i have to use that?
Still pending. Couple of options. Use a callback, handle the promise, or await it.
Personally I would recommend using await so that the scope of variables is easier to access
Plus looks cleaner, avoids callback hell, etc.
is it prefered to use the await keyword over then?
Depends on the project. I recommend using async/await whenever possible.
Especially for the browser unless a specific library doesn't support it
ah
Even then you can create a wrapper function but that's a bit more technical
i see. alright thank you, ill stick with await
Not a problem! Good luck.
:incoming_envelope: :ok_hand: applied mute to @timber thorn until <t:1627516746:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 121 newlines in 10s).
its more finicky to connect react to flask than i was originally thinking it would be lol
Top 4 python projects-
What are django channels
What are multiple user types in django
Why we use these things
websockets. real-time communications, non-http protocols. awesome stuff. think chat applications
Ohh chat application and apps like discord are made with django channels
websockets are non-http and not request-response based (once the inital request is sent from the client to the server the connection is left open)
yes it's exactly how i can send a message without you having to refresh discord every time
Ohh but i was thinking it was feature of one page application in frontend
Ohhv
yes it integrates nicely with django however
you just have to be somewhat familiar with asynchronous programming
async/await kinda stuff
I have to learn Django Rest Framework and Django Channels both
And js and then react

Now i know about databases django and flask ,html css
And I'm rn kind of deep into Django
that's good
django rest framework and django channels will definitely be a powerfull tool to have under your belt
does anyone know how to create a large image embed for discord using meta tags?
ping me if you do
How can i count the number of users that have registered in the last 24 hours (Starting from midnight 00:00 AM)
for counting all the users i use
context = {
'userscount': User.objects.count(),
}```
User.objects.filter(and here filter by what you need).count()
Can anybody help me answer this
and the thing of 24 hours how can i do it (sry but im new to these things)
Hi guys... I am using Django as an external API for a website. Some of my models are not using inbuilt Django ORM, meaning the managers are relying on a postgres function.
Is it a good practice to build the JSON response in the database?
Let's say you're getting some weather data using APIs or scraping. And you want your python program to automatically update the temperature in the app or website without having to press any button.... Whats a good way to do it?
One way I can think of is create a while loop with sleep for 5 minutes... Any other way? Websockets with a set firing sequence?
This is how my postgres database would look like.....
app.country
| id | name |
|---|---|
| 1 | United States of America |
app.city
| id | name | country |
|---|---|---|
| 2 | New York | 1 |
function__get__city
CREATE OR REPLACE FUNCTION app.function__get__city()
RETURNS SETOF record
LANGUAGE plpgsql
AS $function$
BEGIN
return query
SELECT
ct.id,
ct.name,
to_jsonb(c.*) as country
FROM
app.city ct
JOIN app.country c on c.id = ct.country;
END;
$function$
;
view__city
CREATE OR REPLACE VIEW app.view__city
AS SELECT f.id,
f.name,
f.country,
f.acronym
FROM app.function__get__city() f(id integer, name character varying, country jsonb);
The view would return something like this (which is what will be passed into the Django manager for use in API view):
| id | name | country |
|---|---|---|
| 2 | New York | {"id": 1, "name": "United States of America" } |
do i need to be expert in python to start learning django? or i can start with just the basics of python and learn more on python on the way on learning django?
you need to know at least python oop since mostly everything in django is classes and objects
oh nice ncie thank you
Anybody
# sign up
print("Welcome to the Sign up Page!")
Username1 = input("Please Enter Your New Username:")
Password1 = input("Please Enter Your Password:")
print("Thank you! Redirecting...")
# login page
UserCheck = input("What is your username?:")
if UserCheck = Username1
continue
UserPass = input("What is your Password?:")
if UserPass = Password1
Print("Access Granted!")
else break```
if UserPass == Password1
== is an equality check, = is for assigning a value to a variable
there's lots of things wrong wih it. Firstly, you have no colons on your if statements and it's not indented...
and yes, that is invalid syntax
.
because you have incorrect syntax... read up on this:
https://www.w3schools.com/python/python_conditions.asp
Folks any ideas will be appreciated
Celery is used for periodic/repeating tasks like this. But yes, really crudely you could have a command which sends API requests every 5 mins. I think the script will have to be async otherwise it will block the main thread
Hi can any one help me in python. i am begineer of python.
If you have a linux server cron is easiest.
Does anyone know how to change the undetected-chromedriver version just woke up today and got
from session not created: This version of ChromeDriver only supports Chrome version 93
Current browser version is 92.0.4515.107
Anyone know what I can do to fix this I have tried to download the chrome beta but nothing worked for it and tried replacing the chromedriver with version 92 but still gives the same error?
errors:{'image': <ErrorList, len() = 1>, 'category': <ErrorList, len() = 1>} this is in my form.errors when the form is invalid, anyone have any ideas what this means ?
@limpid oyster chromedriver version doesn't match up with your chrome browser.
You can try run it in headless mode
Or make sure the browser and driver versions match
Thanks had to change a bit of code I use undetected chrome driver so changing driver version didn't matter had a look and it was a full mess up lots of people reported they couldn't run code till someone sent a fix
hello, i dont know why my favicon doesnt work
so i searched up it says it has to be 32 x 32px or 16 x 16px
but it still doesnt work :|
i converted my file from jpg to ico, but it didnt work
how do i do it then?
@thick hull go into devtools, go to network, and see if the favicon is being retrieved with a 200 http code
okay
nop
Refresh the page with devtools open
Hello good Morning
How do I send email on python not go to spam
All email confirmations I made on the backend are going to spam. Does anyone know how I can avoid this?
But a doubt, because I'm a beginner in python. I can't show the images that are on the backend server. How do I do this?
oh okay and also are u using vm?
nope
cuz it looks different from windows
I use linux
just now when i asked this it was already 1h+ from me uploading the icon
idk why but now it works
anyways thanks for help
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('JWT',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}```
what would be the values for 'ACCESS_TOKEN_LIFETIME' and 'REFRESH_TOKEN_LIFETIME' in a real world application?
how do I convert json.request to dictionary?
that's hard to tell for all applications like this, as you will want lower values for e.g. a banking site and higher values for e.g. a social network. it all depends on how long you expect your users to visit and how often you expect them to visit
what's json.request, specifically? do you mean the json payload of request? most web frameworks do it for you, if not, you could use something like json.loads(request.content) to parse it yourself
wait let me show you the code here
from flask import Flask, Response, request, json, render_template
import pymongo
app = Flask(__name__)
# establishing webhook_db connection to create a new db
try:
mongo = pymongo.MongoClient(
host="localhost",
port=27017,
serverSelectionTimeoutMS=1000
)
db = mongo.webhook_db
mongo.server_info()
except:
print("ERROR -Cannot connect to db")
# home page
@app.route('/')
def index():
return "HELLO"
@app.route('/webhook', methods=['POST'])
def webhook():
try:
if request.headers['Content-Type'] == 'application/json':
my_info = json.request
return Response(
response=json.dumps({
"message": "successful",
"requested json": f"{my_info}"
}),
status=200,
mimetype="application/json"
)
except Exception as ex:
return Response(
response=json.dumps({
"message": "some error occured",
"error": f"{ex}"
}),
status=500,
mimetype="application/json"
)
if __name__ == "__main__":
app.run(port=5000, debug=True)
@meager anchor This is the code I have written
where did you get that json.request from?
I am trying to get it from github webhook
no, I mean, which docs told you to use that
well, whoever made that video somehow doesn't know how flask works.
anyways, you're looking for request.get_json(). request is the flask request object, and get_json() parses the content as json, if present. See https://riptutorial.com/flask/example/5832/receiving-json-from-an-http-request for an example
Learn Flask - Receiving JSON from an HTTP Request
nah, it's fine
my messages are getting deleted here
We block messages that have an ngrok url in them
oh ok
since they're commonly used for scams
feel free to resend your message with the domain removed
@meager anchor I am getting the output something like this as the output
"<Request 'localhost/webhook' [POST]>"
I wrote localhost
sorry to ping you btw
how long would you recommend for a social network?
of request.get_json()? or what specifically are you outputting here? and where?
completely fine, please continue to do so, i may otherwise miss a reply :<
personally i'd just slap something like 3 months on it and call it a day. i wouldn't recommend that from a security perspective, but well
also, you need to decide whether you need the access tokens for so long
it's impossible to tell from the settings page only though
It was for the one in this message
#web-development message
for request.get_json() in the place of json.request I am getting the output as an error as it goes into except
{
"error": "400 Bad Request: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)",
"message": "some error occured"
}```
then you're not sending it valid JSON
I have written this now
@meager anchor is it correct?
the change is line no. 29 in the image
if you're not sending valid json, you will get the same error
excellent ๐
print(my_info)
I tried it before but it was not working
as if the whole statement was being ignored
Hey guys so , I am trying to give a registered user default profile picture, after looking through everything , I think this might be the case
the default.jpg is in media.profile_pics but in the screen we can see that it looks for with a different url
is there a way to change that?
I have done this
and this
I mean, i could just move that to media but
shouldn't the media_url be /media/profile_pics?
or do you want to have other media categories as well?
oh , in here right
yes
no , just this one
lemme try
no that does not work
it works just fine if I move the default.jpg one folder back
in the media folder
@meager anchor I want to get these fields from the parsed json
but I am getting many things which I don't understand
how can I get these shown in the image?
wait, sorry. i think i gave you bogus info. i believe the MEDIA_ROOT needs to be adjusted, not MEDIA_URL, because you're accessing the pic at /media/default.jpg and want it to go to /media/profile_pics/default.jpg on the filesystem
also, just to be sure, you did enable this? https://docs.djangoproject.com/en/3.2/howto/static-files/#serving-files-uploaded-by-a-user-during-development
you got the parsed dictionary, right? are the keys and values not present in there?
I can't undestand it
can I use something like a for loop to print it?
you can use my_info[somekey] to get the value of key somekey in the my_info dictionary
for example my_info["author"] to get the github user making that action
@meager anchor I did these changes
got this as output
and I get this print function after I kill the server
I don't get this before the 200 status
why is it so?
I tried different types of things too
like print(my_info["action"])
print(my_info["number"]) etc but I am still getting the print after I stop the app
this one gives error btw
this is the error
it goes into except
good question, I'm actually not sure myself. i don't use flask much
yes, because author isnt in there
@meager anchor I stored the parsed json in mongo db
can you help me understand a bit?
I want to get the above image data out of it
have you created a basic flask app?
Hey guys can someone help me to understand the concept of project and app when we are working with django? I know how to use but want to deep my knowledge
for exemple if i want to make a django rest api to a library
i probably would do
django-admin startproject library .
cd library
django-admin startapp books
sorry if i interrupted any previous conversation
tbh I don't know much about this method I have only used the normal version
from flask import Flask, Response, request, json, render_template
#import any libraries required
app = Flask(__name__)
if __name__ == "__main__":
app.run(port=5000, debug=True)
you can run this file in terminal and you'll get the link
i think he wants to host it so that anyone can access it
oh ok
I used ngrok for that
because I am testing stuff
but I don't know other methods tbh
As soon as I import web3 in my server.py file my Flask stops working. Even importing another python file (to use some variables from it) makes the server stop loading anymore.
Why so?
How do I remove this in django. I've tried setting required field error as empty string, but it just gets rid of the required text and all in the square brackets stays still.
width: 100%;
height : 10%;
background-color : rgb(92,82,102);
position:fixed;
top:0;
left: 0;
margin: 0 0 0 0;
}
body{
background-color : rgb(123,123,164);
}
ul#nav li{
float:left;
}
ul#nav li a{
text-decoration : none;
padding: 30px;
margin-right: 5;
display: block;
text-align:center;
color : rgb(255,255, 255);
font-size:16pt;
}```
i cannot for the life of me get to text align to center
in the navbar
try to watch the boxes on the inspect element
So ive been watching a vid on how to build a REST API w/ flask, and I was wondering how I would apply that knowledge and build an actual project with it.
what are the uses for a REST API if u build it yourself
guys i have a question in web dev , i made a sign in / sign up form and linked it to a data base , my problem is : every time a user refreshes the page they have to login again how can i fix that
the website is wrriten in react native
hey folks, what is your favorite flask starter kit ?
add there credentials to local storage
and then you can check for there credentials
if not there send to sign in form
you can store there data in the browser storage
oh
so even if they close the browser and open it again they will stay signed in
oh man thank you so much
yes via cookies
i will google it now
is it a complicated procces though
i just finshed that course and it didnt include any of that lol
uh
well
the website is made on react js , i send a fetch request to my sever and it checks for the database
the server is written in express
thats it
Ideas on handling cookies in SimpleHTTPRequestHandler?
I am not using any frameworks at the moment.
hi, can i mix python, flask, and javacript together?
I believe so
like really?
You could look it up ๐คทโโ๏ธ I don't have a definite answer but I don't wanna say no and that be the final answer haha, Ik you can use python and javascript together
Idk about flask
yes you can
in two ways
a) You use python-flask as your backend and your use its jinja2 templating language to render pages, which you saturated with javascript (I guess it is more simpliest choice)
b) you turn your flask into RESTful application which outputs the data in json format, and then use any frontend framework at your choice and make requests to flask (instead of REST there are some other options though)
@inland oak So ive been watching a vid on how to build a REST API w/ flask, and I was wondering how I would apply that knowledge and build an actual project with it.
what are the uses for a REST API if u build it yourself
REST API gives:
- clear separation of your backend logic from front end logic, it is good in terms of increasing code base for big projects
- good for situation to have two developers on two different tasks, one is good with frontend, another one is good with backend.
- reusability of backend for other frontend applications. With keeping the same REST flask, you can make desktop/mobile version easily accessing the same back end
- and python frameworks aren't that rich in frontend, with having your backend accessed by REST, you can use better tool for frontend, something like React, which gives more frontend features.
ooooh got it thanks! Do you know any examples of beginner projects I can make using a REST API that I would build?
REST api can do everything that not REST api web apps with backend do.
So anything you wish
I would not mind having youtube playlist downloader in form of web site
probably going to make one for myself
anything that you wish
oooh isee thats a good idea, wait would the songs be downloaded directly to the computer or to spotify
i wish downloading to computer so I could load them to my mp3 player
Hi! I'm trying to make a rain prediction model using already existing data but get errors left and right. Pls help me in #help-mango
I listen audiobooks in this way
im a little confused on the role the REST API would play in the youtube downloader
i am unsure myself.
this sort of web site can be requiring web sockets instead of REST API
lets think
user makes request to download the song or playlist
he sees progress bar, how much is left to wait
after finishing, big song or playlist of songs could be compressed into archive in order to download a bit less perhaps
the link is offered to user to download / or process for file transfer is initialized on its own
GET request would be enough, yeah.
I did not deal with web sockets to realize how they would be applied best
I only know that progress bar with web sockets could be made in a real time way transmiting info between server to user, so at this stage they could be prefered
with requests we would have to make repeated requests in order to check status, which would not be that fun but still an option
plus with making multiple requests we break the rule about application being stateless
so that would be not cool, hmm
in order to realize how to make this app better, we need to check how we can force user to download file I guess with delayed state
wait sry this is a dumb question but the user would make a GET request by clicking on a button on the website right?
yes
for some reason when I think about this application, I strongly wish to divide responsibilities
one application will be doing only downloading and nothing more to some second server
another application would be checking / showing status of the download
it makes no sense though to split such a small application for a own usage though
well, nvm, I should return back to work.
pls help
thanks for your help, I appreciate it
Hi Everyone, i am making a blog application in django. I have also used django taggit module to categorize the blogs. i want to track the user and which categories of blogs he/she is searching/reading then utilize this data to recommend blogs in a recommended blogs section in the home page. But Unfortunately i have not a single idea for how to implement that... It would be great if someone could help... Thanks in Advance...
Help
And Please tag me when answering.........
like @ornate flame
help me in #๐คกhelp-banana
Hi, I'm an incoming CS major at my uni and I'm really interested in web development leaning towards the front-end development with room for full-stack development. Most of the courses taught in my program are going to be back-end related so I'm wondering if I should pursue learning JavaScript, HTML, CSS or should I continue learning Python like I'm currently doing right now and transition into front-end tools. I'm not sure if this is the right place to ask so sorry in advance if it's in the wrong section.
css is hard
Hello please help, im new to devops.
I am using django rest framework and allowed all CORS
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_ALL_ORIGINS = True
this is deployed on aws lightsail and is a working api.
I have a react frontend deployed on aws amplify, but I always get this error:
Access to XMLHttpRequest at '<api>' from origin '<frontend>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
how do i fix this?
Are you sure your settings are up to date?
pip install django-cors-headers
INSTALLED_APPS = [
"corsheaders",
...
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
i have this already... as well as the middleware
is django behind some reverse proxy perhaps
nginx?
yes it is in nnginx
there is the problem then
how should i fix?
server {
listen 4000 ssl;
# # location of SSL certificates
ssl_certificate /app/web/ssl/ssl.crt;
ssl_certificate_key /app/web/ssl/ssl.key;
location / {
proxy_pass http://django;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /static/ {
alias /app/web/build/static/;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
add_header 'Access-Control-Max-Age' 86400;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204; break;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
}
add in the appropriate place those add_header things
should i copy all add_header things in nginx?
whatever you wish
what things should i change?
im not so familiar with nginx, i cant understand some of the code
location /static/ {
alias /app/web/build/static/;
# add_headers
}
it is responsible for adding your CORS thing to your static files served with nginx
if something would be still wrong
check
location / {
proxy_pass http://django;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
may be it has something useful too, but I doubt.
this is looking like it is not setting any CORS related, this is just transmiting ip of the incoming request
try and check if it would be related
i see. thank you @inland oak. can I pm you if I encounter anything more?
nah. I am at the moment all in pain and not in the best mood, I would be a bit over aggressive I think
okay, thanks for the tip
Hi guys, I'm currently learning the basics of JavaScript. What else do I need to learn before I can use Ajax with my flask apps?
Well sounds like you need to learn how to use JS with your Flask webapp.
Can anyone think of a way I could โPrint to PDFโ a page, non inclusive of the header/footer/menu?
Iโve essentially created a report of data. It would be a good feature to be able to allow the users to print that off
I am gonna start learning web development.. But have no idea about where to start from what should be the first step? Can some please help out .
Learn python fundamentals then try Django tutorials on YouTube
So normally I use flask login manager to login users. But with this new project I'm working on, the API is also going to be used for a mobile app. What type of login should I use? I have a general idea of how it should work: User logs in, it queries the database, and returns a token. I use this token for further requests. Is there a specific terminology for this type of login, so I can research it?
or if there is another way to achieve what I want?
It's called token based authentication :)
Idk about flask but Django rest framework has an implementation out of the box
Thanks! i just figured out its called JWT, i'm just trying to see the different between JWT and normal token authentication (which is stored in the user table)
Folks I have a simple problem with my HTML table (in Flask). Can someone please figure out why my CSS isnt being applied to the table which I produced using jinja python? #help-corn
im not sure how it is in flask, but in django i have come across at similar problem, and I believe it was the browser's cache
when ran in incognito, or just with disabled cache it was working fine
dont think thats it. because every 20 seconds when i refresh new data comes up
Unfortunately, I can't be of any help. I'm not familiar with flask
im just learning django and whenever I change any backend code, I have to runserver again! I know that this can happen sometimes, but in my case its happening everytime?
are you sure it doesn't make the changes, usually it should rerun the server automatically
what ide do you use?
visual studio code @next comet
Yes. Extremely sus
the html edits work just fine. it's the python part that needs restarting
What kind of changes did you make?
it will take a few seconds for the server to automatically reload
What django version are you using?
3.2.5
Did you save the file?
yes. It runs fine after restarting the server
that's sus
Switched the ide to sublime. Issue persists
btw your name is hella cool @eternal blade
Hello everybody, I'm suffering with authentication & authorization in Django restframework, even though I read the documentations many times, about token, sessions, oauth1, aouth2. But I can't seem to put it all together, could someone help understand where to use what, and the difference between all these methods, THXโค๏ธ
guys, can anyone help me very quickly with a deploy on heroku with my django app
its my first deploy and i encountering a serious of erros, fixing ones and finding others
i we could go to a voice chat i would appreciate
thanks, tag me anytime
can you download files to an s3 bucket
like if i have a script in ec2 that downloads file and i choose the destination to be in a s3 bucket?
Hi, I got this code online for updating cache on Flask apps, but I'm not too sure what each line does, can someone explain?
https://stackoverflow.com/questions/32132648/python-flask-and-jinja2-passing-parameters-to-url-for
@app.context_processor
def override_url_for():
return dict(url_for=dated_url_for)
def dated_url_for(endpoint, **values):
if endpoint == 'static':
filename = values.get('filename', None)
if filename:
file_path = os.path.join(app.root_path,
endpoint, filename)
values['q'] = int(os.stat(file_path).st_mtime)
return url_for(endpoint, **values)
If I wanted to be a front-end developer should I learn JavaScript first or keep learning Python?
I want to have a bit of back end knowledge
You should learn html/css/js for front-end development
JavaScript is essential for frontend, and you can also do backend in js with Node.js
So if your main goal is frontend, I'd go with JavaScript personally
oh i see, so if i learn node.js there isn't really any point to learning python with frameworks like django?
but django kinda swag doe
If you prefer Python for backend, Python is fine
i knowww
It's your preference
its so hard to decide
But if you're wanting to be mostly frontend, JavaScript is the way
i love python bc its easier for me to understand but i really wanna become a proficient front end dev
after you learn the basic stuff like html and css you could look at front end frameworks like angular
css is the hard part
css aint even that bad
Angular is losing popularity afaik
is react good as well? I heard good things about it
just use display: flex
angulars just an example
not similar
js is dynamically types
But you can use TypeScript to use static typing in JS
Not very similar at all
java is to javascript as car is to carpet
https://javascript.info is a great way to get started with JS
okay thank you so much
can you download files to an s3 bucket
like if i have a script in ec2 that downloads file and i choose the destination to be in a s3 bucket?
hey
Made a flask boilerplate if its any use
git clone https://github.com/SarangT123/flask-boilerplate
can anybody help with django
I'm running my aiohttp server with authbind and it's not working
that's the command
I made a test. Every time the homepage is visited it tries to touch (command) a file in the root directory
and it works....
more than jquery too?
I believe so
jQuery isn't used often much anymore in non-legacy code afaik
jQuery has lost popularity as the newer more modern frameworks do what it does better
oh i see
oh jquery is pretty low, below meteor, which i don't even expect javascript developers to have heard of
I've certainly never heard of it
Hi, I'm trying to get a form to save within Django and am having no luck. I'd like to use a django form to create a digital ocean droplet and have it linked to the student who creates the droplet. I can get the droplet created, but the form won't save. Any help would be appreciated:
`def DropletCreateView(request):
if request.method == 'GET':
form = LHCreateForm()
else:
form = LHCreateForm(request.POST)
if form.is_valid():
ipv4 = form.cleaned_data['ipv4']
cider_size = form.cleaned_data['cider_size']
DropletName = form.cleaned_data['DropletName']
Droplet.customer = request.user
u = form.save()
try:
#gog = env("dOcean")
url2 = "https://api.digitalocean.com/v2/droplets"
headers_do = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization':'Bearer Super-Sweet-API-Key',
}
droplet_create_data = {
"name":DropletName,
"region":"nyc3",
"size":"s-1vcpu-1gb",
"image":"ubuntu-20-04-x64",
"ssh_keys":'301886968888',
"backups":"false",
"ipv6":"true",
"user_data":"null",
"private_networking":"null",
#"volumes": null,
"tags":["customer-slug"]
}
r2 = requests.post(url2, headers=headers_do, json=droplet_create_data)
r3 = r2.json()
print(r3)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'pages/droplet_create.html', {'form': form})
def successView(request):
return redirect('')`
The error I receive is: NOT NULL constraint failed: pages_lighthouse.customer_id
do you understand the meaning of the error
Yes, I do. It wasnโt pulling in the user which was required. I couldnโt figure out how to pull that user in but I figured it out.
anyone have idea how to make web like botghost.com
hi, how do I make a custom 'page not found' page using flask?
look into error handling in flask and the @app.errorhandler(404) decorator
thanks
can someone help me understand the benefit (if any) of using something like flask or django for a backend with a react frontend? is there something inherently bad of just using a node server to use react?
I've not written apps with node before, so I'm not gonna be able to give you a detailed answers comparing these backend frameworks. It's not a matter of it being inherently bad, it's a matter of having different features, the ecosystems around these frameworks, and also personal preference (which language you like more, which lang/framework you have more experience in, etc.)
Well, node is a runtime not quite a framework. I assume you mean something like express for a node backend.
Anyway, on the surface, these frameworks ostensibly fulfil the same purpose. But when you look more closely, they have different features. For example, django is designed to be more "batteries included" so it comes with an ORM, an admin site, etc. and it's designed together so the idea is that it is integrated better and works out of the box better compared to installing third party libraries to fulfil these other needs.
Alright I see, well thanks for taking the time to explain that, it definitely cleared things up
Hey, I am very well versed in python, but I don't know much about advanced web development (Knows only the basics of HTML/CSS/JS)
For a side project I want to build a live streaming website/app
People recommend me to look into EXPO react native
but python is my best language, so I want to know is there any good python web/app framework that works for live streaming?
Python is used for backend development (django, flask, fastapi), React native
is a front end javascript framework
You can use python as the backend for your app and React native as the front end
this is not python but, when I open pgadmin4, shouldnt it already have a postgre server?
Or I have to create one?
postgresql and pgadmin4 are two different but compatible programms
ohh
postgresql is a program for database
pgadmin4 is a purely Graphical Interface to make your experience a bit more comfortable
you can create database having only postgresql, by using console interface, pgadmin4 existnence is not needed for that
I see. So what do I name the server?
I'm trying to follow a tutorial on youtube, so I'd like to do things identically
ยฏ_(ใ)_/ยฏ
Why we need to learn Django Rest Framework
What is Rest api
Why django rest framework if we can create stuff with Django
Look these questions up on the internet first
I just searched on yt
Ppl directly start teaching noone tells why it is needed
How and when
https://www.django-rest-framework.org/ literally the first search -_-
Django, API, REST, Home
an api is used to transfer data between the frontend (javascript) and backend (django rf) in your case
Hello, I am new in this server, and I am interesed in backend web development with python using the django framework. Are there any tips on how to do so?
Does anyone know a Python module for making interactive maps for Flask?
Ik about Pyecharts, but the documentation isn't as good
Anyone experienced with microservice architecture?
I know this isn't strictly just about Python, but could someone please confirm or correct whether this is the correct way to do favicons for a static website (not PWA)?
hey i need help with django models
im taking an input of an audio file using filefield
but i want to check whether the user is submitting only audiofile
not other files
how can i do that
yes
I've skimmed various websites, but they all have different methods
Need a little help with something. I am building a webapp, and I am also building an API so that when the mobile developer is hired, he can easily connect to the API to login users etc. Now I a route called student_register - this is a webapp route.
Now inside my api route, I have a route called submit registration. So I want to use this same route for mobile api requests, and website requests. But on desktop its going to return a flash error message, on other api requests, it should return status codes.
Is it possible call another route from within a route?
You can check this at various levels
But overriding the save method of the model would be the best imo
Maybe use some kind of redirect
You can use FileValidator, eg: py validators=[FileExtensionValidator(allowed_extensions=['pdf'])]
hey does anyone know how to integrate Windows Terminal in vs code? now it opens in a new window
anyone know how? For a user selected category (e.g., Rent), determine the mean value
over the whole 12-year period and display the values that fall within
20% of the mean and the years in which they occurred.
Windows Terminal is the new window though, I'm not sure what you're trying to do
You can do stuff like run WSL or Powershell or Command Prompt inside, because those are the different shells
just open the terminal in vscode
guys did you update your authentication for git? if you didn't use authentication token
I would recommend starting with the django tutorial, it's really great
Corey Schafer also has a video series on django if you'd prefer that
Hi ,I am now watching tutorial about api in django but somthing I notice is 'Pygments' what is that
@mystic wyvern that's a google search away
Hi
I am learning Django and working on an API for a discord bot
I need to put 5 items in a group and should be can call with group PrimaryKey all the items in it
Does anyone have a solution?
(sorry for the bad English)
anyone know if django has some sort of validation pipe system, such as in nestjs where you can define how you want POST data to look like before the request reachers the view?
the vscode integrated terminal is a better option because your code and terminal is all in one window, you can change between shells, and every new terminal process in the integrated terminal starts at the current working directory
do you mean like django forms?
windows terminal just puts cmd/powershell/ubuntu shell/ whatever else in one place right? I'm not sure what it means to put the windows terminal into vscode
how would I implement user created communities using the group class in django?
@wooden ruin DRF serializers, but that's once the request has reached the view... before it reaches the view you could have middleware which you apply to certain routes
Because windows terminal has some tweaks for example ctrl + a, would be nice to finally have it, it's improving normal cmd
Hello guys!
I have been learning the basics of Python for quite some time now but I was wondering whether the Flask framework was a good way for me to learn how to make a website (I don't know any other language besides python...)
Hey, how can I find the http authentication method of a site if it does not show up on the response headers?
learn django
its awesome
and secure
you will need to learn either django or flask (the choice is yours), but you will have to be familar with html/css at the least
Mm, I see.
yes its your choice
To be honest, I am a complete beginner so I have to learn pretty much everything from scratch
I heard that django was better for complex projects
flask is good for beggineers but man django is awesome
but django is awesome, try it once.... it is beginner freindly
By the way, is Django requires heavy knowledge about CSS and HTML?
django/flask are backend frameworks, htmll/css/js is used client side
yes
but not heavy knowledge
first learn html css js
django and backend frameworks
do @ornate flame to reply
Okay thank you ๐
freecodecamp is the best way
if you know python the js will be easy
i am learning js now
I know basic python but that's a far cry from being an expert
In school we mostly learn how to use it for math problem solving
It doesn't teach me much about the other stuff
no expert needied
yeah I suppose
freecodecamp learn python
I see thank you very much for the advice
Sorry can anyone guide me?
can you share your current schema and maybe a drawing of how you want your assocations / group to look like? i'm having a hard time understanding right now
is that the only path in urls.py? do you want the task update view as the success_url or another one?
it is, yes. you can also try django, but it's a bit more involved than flask, i would highly recommend starting with flask first to learn web development and moving to django later
you can loop through inputs (which are of the type checkbox) and then check if the text of the DOM element is equal to the "By checking the box you acknowledge...", then you know it's the right input
Delete it, easier
# Inputs that are children of <label> tags
possible_inputs = driver.find_elements_by_xpath("//label/input")
for input_ in possible_inputs:
if "text_here" in input_.text:
input_.click()
break
read code above
input_ is a DOM element... you check if it's text is equal to what you want
if it had to text then you know it's not the element you're after
OK, This API is supposed to return five simple questions with a GET request like this: example.com/api?question_pack_number=(number_of_question)
My problem is that I do not know how to write the models.py file of the api app so that all the items in a group can be called with the primary key of group.
any... they are identifiers for the input
the text may be of the label tag, instead of the input tag actually
any web dev team here
team?
yep
do u know about any web dev team
a "team"? no. you gotta question?
the href attribute yes
it has another attribute, target
show code
well, the text could be a part of the label tag instead of the input tag. Try investigate the text of them elements to see which one to select.
I think it would be a part of the label tag here
also,
if "href" in input_.text:
input_.click()
break
There isn't any "href" text on the page, so that will always be false
even another way to check would be to check the hrefs of the links:
# Iterates through all labels
labels = driver.find_elements_by_xpath("//label")
# Checks if there is an anchor tag within the label
for label in labels:
# Gets first anchor tag
first_anchor = label.find_element_by_xpath("//a[1]")
if first_anchor:
if first_anchor.get_attribute("href") == "/static/terms.html":
# You know you know have the right label
# Select the child input and click it
label.find_element_by_xpath("//input[1]").click()
What is the best light way to publish a website to the web?
I just made a simple website and wanna put it out on the web
hmm
well, the general premise is there with multiple ways to do it, gl
hey can any1 gimme some tips to learn django rest framework
and some good tutorials
cez docs aren't enough i'll follow along the docs + i will se tutorial 1st
as docs are kinda harder then vid
anyone know how to get another value from the database based on login information. Like i want to get something else associated with their email
This is in flask btw
need more details
So I have a login page right. I want to get the file that is associated with the login info.
I have a data base that stores usernames email password hashes and a data_name. I want to get the data_name file and then put it on my graphs.py file
ok, is data_name on the same table as email etc
Yes
ok, so why not just query the database with the login details
But how do I get the current user one
Is there like a current user or something
That I can query the data_name file
what do you mean current user? what are you using for user login management?
Flask's thing
what thing is that
are you using flask login?
yeah
ok, so it has a current_user object
ah yeah thats what i was asking about
so are you using it?
current_user
where is login_user from?
dude, are you using this https://flask-login.readthedocs.io/en/latest/ yes or no
oh you ah nvm
wait
yes, there is a current user object
so i can use the current_user thing right
okk
so i can do
current_user.data_name

yes
sir is fine
ty sir 
o wait but i have to import that in my graphs.py file right
but if you want to use current user in it, yes you can import it from flask_login
yes
I have to work on a website project ,can someone please tell me what SGBD is better to use?
What are the things python backend programmers do?
Help me out please
Uhh a lot. You're going to want to be more specific here.
Database design, storing and retrieving data, authentication, scheduled jobs, micro services... Basically anything you could think of.
problem again. Uhm i doin't think im using the right syntax to get the info in the data_name column
is that the correct syntax?
bro, why are you querying for a user when you already have current user?
what is data supposed to be? cause it's an object at this point
o ok
um im just trying to store the data_name
like thaty
so the login is dev
right
and im trying to get the data_name
oh so do i just say
current_user.data_name
is that all?
its still saying its an object
What would be the best for creating a user community system in my web app
would i have to create a new model or to use the groups that django gives you
@thorn igloo
I have used the User model since the beginning of my project from django.contrib.auth.model. But now I want a to use a CustomUser model
what do I do?
Do I delete all the posts + users? then create the CustomUser model + additional fields I want to add to my Post model.
restart the server
I did tho Everytime
show me your model for user
I'm just not able to get any of the columns
Ok
I even tried it with email_address
Do I import them separately or something
show me user loader
show me the error you are getting
It just says it has no attribute
When I did user = current_user
And then in format function
I passed through
user.data_name
And it said it had no attribute data_name
bruh, are you calling this function after the user is logged in or what
Yeah
It's supposed to
But I think what is happening is
It's just not running
Cuz no user has logged in
Is there a way to bypass that
i thought data_name was linked to a user
It is
how are you gonna access it for a specific user without loggin them in, that makes no sense
Yah
I realized that
But it is there a way to bypass that
Or another way to do all of this
you need a way to know which user you are dealing with, either way you're gonna query the database
you can't access something linked to a user without identifying the user
Unless the user is logged in
what you want to do is impossible.

unless you just randomly query a user and display that data
Can't I do like
If user logged in
Load the csv
Else
Do nothing?
Can that be a possibiloty
yes, that's possible
current_user.is_authenticated
learn to refer to the docs, this info is there
I'm looking to create a user community system for my webpage can anyone guide me in the right direction on what to do?
step 1: list all your requirements
What do you mean?
you write down what you want this community system to be able to do etc
that will give you an idea of the functionality you need
to implement
I was wondering is it best to use a django groups or use a custom model?
depends on your requirements
There will be permissions, owners and mods. So which would be best for this?
idk
are you familiar with django groups @thorn igloo
no, i don't use django, i'm a flask guy
ah fair
I have used the User model since the beginning of my project from django.contrib.auth.model. But now I want a to use a CustomUser model
what do I do?
Do I delete all the posts + users? then create the **CustomUser **`model + additional fields I want to add to my Post model.
Yes that'd be the way to go. But changing the auth model midway through the project is going to be difficult, the Django docs themselves say so.
I think you'll probably have to delete all migrations that are related to the user.
Do I also delete the migrations file for the posts?
Try first without deleting them
I suspect you'll have to since post will probably have a relation to the user
hello
do we have to clear residues from migrations? or something like that? In django.
I encountered an error, which I removed. Yet it still shows that same error when I run python manage.py migrate
@candid palm which error?
@meager anchor
can anyone give me good site for html templates for errors,
Hi. I have been working on a Python Flask app recently. I have wanted to host this app using Heroku service, but I cannot seem to get it working. I am trying to use the service 'waitress' to help with this. But I am not sure how to get them to work together. My current Procfile is:web: waitress-serve api:app
My python file is labeled as api.py and is in the same folder as the Procfile. The end of my python file I just have serve(app)
Whenever I try to visit the website, I get the error
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Does anyone know what I should do to fix this? Thank you.
i don't understand what you're saying with primary key. wouldn't you just want to return five questions from the database t random?
can you run it locally? does heroku expect it to run at a different port than it does?
normally not, no
can you share the error and the generated migration?
I figured it out
So the residue bit was somehow correct
if one of the migrations has bugs then all subsequent migrations will have it
so i had to individually delete the buggy file, then it worked
PK
for example
Question_pack.objects.get(pk=pk)
I wanted to create 5 char fields in a model and use it
But I thought maybe there was a better solution
ah I see, that makes sense
yes, but if you want to retrieve multiple objects, like a random sample of questions, then a pk is probably not what you want? a primary key is unique, so getting a question with that would only return a single entry. or do you want to return a set of questions grouped by some category?
first off, you should delete that message and regenerate the client secret asap
oh
ok
i regenerate
ty
for saving me
did you install requests in a virtual environment? is there a setting telling pylance which interpreter to use?
i installed it in cmd propt
with pip install?
oh i got it to work i just had to reboot vs code
๐
I decided to just switch it to the default server inbuilt with flask. Couldn't get it to work with waitress or gunicorn
no clue what i did wrong
I also do not want it to be random, it is supposed to return specific questions. In fact, I want to know is it possible to create a parent model that contains a certain number of other models So as to be able to access child models by parent pk?
ok
Also you should use this #discord-bots
i was making this for the website
i needed to connect the bot to the website
but ty for the help
ahhh okay I see. you want to use a OneToManyField or ManyToManyField, see https://docs.djangoproject.com/en/3.2/topics/db/examples/
Thanks
please wait bro let me get some help after that u ask
i can help u what's the issue
it is on the above images
it's not whole ss
i have app name calc
which page u r accessing i can't see the slug ^^ up
hey guys
is there any way i can pass variables to a json file?
so i can access them in a js file
I have a question about Django models/forms. In the project I'm making, I ask the user 3 questions. First I have a dropdown field where the user can select which object to create, then in the next form I ask about parameters for that object (which vary wildly depending on the object), and in the third form where the user selects how they want the object to display (also depends on the object, but it's always a single dropdown field).
The problem arises in the second step. One of the objects requires only a single checkbox (models.BooleanField) and whenever I want to create that object, the second step is skipped completely, I am not shown the checkbox at all, instead I go directly to the third step (selecting the way I want to display it). After some digging I figured that form.is_valid() evaluates to True if there are only bool fields, so that step immediately passes through and skips to the next step, without waiting for the user to actually click Continue. Does anyone have any idea how to work around this issue?
I really messed up the backend of my project
I have a User model and Post model
user can create posts
this is what the Post model looks like```py
class Post(models.Model):
options = (('draft', 'Draft'), ('published', 'Published'))
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
title = models.CharField(max_length=250)
excerpt = models.TextField(null=True)
content = models.TextField()
slug = models.SlugField(max_length=250, unique_for_date='published', null=True, blank=True)
published = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post')
status = models.CharField(max_length=10, default='published', choices=options)
class Meta:
ordering = ('-published',)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)```
I deleted all the posts that were created + the migrations file
and when I try to delete all the users now I get this error OperationalError at /admin/auth/user/ no such table: blog_post
I also deleted migrations for the User
When I tried to delete Users before I deleted the Post + it's migrations, I also couldn't delete them because of outstanding tokens.
could you show us the view? iirc, form.is_valid() checks if the request method is POST. So, in theory it should only be valid if the user submits the form, maybe there's a logical error in the view.
I'm using JWT
surely you can just delete all of the migrations files, nuke the db then remigrate?
what db are you using?
default sqlite
I can do that for the Users?
yeah just delete your database... your migrations don't align with your table schema anymore
then remake
ok
the function in views.py where this happens is
def create_parameters(request, content_type):
parameters_form = problem_parameters_form(
content_type, request.POST or request.GET or None
)
if parameters_form.is_valid():
return create_text(request, content_type)
return render(
request,
"objects/create_parameters.html",
{"form": parameters_form},
)
is this for the 2nd step?
yes, I have create_object() which is called at the start, that one in turn calls this functions to get parameters, and this one calls create_display() to get the display, and that function then saves the whole object. The if parameters_form.is_valid(): from the function I sent above is the one that evaluates to True immediately if there is only a single BooleanField
that's a bit confusing to me...
parameters_form = problem_parameters_form(
content_type, request.POST or request.GET or None
is going to be populated, and if the req method is POST it will always be valid... have you checked what request.POST contains?
hey, how can i get a number of something in a json variable for example
"1": {
"type": "food"
}```
in my case should equal 97
Oh yes youโre right
https://kolkatakurti.com/
this is the website when you click on join Whatsapp
it will show you a pop up for phone no. and I want when user enters no. an OTP will be sent to the no. and they will enter the OTP and click on validate OTP and then the next popup will be shown
please have a look and help me out
pin me
I get this error AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.CustomUser'
This is my user models file ```py
from django.db import models
from django.contrib.auth.models import AbstractUser
Create your models here.
class CustomUser(AbstractUser):
pass```
I set AUTH_USER_MODEL in settings AUTH_USER_MODEL='users.CustomUser'
and this is the users.admin file ```py
from django.contrib import admin
from .models import CustomUser
from django.contrib.auth.admin import UserAdmin
Register your models here.
admin.site.register(CustomUser, UserAdmin)```
try using the following instead
from django.contrib import admin, auth
admin.site.register(auth.get_user_model(), auth.admin.UserAdmin)
hey i just downloaded a static contact page with form in it
and using django im saving info to db
but i want functionality of django forms
modelForms
i dont wnat to create a new form using modelforms
just want
raw form to have clean and isvalid functionality
I get the same error
oke
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Resu-Me</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Courier+Prime&display=swap" rel="stylesheet">
</head>
<body>
<h1>A new way to get Volunteer Oppurtunities to your prefrence</h1>
<div class="description">
<h2>Resu-Me searches our database to find you volunteer <br>oppurtunities catered to your needs and wants.Find <br>a chance to volunteer at a great place by <a href="#">Registering</a></h2>
</div>
<div class="backgroundImg">
<img src = "../static/assets/volunteering_icon.png" alt = "Img" width = "200" id="backgroundImg"/>
<img src = "../static/assets/resume_build.png" alt = "img2" height = "50" id="HomeImg2"/>
</div>
<ul style="list-style-type:none;" id="nav">
<li><a href="#"> <img src = "../static/assets/logo.png" alt = "Logo" height = "50"/></a></li>
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">SEARCH</a></li>
<li><a href="#">CONTACT US</a></li>
</ul>
</body>
</html>```
html
margin-top: 31%;
width: 20%;
height: 40%;
background-color: black;
}
img#HomeImg2{
position: absolute;
margin-left: 60%;
margin-top:25%;
width: 20%;
height: 40%;
}
ul#nav{
width: 100%;
height : 10%;
background-color : rgb(92,82,102);
position:fixed;
top:0;
left: 0;
margin: 0 0 0 0;
}
body{
background-color : rgb(123,123,164);
}
body h1 {
font-family : sans-serif, Helvetica;
position: absolute;
color : rgb(255,255,255);
margin-top: 3%;
margin-right: 3%;
font-size:10vh;
margin-left: 10%;
word-spacing: 0.2em;
text-align : center;
}
.description{
}
body h2 {
font-family : 'Courier Prime' ;
position: absolute;
color : rgb(200 200 200);
padding: 1%;
margin-top : 20%;
margin-left:22%;
width: 50%;
background-color : rgb(100,100,150);
font-size:3vh;
text-align : center;
}
body h2 a{
color : rgb(200 200 235);
}
ul#nav li{
float: left;
display: flex;
height: 100%;
}
ul#nav li a{
font-family : sans-serif, Helvetica;
text-decoration : none;
margin-right: 3em;
margin-bottom: auto;
margin-top: auto;
display: flex;
align-items: center;
color : rgb(255,255, 255);
font-size:3vh;
}
li:hover {
text-decoration : underline;
}```
csss
those r the files
@media only screen and (max-width: 780px)```
well i tried that
and formatted according to
a phone but that didnt scale
to other devices
so idk what to do
you are using scss?
I set seperate media querys for seperate devices
stop interuppting ma phew
<@&831776746206265384>
Muig use modmain
Was this handled?
is anyone especially good at regex / rewrites in apache?
Maybe. You should just ask your question.
can someone show me some Navbar strategies with flask
im currently writing the same variable names in 4 places and i dont like that tbh
i was thinking of adding a decorator to register functions ina global NAV bar variable
but when i did that, it would only work after i used the given view function
@api_view(['POST'])
def taskcreator(request):
serializer=TaskSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)```
@opaque rivet the only hope == u (lol)
Hi, could you please recommend to me some great web where I could learn django???
Udemy
MEGA
In django,I have a 2 models that are vaguely related. Let's call them A and B. I have a function, that, using an instance of B builds a query expression that updates a related A entry's field.
Where should I put this code? B method? A classmethod? just a straight up function?
It's gonna be called every time a B instance is created.
Putting it as a B method for now but it feels wrong to do that with something that modifies a field on another model. Or maybe I'm tired. IDK.
OK i put the part that gets the query expression for the related A on B, and the updating is a custom manager method on A. Thanks rubber ducks.
Hello guys
im newbie to python , and i was just wondering how can i perform http/https request ?
like "https" module in node.js
The requests packages is a pretty easy way to do that
!pypi requests
Hi, I want to display a value by WebSockets from one page to another but I can't get it to aggregate.
is there anyway without downloading packages ?
Source code: Lib/urllib/
urllib is a package that collects several modules for working with URLs...
hey all. I'm assuming theres no way to make a component like react/vue but for a static python fastapi/django site? Just something to pass parameters in that sticks to a ubiqutous language
for instance
<div class="card">
<div class="card-body">
<div class="card-title">
<h5> {{metar.station_id}}</h5>
</div>
{{metar.raw_text}}
</div>
</div>
To something like <Card title="foo" body="bar">
Dazzler is react components in Python, server behind is aiohttp.
thanks. I'll check it out!
Ah, you are the author I presume
I suppose anything like the sort will bring you into a framework. Looking for something pluggable. Thanks though
Hi I am learnings Django and I am getting this error and I can't fix it no matter what I try
here is the HTML
{% extends 'main.html'%}
{% block content %}
<P>Hello you are on the {{page}} page </P>
{% if number > 10}
<p>number is greater than 10 </p>
{% else %}
<p>number is not greater than 10 </p>
{% endif %}
<h1>Projects template</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, nemo. Placeat ex voluptatum in iusto
asperiores nam nobis eum vitae
commodi voluptatibus sunt doloremque, amet dolor velit voluptate. Adipisci, excepturi.</p>
{% endblock content %}
the error
TemplateSyntaxError at /
Invalid block tag on line 7: 'else', expected 'endblock'. Did you forget to register or load this tag?
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid block tag on line 7: 'else', expected 'endblock'. Did you forget to register or load this tag?
Exception Location: C:\Users\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py, line 522, in invalid_block_tag
Python Executable: C:\Users\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.6
Python Path:
['C:\\Users\\user\\Desktop\\devsearch',
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
my views
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def projects(request):
page = 'Test '
number = 10
context = {'page': page, 'number':number}
return render(request, 'projects/projects.html', context )
def project(request, pk):
return render(request, 'projects/single-project.html')
can someone please help I have no idea what i did wrong i have the {% endblock content %} tag
youre missing a % neear the {% if number > 10}
hey which is faster
deploying django site on heroku or netlify
or using apache or ngnix on pc to deploy
in which of these my site will be faster
That's the error alright! Good eye. ๐
Thanks
Are you using a text editor?
VS Code?
yes i am
Surprised it didn't pick up the missing end jinja tag. I'm newish myself, but started on PyCharm. If I miss a tag it flags it in the editor. Not a crutch, but a good catcher of those things
General note. I love UserPassesTestMixin!
ya that's what I was thinking
but i use other languges beside python
so i find it best to use VSC
Ahhh....that makes sense then.
I mainly use react
What do you use react for?
Aahhh...
I'm so focused on teh back end of this app right now...
Building out 7 apps within a web application...
The final app will require JS though...so then I'll circle back to JS. But by then I'll have the back end and application built to serve up the data needed for JS
Oh I know that. However, by focusing server side first, I'll not be leaning into JS except when I truly need the front end behaviour
that sound best
Literally sitting on a web dev bootcamp in Udemy. Spent the past month learning Django. Love it
did a month of Flask before that. Great foundation
just started yesterday
But now my Django project is 166 files and over 4,000 lines of Python code...it's growing
wow
It's so exciting
that's awsome
Yesterday, worked out how to build a form, get partial data from the user, query for remaining data in control table (membership) and then write the combined record.
cool



