#web-development
2 messages · Page 193 of 1
I don't want to manually write code in every API for this, was wanting to know a centralized way
simply render the page
?
I meant in every API view function
I'm doing
post = getpost..
if post.deleted == False
then updatedPost()```
I don't want to write this in every view function is what I meant.
that's posgres, I was asking about MYSQL
the page says: Postgres Specific Fields in Django ORM -> it mentions your Array field -> Logical assumption, Array field works only in Postgres -> Logical assumption: Array field is not working in MySQL with Django ORM
well, I didn't specify it directly, but logically my question also asks if there is something like that in mysql
Hi Pady. Check out https://www.dj4e.com/. You might find it helpful. There's also an 18 hour long video of it on FreeCodeCamp's Youtube channel https://youtu.be/o0XbHvKxw7Y.
Also if books are your thing, Django for Beginners by William S. Vincent is a good bet.
This Django tutorial aims to teach everyone the Python Django web development framework.
🔗 Course Website: https://www.dj4e.com/
💻 Sample Code: https://github.com/csev/dj4e-samples/
✏️ This course was created by Dr. Charles Severance (a.k.a. Dr. Chuck). He is a Professor at the University of Michigan School of Information, where he teaches var...
can you configure django to not use a default database?
i'd like it to fail rather than fall back if you don't specify what database your model belongs
@tepid lark yes, you can leave out the database. most of what I've been developing this year has been APIs fronting services and I don't need the database. All you would do in settings.py is
DATABASES = {}
got called into some other work, but inside this post there is a single file django application included in the discussion here: https://adamj.eu/tech/2019/04/03/django-versus-flask-with-single-file-applications/
@cinder sluice Thank you!
i have no clue why it isn't creating a .db file
it doesn't even give me any error
any solutions?
app = Flask(__name__)
app.config['SECRET_KEY'] = 'kdljfkldjfdlkfjklf'
app.config['SQLAlCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)```
You have a lowercase l for the database uri key.
Hello anyone help me to figure this out.
django.urls.exceptions.NoReverseMatch: Reverse for 'delete-user' with arguments '('',)' not found. 1 pattern(s) tried: ['manage\-users/delete\-user/(?P<pk>[0-9]+)/$']
def DeleteUser(request, pk):
data = dict()
userprofilelist = get_object_or_404(User,pk=pk)
if request.method == 'POST':
userprofilelist.delete()
data['form_is_valid'] = True
userprofilelist = User_Profile.objects.all()
data ['tb_list'] = render_to_string('table_list/tbl_user-profile.html', {
'userprofilelist' : userprofilelist
})
else:
data['form_is_valid'] = False
context = {'userprofilelist': userprofilelist}
data['html_form'] = render_to_string('partial_modal/delete-user.html',context, request=request)
return JsonResponse(data)
<a class="dropdown-item show-form-delete text-danger" data-url="{% url 'delete-user' userprofilelist.id %}">Remove</a>
<form method="post" data-url="{% url 'delete-user' userprofilelist.id %}" class="delete-form mt-4">{% csrf_token %}
<p class="lead">Are you sure you want to delete this user <strong>{{ userprofilelist.username }}</strong></p>
</form>
path('manage-users/delete-user/<int:pk>/', views.DeleteUser, name="delete-user"),
Did you inspect the Remove button in browser to see if the url that's generated is actually good? Because it appears that its barfing on the url being something like manage-users/delete-user/('',) instead of your expectation that userprofilelist.id is something like an int. So then it can't find a url pattern accepting that weird string. So I'd start there to confirm that the template is really making the URL what you expect
I implemented blueprints in my website using a tutorial
And now I'm not sure how to access my database from the terminal
When I try to run the website I get this
So I tried going into the terminal to just drop_all() then create_all()
I am trying to run android on the cloud ? Have anyone here tried that ? I tried using anbox. It's kinda working but i am having stability issues. CPU usage and RAM usages spikes randomly etc
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
subject=request.POST.get('subject')
desc=request.POST.get('desc')
thumbnail=request.FILES['thumbnail']
file=request.FILES['file']
author=request.user
entry=Notes(title=title,subject=subject,desc=desc,thumbnail=thumbnail,file=file,author=author,published_on=datetime.now())
entry.save()
messages.info(request,'Notes updated successfully!')
return HttpResponseRedirect('/')``` this is my code for notes upload it's working fine but when i'm not uploading thumbnail it's flashing error
not from admin panel but only from the html file
MultiValueDictKeyError at /notes_upload/
class Notes(models.Model):
title=models.CharField(max_length=60,blank=False,null=False)
subject=models.CharField(max_length=50,null=False,blank=False)
desc=models.TextField(blank=True,null=True)
thumbnail=models.ImageField(blank=True,null=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
file=models.FileField(blank=False,null=False,upload_to='Notes',validators=[FileExtensionValidator(allowed_extensions=['pdf','doc','docx'])])
author=models.ForeignKey(User,on_delete=models.CASCADE)
published_on=models.DateTimeField(auto_now_add=True)```
error
<form method="POST" enctype="multipart/form-data" >
Hey I’ve been learning python for a couple months, doing dev work is something I might wanna do in the future.
Now I never done any web stuff but I would like to build an online store for my business. Would going and learning django be a good choice for that? Are the other routes I should consider, python or non python related?
yes, look @ frontend stuff too
Wagtail is another layer on top of django that may prove to be useful. Start with a relevant tutorial like https://snipcart.com/blog/django-ecommerce-tutorial-wagtail-cms and see how you go.
Is there a way to obtain real time audio data from a user in a django web application?
websockets?
do I need to use sqlalchemy with flask or can I use raw sql?
you could
whatever you find comfortable ;b
I would say, SQLaclhemy provides simpler output in terms of database management
all your database... tables are stored as a code
and changes from one database version to another one, is just a database migration code stored inside your project
it simplifies stuff a lot for simple projects development
Hi everyone I'm working on the UI for my webapp and I cant figure out how to get it so that lobbies box fills out the remaining space in the container and scroll for the overflow
hey, my dream and what i want to do in the future is to be a fullstack freelancer or work at a big tech company im only 14 and i watched this entire video https://www.youtube.com/watch?v=rfscVS0vtbw and i also know html and css quite well and i want to be a web developer i don't know where to go now and help?
This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you'll be a python programmer in no time!
Want more from Mike? He's starting a coding RPG/Bootcamp - https://simulator.dev/
⭐️ Contents ⭐
⌨️ (0:00) Introduction
⌨️ (1:45) Installing Python & PyCharm
⌨️ (6:40) Setup & Hello Wor...
send me a dm
I am getting an error on my django site hosted on heroku when I try to connect via sockets to a ngrok forwarded port from my raspi. I am getting it timing out but I am not sure why.
Logs:
Code for django view:
PORT = 8080
SERVER = 'redacted'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT!"
class RobotDetail(UpdateView):
model = Robot
form_class = RobotUpdateForm
template_name = 'dashboard/robotdetail.html'
def form_valid(self, form):
self.object = form.save()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
send(form.cleaned_data['path_options'])
send(DISCONNECT_MESSAGE)
return render(self.request, "theblog/bloghome.html")
Hello! Looking for some advice please. I am getting data from an api that has rate limits, these limits are 30 hits every 5 minutes. Is there a smart way to ensure my users cannot go over this limit, like limiting their ability to hit the button that sends teh request? struggling to solution this issue
Hey guys! <3 I want to make a very simple web API, I am not sure which platform to use, Flask? Django? Gunicorn? Uvicorn? D:
It's a very very simple API, just take some data from my DB, process it just a tad, and serve it
I have already added chromedriver to path but then also it is showing error
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.
what to do?
I’m trying to add a form, but for some reason, above the form, it’s showing this field is required. This stack overflow shows what I’m talking about: https://stackoverflow.com/questions/68374208/remove-this-field-is-required-text-above-django-form. Is there a way to remove the bullet point?
hey i am going to build the video chat website using django WEB-RTC with django channels please give some docs or any suggestion is it possible to do this ??
lets work on it together 🙂
okay but why
i am learning channels too
Help needed, in django i have to upload a text file, that is done, then i have to copy the content of that text file to a new file (python normal code ready, dont know how to access that text file from django) then make it available for download
Hey there, I'm hoping to build a dynamic website with user profiles and such.
I've been wondering what is the best python web framework to use in this case?
Flask? Django? Or FastAPI.
I've also been wondering if I should directly send all the content to the browser or use "static" pages with REST/WS APIs to load the dynamic content?
Lol file.url should work
heyy, is there anyone that can help me with Quart?
How can i get button onclick event to work?
i have this simple thing on web
and this in my code, how can i get the input from the input by the button click?
you need a form around it and the form determines where it goes
or you can use js and a listener
whats more simple?
and how to that, cuz im new to web developing and i cant find any info about it :/
I suggest pausing your python work and learning html forms first
I am trying to deploy my ASGI chat app on Heroku.. but I keep getting this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
you've tested locally and it runs fine?
it's likely a settings issue from what I can tell reading online
a missing ENV, a misconfigured asgi.py
bad procfile
I am working on a web app using python and having trouble setting up virtual environment.
I have the latest Python3.9 installed. I am using VSCode. Windows
I have used the following command that is listed in the python documentation and I am trying to activate virtual environment py -m venv env
.\env\Scripts\activate
The result is a message saying 'Command not found'
-are there any commands I should do prior to this?
-I have tried activating inside and outside env folder.
is there a way to undo 'django install' on vscode termial?
So I am working on a banking platform, and when a new user registers, we need to send the submitted data to that user's country's trusted verification API (for eg: SendWyre for US). Now as you can imagine each API has different requirements.
Is there any way I can use a common function to somehow contact all the API's or is it necessary to write a separate function for each?
looks like you are trying to run windows commands on a bash terminal?
Do you mean uninstalling Django?
I was able to resolve both issues. Thank you for the replies!!
@login_required
def profile_update(request):
if request.method=='POST':
user=request.user
image=request.FILES['image']
about=request.POST.get('about')
data=Profile(user=user,image=image,about=about)
data.save()
messages.success(request,'Profile created')
return HttpResponseRedirect(reverse('users:profile'))
return render(request,'users/profile_update.html')```
so i have a form for profile which takes 2 things by user
image and about
if about is left empty it works , but if i leave image empty if breaks and give error
class Profile(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
about=models.CharField(max_length=200)
image=models.ImageField(default='default.jpeg',upload_to='Profile_Pics',blank=True,null=True,validators=[validate_image_file_extension])
follower=models.IntegerField(default=0)
following=models.IntegerField(default=0)```
MultiValueDictKeyError at /account/profile-update
'image'```
according to me error is coming cuz in my form im taking
<form method="POST" enctype="multipart/form-data" >
and when i dont take img this enctype remains empty
so it shows error
not sure
this is the error
Ao turns out, my web application had a sys.exit() error because of gunicorn, I am not sure what caused this, how should I go about diagnosing the problem?
It seems like the request took 30 seconds for some reasons? But how would I know what caused such a timeout? I had a suspicion of the omage upload in said view as it sends it to Cloudinary, but that took 1-1.5s to complete not 30
ratelimit decorator package might help https://github.com/tomasbasham/ratelimit
from ratelimit import limits
import requests
FIFTEEN_MINUTES = 900
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
response = requests.get(url)
if response.status_code != 200:
raise Exception('API response: {}'.format(response.status_code))
return response
Looking to construct a looped select menu using flask and I am unsure about the jinja syntax
{% extends "layout.html" %}
{% block title %}
Sell Stock
{% endblock %}
{% block main %}
<h2> Enter the stock name and the number of shares that you want to sell </h2>
<form action="/sell" method="post" id="sell_form">
<div class="form-group">
<label for="symbol">Choose a stock:</label>
<select name="symbol" id="sell_form">
{% for stock in owned_stocks %}
<option value="{{stock['name']}}" >{{stock['name']}} </option>
{% endfor %}
</select>
</div>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="shares" placeholder="Shares" type="number" >
</div>
<button class="btn btn-primary" type="submit">Sell Stock</button>
</form>
{% endblock %}s
Hi all - has anyone here deployed Django / React with Azure App services that I can pick their brain? I'm having a problem with my main.js not being found after I've collected statics and declared the static location.
current_time = datetime.now()
time = timedelta(weeks=4)
month = current_time - time
filter_by_month = db.session.query(Patient.subid).filter(Patient.create > month).all()
This is my script for filtering patient per month, but is there a method that allows me to get all the list for each month?
cant just increment?
not enough background to understand/answer the question
i have a list of patient in my database, and i have already filter them by current month and day, but im trying to filter the amount of patient for each month(Jan - Dec) (i hope this can make a bit clear)
so, you can query their amount/set in a specific month
but you wish to acquire their amount/queryset for a year?
how your database customer table looks like?
the first part was right, and for second part, sorry for my bad explanation, i was meant to say from jan to dec, amount of patient for each month
so you wish to acquire in one request, amount of users in separate months, not one value for whole year
yup
sounds like SQL grouping
I am a bit rusty on SQL, but I know for sure that it is possible
in raw SQL it involves syntax words like Group By, Having
that sounds like a great idea
https://docs.djangoproject.com/en/3.2/topics/db/aggregation/ for Django ORM should work
For an sql query its just as simple as a GROUP BY var_name clause isnt it ?
https://sqlbolt.com/lesson/select_queries_with_aggregates
SELECT AGG_FUNC(column_or_expression) AS aggregate_description, …
FROM mytable
WHERE constraint_expression
GROUP BY column;
and having aggreating function
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
https://sqlbolt.com/lesson/select_queries_with_aggregates_pt_2
plus potentially can involve HAVING, not sure how it applies 🤔 I am too drunk to think about it
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
HAVING would specify a particular month. SELECT COUNT(*) GROUP BY(month)
i should use code so it doesnt look like im yelling at you
nah, that will work too. having big SQL syntax is... normal.
syntax handed down from old wise peoples
does nginx -> wsgi -> flask make sense for a small project ?
it does for everything
because we use gunicorn as default for flask wsgi
and it can't serve static files
nginx is the best default option to serve static files
other things... like white noise just literally suck at serving static files (taking up to 4 seconds to serve one file)
old alternative solution could be using Apache, but I think Nginx is better, easier and faster at the moment
wow i didn't know whitenoise sucked that bad with static files
thankfully in dev env
plus with nginx you can easily setup additional things to speedup your website by about 100 times with minimum effort
you just enable http2
client side caching (static files css/js will be cached at the client side and will not be requested again until time expries)
and server side caching for urls you can (nginx will serve cached version of the particular url, before the request reaches your python framework
the book is free how to do that
what do you think about uwsgi ?
does nginx still detect and cache static content generated by flask ?
you mean by those jinja2 templates?
yes
yes
it can cache even JSON requests of your REST API end points (making one request to database and caching it 🙂 )
wow
i knew this to be true from experience, had to tell it not to cache to troubleshoot some stuff... just checking im still understanding 🙂 thanks mate!
at least it is working perfectly for GET requests, that I checked
it can cache separetely requests like url?one_var=123&other_var=32434
it will serve/cache the right answers for different query_params
not sure how it works with POST requests since they have JSON data paylod 🤔
it was working perfectly. it was my implementation that was awkward
making me curious but i must resist the rabbit hole
there are passthrough options... thats all i know haha
quite deep rabbit hole, I tested. still falling.
always changing so never ending. which is good..
does anyone know which python tools I can use to start learning web development
String literal is unterminated``` please help String literal is unterminated``` please help
sorry, I meant app development. Does that come under web development?
I am still torn apart, if I should apply Vue or Svelte at the startup 🤔
Vue looks like safer choice, but Svelte is so attractive and easier
eh. the size of usage Vue and its community leaves me no choice but to choose Vue
Svelte is so super attractive, clean, small coding, but I just can't choose it for startup/commercial because of small community and small percentage of usage in commericial (50 times difference at least)
I have these two elements: text hello world. Text being a paragraph element, and hello world being a button. How can I make it so that if the button is clicked, it deletes the paragraph element and the button element itself?
svelte is easier than vue ? vue was the only js framework I could work with
yeah, svelte is even easier than vue.
https://www.youtube.com/watch?v=cuHDQhDhvPE check comparison of the same program in Vue and Svelte
I built a simple app with 10 different JavaScript frameworks... Learn the pros and cons of each JS framework before building your next app https://github.com/fireship-io/10-javascript-frameworks
#javascript #webdev #top10
🔗 Resources
Full Courses https://fireship.io/courses/
Performance Benchmarks https://github.com/krausest/js-framework-benc...
less code, plus I heard inbuilt nice testing framework.
okay I will check thanks
Hello,
I am struggling with getting Set-Cookie header's session value created by Flask-Login.
from flask import Flask
from flask_login import LoginManager, login_user, UserMixin
app = Flask(__name__)
app.config["SECRET_KEY"] = "abcdef"
login_manager = LoginManager(app)
class User(UserMixin):
def __init__(self, identificator):
self.identificator = identificator
def get_id(self):
return self.identificator
@staticmethod
def load_user(user_id):
user = User(user_id)
return user
@login_manager.user_loader
def load_user(user_id):
return User.load_user(user_id)
@app.after_request
def ar(response):
print(response.headers["Set-Cookie"])
return response
@app.route("/")
def main():
user = User(1234)
if user is not None:
login_user(user)
return "Should be logged in"
return "At first log in"
Minimal piece of code ^
Unfortunately, there is not Set-Cookie header in my response.
However, each time I call / endpoint, I see HTTP response in my curl - containing Set-Cookie and session=.eJ... headers!
How to obtain that session cookie value in my Python code?
the biggest killer feature, that svelte is not shipping virtual dom and instead it is lightweight compiler into regular javascript
the size of its build... 10 times smaller than any other framework
Yea, I do recommend Svelte!
so many javascript frameworks makes me feel lost
I was able to throw away other frameworks for some reason or another one
anything that is not React/Angular/Vue/Svelte, throw away because of too small communities / low interest
Throw away React, because it is dirty mix of html / javascript / jsx in one code line
Throw away Angular, because long learning curve, suspiciously small developer satisfaction.
This makes remaning only Vue and Svelte to choose
Vue looks good and solid choice. High job market percentage, community, looks good from afar. 😉
Svelte, looks so super clean, lightweight, easy to learn, battery included (even for state management!) quite attractive and promising to be great in a future. But low job market occupation 😦
when I had a work project I choosed vue because it has vuetify package to make ui creation easy lots of ready made components, svelte has something similar ? cause my css html really sucks
Is there a way of doing this with Django? I am aware that it's possible to do it with JavaScript, but there were some issues with doing it in JavaScript
I mean you could do it by navigating to an entirely new page that doesn't have those elements on it, but you should really just do it with js
what was the issue with js?
@olive patrol
Whenever all the items would get deleted, they would just come back to display. I’m assuming it’s because the elements are stored in a database, and I’m getting those elements fork the database and displaying it onto the screen
do you have some interval on the frontend which is polling the backend and displaying that data every x seconds or something?
No, I’m just getting the items from the database and allowing the html document to be able to display it
That's just what happens on page load, right? So once you click the button and the elements are removed, they shouldn't come back
When I use JavaScript, they’re getting removed from the display, but not from the database itself
ah
Well then you will have to send a request to your backend so it will handle it
So maybe you do want it to be handled by django and not js after all
you should maybe create a form which sends a delete request to your backend for the exact model ID you want to delete
then your frontend will refresh that page, probably and the item should be gone
How would I get the id?
if you have created a database row then the django model will have an id attribute
that is the database id of the row
Can I do Model.id to access it?
if you have an instance of the model, then yes
like if you have a Todo app and you want to get a todo id
todo = Todo.objects.first()
todo.id # is the id
What about with ForeignKeys?
?
My structure looks something like this: class Category(models.Model): … class SubCategory(models.Model): subcategory = models.ForeignKey(Category, on_delete = models.CASCADE)
subcategory
even with foreignkeys, the model still has an id
Now what if there are more than two subcategories? I won’t be able to get the id with first() or second(). What would I use then?
when you render your html I assume you're iterating a list of subcategories right?
Yes
like for subcat in category.subcategory_set
then within there you can send the id to the frontend
and your frontend needs to send the id of the subcategory you want to delete to your backend
your backend shouldn't have to decide what to delete
How would I send it to the backend?
Hey folks, how can I use track argument inside iframe?
<script>
function PlayTrack(track) {
document.getElementById("iframeMusicPlayer").innerHTML = "<iframe src=\"track\" height=\"150\" width=\"400\" ></iframe>";
}
</script>
when using DRF if I wanted to make a post function, to post info from the frontend to the backend, would I be able to return a response, which then I would be able to grab from the frontend? or would I have to create a get function as well, inside that APIView so that I can return a response to the frontend
ok, nvm, just tested it out
you can just return it through the post function
if you are using a js framework, then you can use axios like this to not just post your data to the backend, but also receive whatever you need back, from the same function:
axios
.post(
"function url",
{
whatever_you_are_posting: "whatever you are posting",
},
config //the headers with csrf token, can't make a post request without them
)
.then((response) => {
console.log(response.data) //Do whatever you need with the data that you receive
})
.catch((err) => {
console.log(err)
});
is the iframe on the same domain as your parent page?
then you can use iframe.contentWindow
to access the window/document inside it
like if you have a function in the iframe, you could call it from the parent page and pass your argument, right?
Please have a look at my stackoverflow question, I actuslly just need to know how to format the string, any idea?
document.getElementById("iframeMusicPlayer").contentWindow.PlayTrack(track);
``` something like that?
oh, ok
you could use onclick=document.getEl....
same way
Any django fans in here?
does anyone here knows anything about selenium, how could i find elements by saying that their id contains a certain phrase such as the letter q
//*[@id="assignmentsection_301649"]/td[3].
This is the type of xpath I am working with, everything i am trying to catch shared the id of assignmentsection_number. how do i capture all of those in one statement.
basicly I am looking or a statement like find_element_by_xpath(//*[@id contains "assignmentsection_301649"]/td[3]
Thank you
hihiya
A guide for how to ask good questions in our community.
A guide for how to ask good questions in our community.
!guilds
Communities
The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.
Hello! I am attempting to use uvicorn[standard] for handling websockets requests. I am using Nginx as my web server and doing a reverse proxy to uvicorn for all websocket requests. I can get uvicorn running, but once the websocket request is made, I get an error from unvicorn saying WARNING: Unsupported upgrade request.
Here is the command line I used for running uvicorn uvicorn --log-level debug --workers 3 --uds /home/ubuntu/personal_site/app.sock mysite.asgi:application
I also want to mention that just in case I accidently downloaded the regular uvicorn, I uninstalled it, and then reinstalled it using pip install --no-cache-dir uvicorn[standard] , but I am still getting this error.
I can't seem to figure out why I keep getting an unsupported upgrade request. Could someone point me in the right direction
Also, just in case, here is my NGINX config file
`
server {
listen 443 http2 ssl;
listen [::]:443 http2 ssl;
server_name _;
ssl_certificate /etc/letsencrypt/live/ADDRESS/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/ADDRESS/privkey.pem;
add_header Strict-Transport-Security "max-age=31536000";
location / {
root /home/ubuntu/personal_site/static/vue/personal_site_vue_prod/;
try_files $uri $uri/ /index.html;
}
location /ws/ {
proxy_pass http://unix:/home/ubuntu/personal_site/app.sock;
proxy_http_version 1.1;
proxy_set_header Upgrade &http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
}
location /static/ {
root /home/ubuntu/personal_site/static/vue/personal_site_vue_prod/;
}
location /test/ {
try_files $uri $uri/ /test.html;
}
}
`
@inland oak #help-orange
Hello, I tried to do python manage.py migrate but I got a ValueError from it. I tried to delete the migrations folder but when I try to do makemigrations and migrate again it still throw me the same error.
Hello How can we send update signal in django when model gets updated
Hi, I've been bashing my head on something the past days tat I can not seem to find the answer to.
I'm building a password manager in Django and I'd like my password field to be hidden like a pw field usually is.
Now I have tried using forms.PasswordInput however, this is not persistent and it removes the content once refresh the page.
Is there a way to fix this using only django?
AttributeError: type object 'Oauth' has no attribute 'discord_login_url'
I am getting this error i am trying to make a discord bot dashboard these are the codes
from flask import Flask, render_template
from oauth import Oauth
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html",discord_url= Oauth.discord_login_url)
@app.route("/login")
def login():
return "Success"
if __name__ == "__main__":
app.run(debug=True)
hi, can I disable admin pagination in a django rest framework api?
you need JS for that
I believe
you can include it in your template
but you’ll still need to code it
Hi
What's the difference between
group.reportedBy.add(request.user)
group.save()```
**AND**
group.reportedBy.add(request.user)
It gets saved to the DB even without me doing .save()
abone olarak bu kanala destek verin...
sizin desteğinize her zaman ihtiyacım var... ;)
click it please
and support me...
😉
Hi Im trying to write code for nav bar using flex box Im using two containers and I want use only one container which has a row with items and colum with items
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
these are html and css files
please some one help me with this
hello guys how to delete with this userprofile along with auth user.? I'm not sure how to use post_delete signals. How do I code it?
class User_Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
ROLE_CHOICES = [
("Computer Operator","Computer Operator"),
("Level 2 Support","Level 2 Support"),
("Level 3 Support","Level 3 Support"),
("Application Support","Application Support"),
("System Administrator","System Administrator"),
("Database Administrator","Database Administrator"),
]
role = models.CharField(max_length=50, choices=ROLE_CHOICES)
access_group = models.CharField(max_length=50)
def __str__(self):
return self.user.username
hey can someone help me im very confused on how to use github, i need to basically update files
they said that i need to make a new branch and i did
now how do i upload all the files from my folder that i made into the branch
Is there a rich text editor that works with both react for frontend and django backend? I also want extra stuff like [spoiler][/spoiler] and such tags to work.
i am getting the below error while trying to signup from form
populate_profile() missing 1 required positional argument: 'sociallogin'
while using this
https://stackoverflow.com/questions/14523224/how-to-populate-user-profile-with-django-allauth-provider-information#answer-48182605
Create a github repo/branch
Get .gitignore file from https://www.toptal.com/developers/gitignore (type and search your tech used in your project) and place it in your project root folder
Add origin as the github repo link
Commit
Push/publish to branch
You should really google this
Hi everyone . I came across a very nonsensical error to start my Django project. Does anyone know where the problem comes from?
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x0000028FFA731670>
Traceback (most recent call last):
File "D:\python3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(args, **kwargs)
File "D:\python3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "D:\python3\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
six.reraise(exception)
File "D:\python3\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "D:\python3\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "D:\python3\lib\site-packages\django_init.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\python3\lib\site-packages\django\apps\registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "D:\python3\lib\site-packages\django\apps\config.py", line 94, in create
module = import_module(entry)
File "D:\python3\lib\importlib_init_.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
I don't think that's still the last part, have you tried scrolling down
Though I'm pretty sure you have missed adding some package to INSTALLED_APPS or not installed it...
File "<frozen importlib._bootstrap>", line 228, in call_with_frames_removed
File "D:\python3\lib\site-packages\django\contrib\admin_init.py", line 4, in <module>
from django.contrib.admin.filters import (
File "D:\python3\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module>
from django.contrib.admin.options import IncorrectLookupParameters
File "D:\python3\lib\site-packages\django\contrib\admin\options.py", line 12, in <module>
from django.contrib.admin import helpers, widgets
SyntaxError: Generator expression must be parenthesized (widgets.py, line 151)
.
Problems with the package itself?
I think there's a mismatch between versions of python and django
there were some changes made in syntax which is not supported in older versions of python or vice versa
Thanks . I will try again now.
if you are in the latest django, downgrade it, if it's not about that then your python is either too old or too new
Thank you for your guidance
hello, Is it possible filter by '2021-10-4' <= end_date in sql because it doesn't equivalent in django end_date__lte=date(self.year, self.month, day)
Any django users here?
I got a quick query, I am trying to develop a django template where, I have a base template and then that's inherited by a template and then another template tries to inherit the second template. Is it possible in django??
It looks something like this:
base.html
html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}title{% endblock title %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light w-100" style="height: 65px; position: fixed;">
<div class="container-fluid">
<a href="#" style="font-size: 25px; text-decoration: none; color: #002b63;">Title</a>
<div class="navbar-collapse">
<ul class="navbar-nav ms-auto me-auto mb-2 mb-lg-0" style="width: 80%;">
<form class="d-flex w-100">
<input class="form-control ms-auto" type="search" placeholder="Search..." aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</ul>
<a href="" class="btn btn-success">Login</a>
</div>
</div>
</nav>
<div style="min-height: 100vh;">
{% block body %}{% endblock body %}
</div>
</body>
</html>
index.html
{% extends "main/base.html" %}
{% load static %}
{% block title %}Home{% endblock title %}
{% block body %}
{% block events %}{% endblock events %}
{% endblock body %}
second.html
{% extends "main/index.html" %}
{% block events %}
<div>
<h1>Upcoming events</h1>
</div>
{% endblock events %}
Please ping me
Yes I did but it seems that the second.html doesn't render
well, when you do this
{% block body %}
{% block events %}{% endblock events %}
{% endblock body %}
I believe you are completely overwriting your previous body
actually that's fine
when you say it isn't rendering, what is it doing?
is there an error? is the page just blank
The second.html file's content is not shown
can you paste the view as well?
from django.http.response import HttpResponse
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, 'main/index.html', {})
# return HttpResponse("<h1>This is a Home Page :D</h1>")
you aren't rendering the second template
yeah if you want django to render something you have to tell it to render that thing haha
np
ey guys
So
if I wanna start being a web developer
does any of you have any tips on how to start
is it hard to implement a search function on your website for searching ebay products ?
The unauthorized message happens as a result of the abort(401)
P. S The error has been made dormant in that channel.
Cool, thanks for the tip, I was getting to the same conclusion
Are we allowed to discuss Website automation in this discord?
if run 'npm run build' instead of 'npm run serve' in my Vue dir my bootstrap css files don't get built
Hi all, when would we return Response in django? Why use that instead of HttpResponse?
Hello friends, i'm getting a problem with my API.
So when i make the POST i,ve pass all the validated data in the request body, but when i'm will send the post, one of the fields are not caching the request body value, and i get an not-null error,cause the current field needs data. So i tried to make the request inside the DB and works, the problem its or in the serializer or in the views, but i can't find:
here the error:
the field pokemon its an related field to a pokemon table, but its work,
here a insertion maded insid DB:
someone can hel-me?
help-me
i also did a little web scrape, what problem do u have?
@soft heart I'm new to this server .
welcome
oo
Hello
Hi, how can I see/highlight which elements a given css selector picks? I want all links that are in a list: <ul><li><a href=...> (and I want to follow them with scrapy
is it possible to use flask instead of js for like
<Body>
<button>hi</buttob>
{% if buttonvale == True:%}
<style>
.div {
display: True
}
</style>
{%endif%}
</Body>
flask does not do HTML templating but you can use jinja2 for templating together with flask
you call a function with the template name and a python dict (ca same as js object) with the key/values you need
maybe this helps https://realpython.com/primer-on-jinja-templating/
Anyone know why I get the weird errors in the bottom when using selenium?
"browser status ended" "getting default adapter failed"
Hi I'm using Django, if I want to query objects with filter "not equal" is ~Q faster or a .exclude
anyone knows any crypto exchanges built on django ?
(context django) i am creating a chat app which has models Chat and Message.
i am thinking of creating groups for every chat object and add the user to the group when they connect.
my question is when a user adds a new contact (create a chat object with the other user in members m2m field) how do i add the other user to the group when he is already connected?
With DRF and Django simple JWT, can you get the user's info easily with a route where you can provide the JWT and it returns stuff like your username or mail?
I need help on this segment and I'm kinda lost
Yes you can
User.objects.get(id=request.user)
Do you have an example with views and serializers?
@api_view(["GET"])
def protectedDeets(request):
try:
UserModel = User.objects.get(email=request.user)
user = UserDeetsSerializer(UserModel)
data = user.data
return Response(data)
Is it possible to have 2 apis, hosted on 2 different servers but that share the same domain name but on different endpoints?
If anyone is familiar with cloudfare free ssl. Can I just remove the privacy + protection add on which is I know is SSL and use cloudfare free ssl and implement it. so I can jsut get it for 1.99$?
Ty
thank you for anyone who answers
Domain privacy is hiding who is the domain owner from services like https://who.is/
instead of showing you, it will be showing generic hosting service information
Find information on any domain name or website. Large database of whois information, DNS, domain names, name servers, IPs, and tools for searching and monitoring domain names.
What is Domain protection they are offering, I have no idea. I know only about default domain protection that goes everywhere by default, they would be surely giving it for free anyway.
oh I see
{{ form.hidden_tag() }} can someone explain this to me? this is in flask
is it for the csrf?
Hello, i want to know how can i check if a column named "test" exists inside a table named "node" using php?
SELECT test FROM node LIMIT 1; and see if it errors.
Thank you
I'm on LInux, have python 3.9.7, is 3.10 in beta or safe to use for making a site with Django?
hey i am making a survey with html and css and i want to use flask with python so that i can store the data and hopefully print them on like an admin page. Does anybody know any websites or tutorial on how i can recieve the info that is being put in my survey?
or just know how?
This is part 4 on forms but i would advice watching from part 1. https://www.youtube.com/watch?v=9MHYHgh4jYc
In this flask tutorial I show you how to use the HTTP request methods Post and Get. The POST method will allow us to retrieve data from forms on our web page. In later videos we'll get into more advanced topics relating to login sessions and using POST methods to retrieve secure information like passwords.
Text-Based Tutorial: https://techwitht...
Can I use a model inside a model?
What I mean by this is can I make say a class for the following
class Comment(models.Model):
text = blah blah blah django stuff
class User(models.Model):
comments = []
``` could I then use that layout from the comment class inside like an array?
would that allow me to pull attributes? say I did User.comments[0].text
I'm not sure I understand the question exactly, are you trying to set up a foreign key?
something like
class Comment(models.Model):
text = blah blah blah django stuff
class User(models.Model):
comments = models.ForeignKey(Comment, on_delete=CASCADE)
this way you can link the User's comments field with the Comment model, but ignore this if I misunderstood the question
I'm new to django if you couldn't tell what does the forgeign key do?
I've done things like pygame before so what I mean is could i use a different class and then use those objects inside another class? Like for example in pygame I could make like an class Enemy: and then make like an array called enemys = [] and then just append the enemy object into that array
Could I do the same thing with the comments?
Do you get what I mean? lol
Like use an ArrayField() and then append the comments into that?
It's for my project we bascially have to wrap our pygame project into like a web interface and im just using django because i already know python
a foreign key would define a many-to-one relationship here, so one User would be able to have many comments(field) which point to the Comment model
full disclaimer i'm also pretty new to this stuff so my explanations are probably bad, hopefully someone more storied can chime in and correct me
What's the format of the foreign key?
this might be of help https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/
Like when I call the attribute comments?
Can I use a foreign key inside an array field?
from django.contrib.postgres.fields import ArrayField
class User(models.Model):
comments = ArrayField(models.ForeignKey('Comment',on_delete=models.CASCADE))
Like something like this?
I'm just asking before testing so i dont end up like destroying my db
and have to start the django project again
lol
i think there's no need for that
if you want to access a comment with the id 4 you can filter it from the database like this
comment = User.objects.filter(comment_id=4)
Hey im trying to use a variable from a js file to an html:
var api_key = "..."
<script type="text/javascript" src="restricted.js">
const youtubeKey = api_key;
</script>
but this doesnt seem to work
What's not working?
Why would you set youtubekey to api_key if api_key is already it self?
Can't you just use that on it's own
I wanted to like attach the comments to the user tho
For like organisation sake
i want to hide the api_key in another file far from the main code
so that only "api_key" is visible
read up on database relationships, i think this is exactly what you'll accomplish by setting up a foreign key
you probz don't want an array field of foreign keys, but just a foreign key there
which should be on the Comment model instead
guys i got this problem,my api in django is not caching the data in the request body to send to db,here the error:
what could be?
bassically i'm passing de data in the field but even that i got a NOT-NULL ERROR, but inside db server is everything runnig fine,its only on the client-side
[Django]
I made the model with "inspectdb", but do I have to do "inspectdb" whenever DB is updated?
is python-flask a good option to setup a home-webserver? or do i need something like apache web server?
well, what are you wanting to do? and host?
local service using python-flask
a single app for yourself? flask could run like that internally .. but if you want to host lots of stuff, that's a different thing all together
you have the idea, yes
sure, you coudl write a single app and run it on a machine and have it listen to a port
large service application
for instance, I have a homelab and I host LOTS of things
multiple users
multiple users like how many and you plan to do this on a server in your home then do port forwarding to it from your router?
over 1k at the same time 24/7
yeah, no, you wouldn't want to host that via the simple server flask can throw up, you'll want nginx/apache or something in front
better yet if you know about containers and other things because then you can do real cool things
but ultimately, you're better off hosting what you want out on a real host and not over your home connection
your isp will likely have a clause forbidding that much incoming traffic
plus it'll bottleneck a bit because your download speeds may be high, but your upload is probably hella slow
and again, just so much better to host outside stuff for outside people in the outside
no uploads, only data service
you can try it, but that's a lot of incoming connections that I bet your ISP will pay attention to
depends on your contract with them
Hi, guys. I am looking for and need help from you for a django project.
If you have skills and experience, and interests on it, feel free dm to me
ok, got it, thanks for the adivice
If you have questions, you can ask them here.
And please don't be asking to pay for work; that's against server rules.
But if you still want to host it yourself, yes, put a webserver up in front with wsgi (like gunicorn).
https://medium.com/swlh/mini-project-deploying-python-application-with-nginx-30f9b25b195
hello can someone help me with my problem?
whenever I click a category, that's the error
Hello, so I'm trying to learn Flask and long story short I got a problem with some code and no idea why it even occurs or how to solve it, I'm new to programming and quite inexperienced, my .py code is this:
app = Flask(__name__)
posts = [
{
'author': 'John Doe',
'title': 'Blog Post 1',
'content': 'First post content',
'date_posted': 'April 20, 2021'
},
{
'author': 'Jane Doe',
'title': 'Blog Post 2',
'content': 'Second post content',
'date_posted': 'April 21, 2021'
}
]
@app.route("/")
@app.route("/home")
def home():
return render_template('home.html', posts=posts)
@app.route("/about")
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)```
and my .html code is this:
```<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% for post in posts %}
<h1>{{ post.title }}</h1>
<p>By {{ post.author }} on {{ post.date_posted }}</p>
<p>{{ post.content }}</p>
{% endfor %}
</body>
</html>
All I keep getting is a damn "jinja2.exceptions.TemplateSyntaxError: tag name expected" error message.
Hey! Anyone up? I had a query regarding Flask
!code-block
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
A guide for how to ask good questions in our community.
I am working on a React-Flask project and I am getting this error,
TypeError: The view function for 'logout' did not return a valid response. The function either returned None or ended without a return statement.
Where I am returning a response. The Code is
@is_logged_in
def logout():
if request.method == 'GET':
session.clear()
return 'OK'
return 'NOT'```
from flask import jsonify
return jsonify(status="OK")
as a choice
you can also return any complex dictionary of information in the jsonify
from flask import jsonify
return jsonify({"status":"OK", "another_var": 123, "or_even_entire_list": [1,2,3,4]})
you will be able to query those endpoints from react with fetch operations
Sure, I'll try this.
Here's another error. I am using sessions from the flask library to work with sessions but I am unable to get the session variables.
Here I am setting the session, if dbm.check_login(username=username, password=password): session['logged_in'] = True session['auth'] = auth.get_auth_key(username=username)
And I am unable to access the same here, ```
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
print(session)
if 'logged_in' in session:
return f(*args, **kwargs)
else:
return {'error': 'Session Expired'}
return wrap```
flask provides with auth library actually named login manager
it would be less reinventing the wheel solution
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I'll check
Hey guys, just to confirm it, you can create a website with PyCharm only, right?
yes
Oh that's cool
how do I import in brython from django's static?
I'm using a PyCharm right now creating an E-Commerce
I'm redirecting <slug>.py but that doesn't work for directory modules
Damn, it is not possible that you can teach me how to build a website, is it? I am interested in web development, game development and cyber security, so it would be great if you could teach me sum
have you develop any website using Python?
I suggest you start watching on how to develop a website using Python, for starters you can use Django as a framework
I'm trying it with django with brython. Not having to deal with javascript is so nice.
nvm I got it
My guy
I started using python for 6 days ago
I see, after you learn Python, start learning Django Framework
it's easy to understand
I don't understand this, you're talking about the IDE not the programming language right?
if so, yes PyCharm can develop a website
Legit
Because I do understand a bit python yk
But I am hella interested in web development, game development and cyber security
if you understand python then you will understand Django easily
it's fun developing website using Python
I came from PHP but when I learned Python, I switch immediately to Python and start learning Django
Is there much different between dj and python?
Django is a framework came from Python, some people use Django as a back end for their website, some use Flask
So ehm
Lemme ask you dis question
Is it possible you can teach me how to build a website?
Pretty sure the subject is a bit too complex to be taught by one person over discord. You have to "do your own research"
Yea but the thing is
Idk what the fuck I gotta search
Should i really just go on fucking YouTube and search "how to build a website using PyCharm"?
PyCharm is 'just' a fancy editor designed to make writing python easier, not sure why you're so fixated on it when it comes to web development. In terms of Django start here: https://docs.djangoproject.com/en/3.2/intro/install/
For flask start here: https://flask.palletsprojects.com/en/2.0.x/tutorial/
fyi, you don't need fancy editors to code, you could even make a website with python using just notepad
hey guys can anyone here help with a django jwt issue?
I suggest you watch Django Tutorial so you have an idea of step by step on creating your own website
Which I mainly use
Thx
here you can watch Mosh, he's a very good teaching things and you can understand it very easily
Django Tutorial for Beginners - Learn Django for a career in back-end development. This Django tutorial teaches you everything you need to get started.
- Get the complete Django course (zero to hero): https://bit.ly/3A7l7qj
- Subscribe for more Django tutorials like this: https://goo.gl/6PYaGF
Other resources:
Python Tutorial for Beginners: ht...
im learning from idk how many months
more then 3-4
whole day
and this guy taught in 1 hr
wtf lol
Hey! If we are taking formData input type at the frond-end in react, then how can we handle the same at in flask?
At the frontend it is being stored like, formData: new FormData()
if you're very new to programming and never learn any programming language, it will be difficult but if you have any programming background it will come to you easy
well for me anyway
dont crack jokes bro
i was good in web d foundations before jumping into django
i was a flask dev
if u wanna be a noob just do less time
but for practice different use cases
different places different methods
for a big
intermediate n a small app too
u need to give time
if u wanna be a good dev
indeed, more time, more effort
yes
Having an idea of how things work and being able to put it all in different case scenarios is a different thing!
no more discussion
i wanna be sigma male
so just told my suggestion
u can surf yt n all for more info
if u just wanna make simple app it will take less then a day
but to master foundations 3 months
and for advaned stuff more 2-3 months
In flask, you access formdata using request.form
ig its request.FORM.get
Sure Man. I'll check
!d flask.request
To access incoming request data, you can use the global request object. Flask parses incoming request data for you and gives you access to it through that global object. Internally Flask makes sure that you always get the correct data for the active thread if you are in a multithreaded environment.
This is a proxy. See Notes On Proxies for more information.
The request object is an instance of a Request.
!d flask.Request.form
property form: ImmutableMultiDict[str, str]```
The form parameters. By default an [`ImmutableMultiDict`](https://werkzeug.palletsprojects.com/en/2.0.x/datastructures/#werkzeug.datastructures.ImmutableMultiDict "(in Werkzeug v2.0.x)") is returned from this function. This can be changed by setting [`parameter_storage_class`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.parameter_storage_class "flask.Request.parameter_storage_class") to a different type. This might be necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but instead in the [`files`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.files "flask.Request.files") attribute.
Changelog Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
(context django) i am making a chat app which have models Chat and Messages.
when a user adds a new contact
i create a chat object and send a message to a group containing all channels (i named the group global)
and then check if the connected user is member of the chat , if yes then add it to group of that chat
my question is
should i be sending a message with the socket to create the chat app or do it with just ajax and send the message to the group in the save method of the Chat?
@cerulean badge I'm starting a build soon that requires chat. Would love to snap that module in when you're done if you don't mind me using it?
(context django) how to check if presence of list of objects in m2m field?
all should be present
hey i am going to build the video chat website using django WEB-RTC with django channels please give some docs or any suggestion is it possible to do this ??
Just try to get intersection of two list
(context django) i have a Chat model with m2m to User model, how do i filter all chats having members both user1 and user2?
I know that this is a pretty general question but one of my cousins suggested that I build a webapp that runs on a python server for a school project. The problem is that I have no clue what that is and whenever I google what that is it just gives results on how to make one not what it is. Sorry if it is obvious but thank you if you can help me. Even if you can share a link or anything like that it can help.
why this happen ?
A web application (or web app) is application software that runs on a web server, unlike computer-based software programs that are run locally on the operating system (OS) of the device. Web applications are accessed by the user through a web browser with an active network connection. These applications are programmed using a client–server model...
thanks for the answer @fickle garnet and @inland oak they helped alot
Hey! How can I serve an image file saved in MongoDB? Any solution instead of saving the file locally?
you should save images and other blobs on a filesystem.
though with mongo, it uses bson, which supports raw bytes.
Okay, so I should save all the files in the file system only?
pydantic question.
Is there a good way to make all fields optional for a query but make them dependent. In case of one query arg is used few others must be used?
I am going to start learning how to make webapps but I am unsure whether to use flask or fast api? Which one will be better/easier to learn?
Well, are you wanting to build APIs (which both are good at), or a website (which I'd say Flask is better at), or what?
is there a point to having jquery if u have react
Nope.
html, css, django(python), JS, react, jQuery, SQL for this would u just take out jQuery
Looks about right
When you have JSX, there's no need for jQuery
hi
I want in my program that when a person select a word, with that word appear in a file txt and can upload it
someone to help at priv
im not to sure what would be the best option for me to use, but im webscraping data off of a website which i want to then display on my own website. how should i do this
currently the only option i know of doing would be sending the data with socketIO to a node server but is there any python packages which allow me to edit a webpage like this?
how do i promote websites/social apps
um hello what editor can you use for javascript?
VSCode is the most common one from what I've seen, but Webstorm and others are used too
thanks
is javascript better or html/css for a website?
you need both.
they do different things
ok
in flask routes can you make *args? i mean
@app.route('/route/*')
def route(*args):
return str(args)
/route/a1/a2/a4/
['a1','a2','a4']
You can use query parameters and access them in your 'route' function instead
yeah, but im asking is there a way to do like this
i mean ofcource there should be a base route get method, maybe i can overide that instead if there is no *args, but i just cant find that function
I don't understand what you mean by overriding. What exactly is your route/function supposed to do(maybe I can help with that)?
Hi Guys,
I need some guidelines and info.
Can i integrate jitsi with my django project?
Jitsi is an open source video calling project.
https://github.com/jitsi/jitsi
hey peeps! Any django-crispy-form wizzards around?
I seem to have a question that has no answer in the docs
I am trying to set type attribute for an input field but not sure of the **kwarg name and can not seem to find it anywhere... it's not type, as type() is a reserved keyword. there's ref. to class for which is css_class but not for type
I am trying to render a form with crispy.helpers and this form is meant to have password field that can be toggled and I'd like to achieve this without setting a widget
I'm making a simple Django project (Todo Application)
So, let's say there are multiple users and they login and add a Task.
Now, while displaying a task, I have used slug in URL to display a particular Task (for that particular user)
Now I have added slug as unique for that Created date (when the task was created). This works fine but when I try to save a new task under another user with the same slug for lets say user X, it shows error. Which is expected.
How can I avoid this behavior? Is there a way where I can limit slug uniqueness only to particular user and particular Created date. But not globally.
That is, multiple users can create same slugged Task for any particular day, but one particular user when creating a new task for that day should get and error that this task is already added.
Hope this makes sense.
In short, unique table for every user.
maybe not related here but. but i have a website i want to scan that displays a red square around a specific kind of part of the site. but it is not in the html its javascript based i think
any guide on how to send mail from django rest framework
i want to send mail for reset password
any blog tutorial guide ?!!
Hi!
I need to make a python script which, given a php web page where news are posted, it takes the link of latest posted news and print it
How can i do this if there is a way?
requests library + bs4 library to parse it, as the lightweightest easiest solution
if there would be some sort of difficulties... then firing heavy artilery in form of selenium
Hey guys so I am following a tutorial and it tells me to do this step
This one
So I tried making templates.py but it didnt work that way
So can please some assist me on how to do this step?
Anyone????
I'm not sure why you will need templates.py
You need a directory "templates" in your app directory, which will store your HTML files.
Project
-->App1
------>templates
---------->App1
-------------->index.html
-------------->something.html
---------->base.html
-->MyWebsite
Anyone else here build crawlers? seems like the best channel to ask in
whats the difference between a crawler and a scrapper ?
yeah very, it's doing it at scale that becomes complicated
you want to crawl a page or two, that's cake. You want to do 20 million pages a day, that's a bit more complex
Hi can anyone please help me? i am trying to pre populate the wtf form from given data but its not working for some reason !
@app.route('/write',methods=["POST","GET"])
def write():
prevLetter =Letters.objects(author=session["user"]["username"], status = "draft").first()
form = WriteForm()
if prevLetter :
print("block 1")
form.title.data=prevLetter.title
form.content.data=prevLetter.content
return render_template("write.html",form = form)
what does your template/html look like?
ah i figured it out. i had script tag clearing my text fields
awesome debugging
lol sorry to bother
no problem at all
i'm donig python exercises and i didn't know the list() method can turn a list into an array
i'm perplexed by that
is it different because of how an array is stored in memory as opposed to a list? In python at least
oh my god i'm an idiot sorry guys.
so what i had was zip(*2d_list) and that zip function returns a damn zip object which returns a tuple
doing list((1,2,3)) turns a tuple into a list lol
The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and return it. In this tutorial, we will learn about Python zip() in detail with the help of examples.
Hey, I have a problem with tests in django
class AboutPageTests(SimpleTestCase):
def setUp(self):
url = reverse('about')
self.response = self.client.get(url)
def test_aboutpage_template(self): self.assertTemplateUsed(self.response,'about.html')
Running test return ```AssertionError: No templates used to render the response
in views ```py
class AboutPageView(TemplateView):
template_name = 'about.html'
Could someone help me with Django problem?
I have connected my Django server to PostgreSQL, created 2 tables for car and driver with help of python manage.py migrate, then removed those tables inside the PostgreSQL bash with help of DROP table, but now I still have them inside my permissions
but there are no car / driver tables in database
Advice: If you're going to do db migrations, do db migrations. Don't mix doing migrations and manual changes.
i got a question regards python web scraping, i saved all the data for each section(title, date, etc) in a indivisual list, and saved in a big list, something like list = [[title], [date]], and access by index element. However is there a method allows me to find any match string as my target item inside the date and remove all the text with that index element
Its a templating engine! Are you using jinja2 with flask by any chance?
Ops, wrong phone number
Not necessarily a loop. Though yes the engine allows loops. such as
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
It introduces loops over arrays and dictionary data, if conditions and other programming logic into your html code writing
Allows writing much... Smaller code to write html and css (or even js). Especially useful for menu and tables for example
well i kinda understood is is like a var to store you html so u can reuse it
That is too
The main purpose is DRY, to have much more reusable code
Defining menu code once for all pages in the site for example
like a nav bar
oh
sure
i maen
idk what advil is but i'll take 3
oh im using Django with python
is django not the best? 🤔
😦
then node.js
😮
if i wanted to be difficult I'd use straight up C or even binary to program my website
bs 😉
js in backend, still bs ;b
well, yeah, quicker I guess a point
more framworks
GO?
yeah
rust is used 10 times less than golang in job vacancies
about what am I supposed to think
its going to be the most used
hello
I decided to help out my friend and make her a website for her business. So far it's been going smoothly, but I've never done any page at all and now I've bumped into a problem that I can't resolve
I wanted to make a navigation bar with some buttons and an icon. I wanted to make the three buttons evenly justified and to that I wanted to add an icon to the left. However I can't make it "jump" in line with those buttons. I have made some attempts, unfortunately non of them worked for me.
could anyone point me to my desired result? I would be very grateful
My code looks like this:
html
<img src="static/icon.png" width="60" height="50" alt="icon" style="vertical-align:bottom" >
<!-- <ul><li><img src="static/icon.png" width="60" height="50" alt="ikona" style="vertical-align:bottom" ></li></ul> -->
<ul>
<!-- <img src="static/icon.png" width="60" height="50" alt="ikona" style="vertical-align:bottom" > -->
<li>Offer</li>
<li>Contact</li>
<li>About</li>
</ul>
</nav>```
css
```ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: rgb(30, 57, 88);
display: flex;
justify-content: space-around;
}
li {
font-family: sans-serif;
color: rgb(255, 255, 255);
/* text-align: center; */
padding: 16px 16px;
text-decoration: none;
}
li:hover {
background-color: rgb(86, 152, 190);
}```
I tried to make two unordered lists side by side, but that didn't work either, that's why I have those img sources in comments, I was trying out things
I also thought that it will help to put an image next to unordered list, but that put my icon on top of the navbar
is it a good idea to use webp over gifs? I have a a couple of gifs loading at once so I figured I'd convert them to webp but I heard there's some browser compatibility issues
guys quick question. you can deploy 2 apps in one cloud server right? like for example django backend and angular frontend at the same time?
Hello Everyone!! Urgent help needed!!
Whenever I open localhost:8000 or 127.0.0:8000 it gets redirected to https://localhost:8000/ or https://127.0.0:8000/. It started happening after I added SECURE_SSL_REDIRECT = True in my settings.py (i am using django).
that what SECURE_SSL_REDIRECT does ;b
it redirects from http to https
using just http is unsafe in production, we are supposed to use verified cerificates and only https mode
oo
I am doubting you're hosting on https.
question: lest say that i have 2 webpages for 2 different purposes: sales and inventory, both in the same server and different ports, but both web page use the same variables, lest say session["user"],
do that will create a conflict if the user A login sales and user B login inventory in the same pc?
Hi all, got a question and I haven't found a solution by googling yet. I am using requests and bs4 to do some scraping. Over the past week the page I have been successfully scraping via AWS Lambda for 2 years made a change and is now sending a 403 response if you don't have cookies enabled ( javascript: var cookiesEnabled=(navigator.cookieEnabled)? true : false; ). Does anyone know a way around this? I believe I need to specify a user agent and somehow enable this, but that's only a guess. Any help is greatly appreciated!
also i have no documentation, php had a way to split session by user, but i have not find how to do the same in python-flask
can i use session["inventory"]["user"] ?
Help!! me, I want to take an existing url from the web and make a backend for it, can I do it with django?
I think you need to do a little research on how hosting, domains, DNS, and some other things work. It's not a small topic to cover.
Roughly, yes you can host a site (frontend AND backend) in Django and you can point a domain at it. But you have to get it hosted. And have an IP to point your DNS to. And so forth and so on.
Sounds like you may also want to check that site's TOS (terms of service) to make sure you're even ALLOWED to be scraping them. And if you are not, we definitely cannot help you get around that.
understood, thanks.
it's proboards.com, free message board hosting, we use it in a fantasy sports league to keep track of certain things, and then I in turn post links to the threads in slack.
so nothing too critical or anything 🙂
right but their changes could be because they are trying to mess with bots by having that js check on cookies
understood, not trying to argue w/ you
oh I know, sorry if it is coming off harsh
in my googling i found people having this issue w/ cloudflare, and it looks like they are now using cloudflare 🙂
selenium/chromedriver looks to be the workaround, just gotta figure out how to do that in aws lambda now
I did look at their TOS and spidering/crawling/etc is forbidden. So best of luck as it sounds like you have a totally non-shitty bot (like a sneakerbot or whatevs) but yeah ... sorry. :/
Django or flask?
They’re both good, but Django is more popular
First off, is there any reason why you are using var instead of let / const ?
Second ...
```js
/* code here */
```
you can edit your message for the second part
Third, I know that error.
// When you did this
progress.max = requiredclicks;
// The result of this (which wouild be outputted to the console) was actually false
console.log(Number.isFinite(requiredclicks));
// Put this last line before the `progress.max` assignment line
// or add that argument to the `console.log` that outputs `requiredclicks`
idk lol
NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, or a non-number ... all would be invalid for that.
Also, the progress bar has a minimum of 1 ... I think ... lemme check
wym
oh ... after testing <progress> tags default to a missing value attribute (the "indefinite" state) and also default to max being 1 (but it can be any finite number that is positive )
Somehow your program tried to set progress.max to a value which is not valid ....
yeah.
how is requiredclicks not valid
somewhere, requiredclicks was not a finite number.
what does finite mean xD
finite means it is a number, and NOT one of these special values:
NaN // Not a Number
Number.POSITIVE_INFINITY // can get it by a huge calculation
Number.NEGATIVE_INFINITY // same as above but it is a negative number
You can get one of those easily if you divide by zero
what is your requiredclicks getting set to?
level * 250 + multiplier * 50
Ah, I think I see why.
When you call loaddata() your localStorage might not have level set (or it was cleared), or the value you got is set to a non-number.
By the way, localStorage IIRC always returns a string if the value is set (I forgot if it returns null if the value is unset or not)
oh ok
so i should set level to local storage?
level = parseInt(localStorage.getItem("level"))
i have
.... you probably should make a class to help hold the data in memory and let that update your localStorage for you
Ah.
Lemme find the link
Note that The Coding Den may have had a recent issue with people being banned unfairly, and for me being one of them much earlier than I heard for that "purge" ... well ... I don't recommend going there.
https://github.com/mhxion/awesome-discord-communities
do u know how to use classes
@round plinth
if u do do u think u can put that into a class for me
I can do that, but it would be spoon feeding you the code.
hi guys , how are you
I have a mini project I'm working on and I setup a little flask site to interface it remotely and I left it on today (It's port forwarded) and I got these requests seemingly from nowhere:
I'm assuming this is some bot testing a security glitch on something like wordpress but anyone know any more info on it.
The end of the url I blocked out is Mozi.m+-O+/tmp/netgear;sh+netgear&curpath=/¤tsetting.htm=1
a cyber attack lol
where's your flask site deployed to?
perhaps this is something for the #cybersecurity channel to help with
It's not an actual site just something I had so I could interface with that program that one day and alright thank you.
I was just home hosting it
Is codeacedemy a good resource for learning flask?
For any web development related assignment kindly HMU .Quality and on time delivery assured.I can provide samples on request.Thanks
i'm also learning flask. I haven't used codeacademy for flask. However, I've been practicing with the documentation and docker. What's your developer experience like? e.g. absolute beginner
I have basic experience in c++ and c# I know the basics of python but I just started python around a month and a half ago and I am starting to learn flask. So a beginner
I used the quick start guide https://flask.palletsprojects.com/en/2.0.x/quickstart/#
maybe this https://github.com/mjhea0/flaskr-tdd
Thank you I will check it out
get comfortable with python first in my opinion. I'm doing this https://exercism.org/ @turbid horizon
Ty that will definitely be helpful
good luck, i'm also learning. keep at it.
@turbid horizon https://github.com/humiaozuzu/awesome-flask#tutorials
I've never worked with Web Auth before. I have a Flask site I'm putting together that allows OAuth "Sign in With X" only for logging in and I'm unsure what to do with their credentials when they sign in. Do I just take their Email Address and check for existing user and otherwise create it? Then for keeping logged in how does that work?
Actually I think I got it, I needed to utilize Flask-Login with Flask-Dance
hi is anyone here an app developer?
Loads of people
hello can anyone tell me how to publish a site using VS code?
have made i want to get a url and all and make it available for public use
deploy it on firebase
@native tide so you have like the html css and javascript files?
actually i just want to test the file is basically a hello world
what is firebase?
oh you are just starting
yes
um
okay there are alot of things to learn
you gotta learn how the internet works
things like hosting domain names etc
just google it or watch a video on youtube
um can you explain this in detail to me after half an hour
i have a school class
thanks
bro just google it or watch a youtube video
um ok
Hi friends, I am after a bit of help, im trying to scrape a table off a website, but i need to fill out a search bar before the table is shown, I want to figure it out for myself but not sure what to search up on google, what are these websites called?
eg copy paste the url into another browser (or python) and the table is reset and search terms need to be reloaded
I can copy paste the table but then need to convert to csv?
Can you give a video or something about it?
Hey Everyone!! Urgent help needed!!
Whenever I try to login in my Website it gives a 403 Forbidden Error
The Message: CSRF verification failed. Request aborted.
But I have {% csrf_token %} in my login form
Also I am using Django!
Github Repo: https://github.com/Jonak-Adipta-Kalita/JAK-Website
can you make a website with only python or would you also need html
U will also need html
I would say knowing some CSS is also preferable if u wish it looking good
There are CSS Frameworks for people brain-dead in it. bootstrap for example
As easiest and fastest solution
To have good looking site
Hey everyone goodnight, so I've been specializing in the MERN stack but I don't really know any frameworks/libraries besides socket.io... What technologies would you guys recommend?
Are you wanting to branch out from the MERN stack? I am assuming so given your asking on the Python Discord?
This guide with Flask and htmx seems very interesting: https://github.com/talkpython/htmx-python-course + https://github.com/rajasegar/awesome-htmx
Student details, source code, and more for our HTMX + Flask: Modern Python Web Apps, Hold the JavaScript course. - GitHub - talkpython/htmx-python-course: Student details, source code, and more for...
yes you would
Yeah basically
I’ve heard development on django and flask is quick but it could be slow at times
Hey Everyone!! Urgent help needed!!
Whenever I try to login in my Website it gives a 403 Forbidden Error
The Message: CSRF verification failed. Request aborted.
But I have {% csrf_token %} in my login form
Also I am using Django!
Well flask or Django is the place to start, I would try a tutorial in both and see which you prefer
<!DOCTYPE html>
<html>
<head>
<title>Store</title>
</head>
<body>
<h1>Jay Derep</h1>
<strong></strong><p>web dev</p></stong>
<img src ="https://cdn2.iconfinder.com/data/icons/avatars-99/62/avatar-370-456322-512.png" width="100" height="100">
<hr />
<i></i><h2>Summary</h2></i>
<p>i like doing web dev its fun</p>
<hr />
<b><h2>experiance</h2></b>
<ul>
<i><li>html</li></i>
<p>i am learning</p>
<br />
<i><li>css</li></i>
<p>still learning</p>
<hr />
</ul>
<table border="1">
<h2>skills</h2>
<tr>
<i><th>Languages</th><i/>
<td>python</td>
<td>c#</td>
<td>kotlin</td>
</tr>
</table>
<i><h2>Contacts</h2></i>
<a href="link one" target="_blank"></a>
</body>
</html>```
Has this error
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'stocks.Investor' that has not been installed
stocks is added to installed_apps and auth_user_model is also configured
How to solve this error?
how to link html front end with python backend?
i found this code on net:
<form name="search" action="/cgi-bin/test.py" method="get">
Search: <input type="text" name="searchbox">
<input type="submit" value="Submit">
</form> ```
but I dont know what is cgi
Presumably a resource on the site where this form is hosted. If the form is on a domain like example.com, /cgi-bin/test.py is going to be found at example.com/cgi-bin/test.py
Do you have a folder locally cailled /cgi-bin?
my backend name is fetcher.py stored in same folder as my html form
You should be able to set that location to fetcher.py then, but like the action field just sends the data as an http request to that "endpoint", and if it's a python file, I'm not sure how that will consume it
Where was that tutorial?
stackoverflow
my question is will this work?
<....... action=".......\fetcher.py">```
instead of cgi?
It will not, since that is not something that accepts an http request
by the way what is cgi?
You could use an http server on your backend? Something like flask or django or starlette
CGI is just the name of the folder for that specific problem
nothing special?
Could you link that SO post?
yes
I have created html form with text box and button
enter ur search keyword
My requirement is to pass the text box value in to my test.py code, is there any way to do it.
Please suggest me how do it.
another query. Actually i wish to store the value written in my form.html to fetcher.py
Interesting, I think I was wrong then. CGI is another http framework
will this cause a problem ? if i dont use cgi?
Both ... and its alternate name are improperly configured
Domain does not resolve to the GitHub Pages server. For more information, see Learn more (NotServedByPagesError). We recommend you add an A record pointed to our IP addresses, or an ALIAS record pointing to suiniee.github.io.
how do i fix this? i dont understand the error
Yes, just a python script on it's own won't accept an http request, but there are many frameworks to have an http server
Like mentioned before, http and cgi are builtin, but 3rd party frameworks provide more utilities
Those include flask, django, starlette, fastapi, etc
then how to create a cgi-bin python file?
@native tide, are you familiar with fastAPI?
Yeah I've used it before
I prefer you ask here since others can correct me, and I'll be leaving soon
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
- a POST request with a boolean parameter that returns the current date in yyyy-mm-dd hh:ii:ss format if the parameter is set to true and returns the date in yyyy-dd-mm format if the parameter is set to false
- a GET request that retrieves the value of a counter of the number of times either of the two endpoints was called
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
from typing import Optional
import threading
from fastapi import FastAPI
from datetime import datetime
app = FastAPI()
counter = 0
lock = threading.Lock()
@app.post("/fecha")
def mostrar_fecha(formato : bool):
global counter
with lock:
counter += 1
if formato:
fecha = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
else:
fecha = datetime.today().strftime('%Y-%m-%d')
return {'Fecha':fecha}
@app.get("/counter/")
def count():
global counter
return {"Counter":counter}
Is that correct?
I mean, it works
but it's an important assignment, and wanna get full score
It looks fine yeah, but depending on how heavy the load to your server is, using that lock inside the function can slow things down
QUESTION
Django
When using django signals do we have to write each signal for each model?
for example if we have a models User, profile, Education, and has OneToOne Relation with Profile and Forignkey with Education so do we need to write signal for each of the model separately or only one signal for both?
I.E, if you get two requests at the same time, you have to process them synchronously because the lock is held by one request at a time
Now in this case, since the lock is only held for a fraction of a second, it's probably fine
I don't know what your professor/teacher is looking for though
python script uses import cgi is that sufficient
The server won't overload
Actually the lock may not be necessary since you aren't using an async function
yeah
I'll delete it
I haven't seen the lectures lol, I should
He just wanted us to learn basic backend stuff
Thanks for your help 🙂
i need some help in cgi. has anyone used this before?
You still need to use cgi to get the form values. For instance:
import cgi
form = cgi.FieldStorage()
form.get(...)
yes. my question is :
is writing import cgi sufficient to create a cgi-bin file? or I need to install some things too?
in simple words does the code sent by you sufficient to change a nomal .py file tocgi file?
Yes, but, you also need to put it somewhere specific
also does a cgi file work if not stored in a cgi-bin file?
For instance, the SO post uses cgi-bin which is the default for linux
What OS are you using
So you can use it on windows 10, but the process is a bit involved. You have to install the CGI element.
https://docs.microsoft.com/en-us/iis/configuration/system.webserver/cgi
In the part where it's specifying how to install it, windows 10 uses the same instructions as windows 8, and everything from there on is the same as well
I've gotta run now, but I think that's the gist of it
after installing the cgi element?
how can i connect my flask code to my domain?
If you guys have any experience working with sockets and ngrok, I have an interesting problem I have not been able to solve combining django with sockets for networking between server and raspberrypi. Full question: https://stackoverflow.com/questions/69503197/ngrok-with-python-and-raspberry-pi
Or Join
#code-help-voice-text
@native tide I installed CGI now what is the next step?
https://hastebin.com/xufogalotu.rust
i am getting this error
the error tells you what you need to do, you can't call a synchronous method (get_object_or_404 from the ORM) from an asynchronous context
how would i make a button that would be at center for every screen size?
im making like a website through html and i have this python file for a game, i was wondering if i can somehow make it so u can run that python file through the website
without needing to download the python file and its code
in CSS?
what does the Python file do
you want to host your code somewhere
and then update DNS records to make your domain point to where you're hosting the code
I got it, thanks.
its a turtle graphics based game
then no
what abt a pygame based game?
the principle is fundamentally the same
your browser is (basically) incapable of running Python code
oof
Hello
I've a query as I'm just a beginner
I have got command on basic Python like OOP, loops, functions, strings, variables, lists, data structures and algos.
I'm willing to learn Django now.
Do I need to learn HTML and CSS before I jump to Django?
not necessarily
BUT Django has a lot of magic in it
you might get kinda lost
So how should I begin
I know about basic html though like what are simple tags and making a simple site with just head body and p tags lol
Is this much HTML enough?
So how should I begin?
with SQL or with HTML/CSS?
because it controls layout
How much SQL do I need to learn?
People say you don't need much SQL to learn for Django unless you really need to dive into database engineering
My teacher said you need only 1 week of SQL practice and that's all.
is this a channel where i ask about selenium? or diff one
How to retrieve post data from a custom form in django?
you just need to know the basics of sql. in django you almost never write raw sql code, but it's important to understand how django does it and what-not
request.POST inside of your view function should give you POST data assuming you sent a post request
Hmm
{% %} just allows you to use logic inside of your html before it is displayed to the user (template pre-processing)
def my_view(request):
if request.method == "POST":
username = request.POST["username"]
like this
it gave me a multivaluedictkeyerror
the html input fields need a name attribute
that same name u use to access the value of it
o ok
and 2 more things
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('mail')
age = form.cleaned_data.get('age')
password = form.cleaned_data.get('password')
htmly = get_template('user/mainpage.html')
d = { 'username': username }
subject, from_email, to = 'Welcome!', 'abc@gmail.com', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
messages.success(request, f'Your account has been created !')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'user/sign_up.html', {'form': form, 'title':'register here'})
i saw it used to reuse html