#web-development
2 messages Β· Page 115 of 1
I'll come back later
I finished authentication
oof
now what should I do
Which (on sign up / login) you should be sending a token to your frontend which then saves it as a cookie.
@native tide how can I do this?
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def login(request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'error': 'Please provide both username and password'},
status=HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
if not user:
return Response({'error': 'Invalid Credentials'},
status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key},
status=HTTP_200_OK)```
I found this example
i think its right
how do I save the token now as a cookie
I know how to get the token now
Yea so u return JSON as a response then use js-cookie to save it as a cookie
is it a module
then in every api request include it as a config in the axios request
js-cookie
just search it up
Not Found: /create
[19/Nov/2020 09:31:31] "POST /create HTTP/1.1" 404 1767```I am using fetch to send a post request and it said that the page is not found
my main urls ```py
urlpatterns = [
path('', include('product.urls')),
path('create/', include('product.urls')),
path('capture/', include('product.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)``` and this is my product urls ```py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('create/', views.create, name='create'),
path('capture/', views.capture, name='capture'),
]
did you make a request to /create/ or /create
well your path is to create/
so you need to make the request to <your_domain>/create/ with the trailing /
Thanks @native tide
Also I think Django props up an error which explains this when it happens iirc. May be in the logs
def create(request):
if request.method =="POST":
print(request)
# Get json from request, gets loop through items and get cuantity, calculate total cost per item, and total cost of all items
# json_items = {}
# create_order = OrdersCreateRequest(request)
# response = client.execute(create_order)
# data = response.result.__dict__['_dict']
return JsonResponse(request)
# else:
# return JsonResponse({'details': "invalide request"})```
I am trying to print out request in cosole, in order to troubleshoot. its not doing so
@native tide
yhuI don't think you can print stuff like that into the console with Django
So how would I log this, save it to a text file?
Hmm print does print out to console
But whats its returning confuses me, <WSGIRequest: POST '/create/'>
its supposed to print a JSON but just returns this
I am using logger to mimic development setting, but print works also,
def create(request):
if request.method =="POST":
logger = logging.getLogger(__name__)
logger.warning(request.method)```
when I print out request.method is returns POST as it should but its not showing me the body
return fetch('/create/', {
method: 'post',
headers: {"X-CSRFToken": csrftoken},
body: JSON.stringify(cartJson)```
this is what I am sending in
NVM
def create(request):
if request.method =="POST":
logger = logging.getLogger(__name__)
logger.warning(request.body)```
this got me to print out the body
Do you have a seperate frontend?
but its so weird, when printing request itself it doesnt show the body, it only shows <WSGIRequest: POST '/create/'>
yeah I got it to work, just weird that when printing request itself it doesnt show any signs of it containing a body, but magically when I do request.body it grabs it.
@native tide I want to take in input from the user, and then they enter 5 into the integer field and I want it to become -5 in the database. What would be the best way to do this? Would I definite it with a certain field in models? Iβm using generic class based views
I made a DNS record to direct my domain to my website but it does not work. Do I need to make any changes to my nginx, gunicorn, or django files for this to work?
@torpid pecan If you ping the domain, does it work?
Ok, so that should mean that your DNS record worked
Can you show your nginx config? I think that is the issue
Not sure if this the the file you are talking about
The red is just the server address
Is server_name your domain?
It should be
And did you enable your config? Look in /etc/nginx/sites-enabled/ . What files are there?
I think I changed it and forgot to reenable it
If only the file default is then, then try sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/ then reload nginx
also reload nginx if you try changing any values
Yeah, I forgot to run that command π€¦ββοΈ . Thanks.
np, that worked?
Yeah that worked. Thanks
hi please wanna ask abt mysql.connector , what does cursor.execute return on success ??
Great. One thing to keep in mind if you have other issues is that the user that nginx is running as will need to be able to access that socket file. There might be some issues with that as it is in your home directory
Try saving the return value to a variable then
print(the_return_value_variable)
print(type(the_return_value_variable))
that's what I thought it like I can compare the statement to true ?
but I guess its not a boolean to return true
what I wanna do exactly is like
if thestatement executed succesfully :
smtng
else :
smntng
Hey, got simple problem with css not being aplied to head
head{
text-align: center;
text-transform: capitalize;
color: rgb(190,0,0);
}
<head>
{% block style %}
<link rel="stylesheet" href="{{ url_for('static', filename='styles/style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='styles/google-icons.css') }}">
{% endblock %}
<title>ZoomIt - {% block title %} Gif maker{% endblock %}</title>
<meta charset="UTF-8">
{% block header %}{% endblock %}
{% block head %}{% endblock %}
</head>
{% block header %} Hello, this is home page.{% endblock %}
header is not head
it was head, then I started to experiment to find solution
I wonder if raw text is ok, or it has to used with any tag
{% block header %} Hello, this is home page.{% endblock %}
Andrew π
save me
nvm got it
but why is renderin comments?
<html lang="en">
<!-- <link rel="stylesheet" href="static/style.css">-->
<div class="navbar" id="TopNavBar">
<a href="/home" class="active">Home</a>
<a href="{{ url_for('save')}}">New Zoom</a>
<!-- <a href="{{ url_for('results')}}">Results</a>-->
i disabled Results but it throws stil error
@plucky tapir in your view, get the integer from the field, multiply it by -1, save that to the db
I am building a webapp using node. js express. js and mongodb . There are users in app and I want to add a chat service option between users , how I can achive it? (edited
websockets
@native tide fields = ['tname', 'recipient', 'amount'*(-1), 'date']
Something like that?
From:
class TranCreateView(LoginRequiredMixin, CreateView):
model = transactions
success_url = '/users/tactionslist'
fields = ['tname', 'recipient', 'amount', 'date']
def form_valid(self, form):
form.instance.user_id = self.request.user
return super().form_valid(form)
I'm not familiar with class based views, but if the form is valid, just get the user input, make it negative, assign it to a variable and then pass that into the DB
When you run Django Admin. In the terminal, how do you have a βquestionβ come up to name the project? I have a βTASKβ setup to run that creates/sets up the project and super user, BUT, I want to have the option as I run a code, to name the project and any apps
Having issues because its not considered an integer ATM. Does anyone here have experience with CBV?
What exactly are uvicorn workers?
If I run app with
app.counter
on 2 workers, will I have 2 different counters or just one?
how do I decide over IaaS, BaaS, and PaaS services when it comes to hosting web applications?
what do I need to consider?
I'm using a Django based app btw if that counts as a factor
I am having trouble understanding the benefits and a typical use case of serializers in django, maybe someone could link me a helpful resource?
you do this for api I think
@limber laurel serializers validate the data incoming to your backend. useful for saving to a model
svg viewbox is not working too good
You almost have it working. What specifically are you having for an issue?
Create a new view like you have done. If the request method is a get then render the same template as the creation but populate the fields.
Then check for an post event.
So for example on update_note() you can pass the id in the URL for the note to load and allow them to edit.
how would I go about sending a list of dictionaries to the fronted of a django application? would I have to use transform it all as json and send it?
@swift heron DRF serializers
DRF or you can build it with JsonResponse. If it's only a couple views then DRF is probably overkill.
f = ContactForm(initial={'subject': 'Hi there!'})
Change the ContactForm to your own values.
I wish I had more time to explain how to do it right now but sadly I don't.
What is the proper way to do logging in Django?
Depends on the use case.
Just a simple web application to log error from exceptions
non-fatal errors @jade lark
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/filepath/site_logs.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers': ['file'],
'propagate': True,
'level': 'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}
make sure you only run this when debug is turned off. That or you can do a custom solution.
So what would the name of the logger be when i use logging.getLogger() in the case above? @jade lark
Ok thanks
web plugin
Hi guys. Has anyone here used the lib dependency injector (https://python-dependency-injector.ets-labs.org/) ?
@native tide I dont get you because you told me that
I needed to store the user's token inside the database along with the user model
instead I can just access the user by doing request.user right
or what should I be doing to access the authenticated user?
every user has an id, so what If I just return the id along with the token and then I can reference the user with the id?
OH WAIT NO
NOW I GOT IT
from rest_framework.authtoken.models import Token
try:
Token.objects.get(key="token").user
except Token.DoesNotExist:
pass```
So the token objects are stored in the database by default with user information.
All I have to do is something like this
but where will I store the token after login/register @native tide ? pls help me
hello
im makin a thing the BaseHTTPRequestHandler and im trying to see how i can get the current html content i know self.wfile.write adds text but i dont know how to get it
you want User.objects.get(auth_token__key=token), actually
but yes, this
okay
now I am stuck with axios post request pls help me
async handleSubmit(event) {
await axios.post(api_url+'register/', this.state.values.items())
.then(response =>{
const token = response.data.token;
localStorage.setItem('token', token);
//setJwt(token);
// bring up app container
})
.catch(error =>{
console.log(error)
this.setState({
errors: error.response,
values: error.data.input_data
})
// set the given field values return by api along with errors
});
}
this post request always gives an error code of 404
@vestal hound could u pls help
axios is bugged, I guess
Any solutions? I tried what they told me there but still it doesnt work
and if not any solutions somebody please recommend an alternative
ping me when help pls thanks
Hey guys
I'm looking to make a button to clone one record in admin page in django
For example when I open first object I can see save button and etc
I want to add another button to make a new object and clone all values from the last one
How can I do this?
what would be a good websockets tutorial. For the protocol itself and python
@tardy heron nothing beat the documents https://websockets.readthedocs.io/en/stable/index.html, if you want simple explaination https://www.youtube.com/watch?v=lv0oEnQY1pM&ab_channel=Vuka
How to set up a WebSockets Client and Server and Connect them!
Code: https://github.com/Vuka951/tutorial-code/tree/master/py-websockets
WebSocket API:
This socket programming tutorial will show you how to connect multiple clients to a server using python 3 sockets. It covers how to send messages from clients to server and from server to clients. I will also show you how to host your socket server locally or globally across the internet so anyone can connect. This uses the python 3 socket and t...
thanks
@twilit needle Store the token as a cookie then send it as a header in your axios request
Django will know the user from request.user from the token value in your Authorization header
whats the easiest way to extend django user model
AbstractBaseUser
or AbstractUser if you still want the user fields
like i want user model for resgisteration
only new field i wish to add is teacher/student a boolean value
so what should i be using?
@green snow this is how you would extend the user model in models.py:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
#your extra custom fields
for authentication you have to tell Django to use your custom user models for it in your settings.py:
AUTH_USER_MODEL = 'myapp.models.CustomUser'
oh ill try this
read the docs on abstractUser and you'll understand what to use
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
isteacher = models.BooleanField```
so i have pasted this to models.py of that app
did you created the migration and migrated it?
no
you should do that first
ok and where does this go
what "this"?
AUTH_USER_MODEL = 'myapp.models.CustomUser'
in your settings.py
ok
your django settings file
sure
when i was learning django , the tutoral which i refered had used the user model ()
withut any extendion
and he did it usiing postgres
@green snow first you add user models and settings , after that create migration - > migrate
so when he created the db he automatically got user table
because the tutorial you watched create a custom user model one, not extending django based user model
well ill try dis first
I've asked my question regarding reactjs class component inheritance here
https://stackoverflow.com/questions/64927837/reactjs-class-component-inheritance
can someone pls help me with it?
thanks!
pls ping me when you help here!
this isn't related to python at all :/
you should probably ask it in a React discord server instead
@gaunt marlin this channel has support for js
Not sure if that's what you want but, if you want to create a class that inherits from PostForm then write:
class ChildClass extends PostForm {}
yeah
The same way you defined it in PostForm, using super(props)
@twilit needle pass the same prop of the parent component to the child component
okay, then?
export default class RegistrationForm extends PostForm {
constructor(props) {
super(props);
}```
like this?
Can u explain what u want to do
So I have a base form class
I want a child class to inherit from it which has its own title, footer and fields
inherit what?
inherit some of the functions it has
like handling submissions and changes in field values
so pass the functions as a prop to the child?
with props
please If you can give me an example I can learn from it
I am quite new and learning react
search react props. it'll give u examples and explanation better than i can
import AnotherComponent from '...'
const MyComponent = () => {
return (
<AnotherComponent url="something" ... />
)
}```
no like props for classes?
there are props for classes
I can understand props for vars and functions
You just render another component like:
<Component propName = "something" />
Then in that component you can access it (let's say it's a class) like this:
{this.props.propName}
but the faster you move onto function-based components the better, because some libraries only work for function-based not class based components
Oh
But my problem is
* Functions to be overwritten by child classes */
form_body () {
super.custom_body();
}
form_footer () {
/* The footer is enclosed by the formFooter container */
super.custom_footer();
}
act_upon_response() {
super.act_upon_response();
}
act_upon_errors() {
super.act_upon_errors();
}
there are some functions like these
which need to be overwritten
so they can be only included inside classes right
overwritten in the sense the child component has its own form_body() function and the like
How about you make a new component, which is the form, and the parent will just handle the submit etc
So you want to pass those functions to the child component?
okay
yes
You can pass functions to the child component via props too, same example as before
act_upon_errors() {
super.act_upon_errors();
}
Get rid of the super, I have no clue what it's purpose is here
It would be best practice though to split up components into smaller chunks. Have the child which renders the form, and have the parent handle all of the submitting, with props between the two so the child can run the parent's functions
thats a good idea i guess ill do it
Also forms/inputs are fiddly in native React
I have a django Virtual form for backup
Especially if you want to perform validation
Ok
Once you practice a bit of React I highly recommend the react-hook-form library, it is very good for forms.
Which also helps because you won't have to send a request to your server everytime for validation, slowing thinks down
I am making a drop down box where you can select from a number of color schemes- dark, light, sepia. As soon as you select one, the frontend retrieves the color scheme from the database and then updates the website according to it. I was wondering how I go about implementing this?
I am using python-django, Vue, and Tailwind CSS.
@versed python You could definitely use React or Django templates (submit a form, then re-assign the class of whatever you want to change the color for)
Can you elaborate what component of React you would use? I am sure that'd exist in Vue too.
I am not familiar with react so idk if I am looking for a component or something else
Infact you could probably just do it with Django's templating. Idk about Vue but it's likely to be there too
I am neither using React nor Django templating
so... what are you using?
because a few lines up you said:
"I am using python-django, Vue, and Tailwind CSS."
Ok, but are you using Django?
So, does it do any rendering of the HTML?
Can I explain my use case to you? Maybe you can suggest a better solution altogether.
Sure. But I wouldn't be able to help with Vue, but I can give you an idea in respect to Django which may carry over
Would you prefer a DM?
Whatever you prefer
Okay. I will write it out. Thanks.
@native tide
so the FormHandler is a component
how can I use it to handle requests
its a react component right
is that the child, or the parent?
parent
class PostFormHandler extends React.Component {
constructor(props) {
super(props);
this.state = {
values:{this.props.fields},
errors: {},
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async handleChange(event) {
const value = event.target.value;
const name = event.target.name;
await this.setState(prevState => {
let values = Object.assign({}, prevState.values);
values[name] = value;
return {values};
});
console.log(this.state.values);
}
async handleSubmit(event) {
event.preventDefault()
await axios.post({this.props.post_url}, this.state.values)
.then({act_upon_response()})
.catch({act_upon_errors()});
});
}
}```
so you setup the Submit function in your parent (what happens when the form is submitted).
<ChildComponent handleSubmit={this.handleSubmit} />
You pass this to your child component as a prop.
Then in the child component you assign it to your form onSubmit event handler.
<form onSubmit={this.props.handleSubmit}
You'll have to change your parent's function to accept your form data, and be sure to include them in the parameters from your child component.
async handleSubmit(event) {
event.preventDefault()
await axios.post({this.props.post_url}, this.state.values)
.then({act_upon_response()})
.catch(error =>{
console.log(error.response);
this.setState({
errors: error.response.data.error,
values: error.response.data.input_data
});
});
}```
over here
how can the parent access the child's this.state.values
??
You add more parameters to that function to handle the fields and pass the parameters through the onSubmit event handler in your child
Hi I have a Django question?
In the child:
<form onSubmit={() => this.props.handleSubmit(this.state.name, this.state.email)}
In the parent
async handleSubmit(name, email) {
event.preventDefault()
await axios.post({this.props.post_url}, <your data in a dict>)
.then({act_upon_response()})
.catch(error =>{
console.log(error.response);
this.setState({
errors: error.response.data.error,
values: error.response.data.input_data
});
})}
}```
Something like that
Also you don't need event in the handleSubmit function because you're not using it.
event.preventDefault()
@native tide I have a list of images and sometimes one image can represent multiple model numbers but I only want to display one image and the list of model numbers.
heres my view
here's an example
here's my model
@naive oar whats the HTML template looking like
this.setState({
errors: error.response.data.error,
values: error.response.data.input_data
});```
So the error is set in the state here how do I return it?
to the form
{this.state.errors}
no it is there in the parent
how can I return it to child
lass PostFormHandler extends React.Component {
constructor(props) {
super(props);
this.state = {
values:{},
errors: {},
};```
this one
Take a guess
here's the template
Ok, so you think it should be this.props.state.errors in the child component. But you missed a step
Before a component can access a prop, what must happen for it to even be possible?
You have to actually pass the prop to the component first
Just as we talked about before
so I have a child element?
I tried to use regroup but it's not displaying the image?
<ChildComponent handleSubmit={this.handleSubmit} />
<ChildComponent errors={this.state.errors} />```
like this?
@naive oar So you have a model, and each entry has an image, model, size and finish?
@native tide yes that is correct
SMTPSenderRefused at /password-reset/
(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError h2sm1061663ejx.55 - gsmtp', 'webmaster@localhost')
You're gonna have to group an image to multiple models then, because in your HTML code it's just looping through every entry.
@twilit needle No, look at the code you sent. How many times will that render ChildComponent?
only once?
Nope, you're calling it twice
@native tide what would be the best approach to group an image to models?
<ChildComponent handleSubmit={this.handleSubmit} errors={this.state.errors}/>```
I meant like this
Yep
I have to call only once
ok I got it this is sooo interesting
thanks a lot for teaching me
errors = this.props.errors
Nice
this.state = {
values:{
email: '',
username: '',
password: '',
last_name: '',
first_name: ''
}
errors = this.props.errors
};
}```
likethis?
@naive oar Well, how do you know which images correspond to each model?
in the state>?
Rethink that
@native tide the image would be tied to the part_number
Yes it can be in the state, but you didn't specify it right
State is an object (a dictionary)
Anyway I got class now I will come back later and help
@naive oar Just a quick thought but it would have to be done manually I think. Maybe make a dictionary which includes {model numbers: image}
Can I solve with a group by?
You could probably do some model filtering too
There's something on that in the docs
I'm not sure of it though
help guys
linode banned 587 port
how should I send emails to reset the passwords now
everything else is paid
.-.
in drf
there are some fields i want to add programatically some i want to take from user
how to do that in serliazer
@hollow torrent can you explain further pls
<svg width="500" height="200">
<text text-anchor="middle", x="50%", y="50%", dy=".35em">
| Hello John.
</text>
</svg>
does css overwtires dimensions?
svg {
width: 500px;
height: 200px;
background-color: rgb(190, 190, 255);
fill: rgb(255,0,0);
font-size: 5em;
font-weight: 800;
}
got it
user !important for what you want.
inline styles take precedent
have another question now
class SomeMode(models.Model):
user = models.ForeignKey(User)
how to have both models created in the same call
huh
well yes, but actually no
what? inline dont take precedence?
no, css heigh is actually changing size
Can anyone help me with an issue related to python flask nginx?
guys, im trying to register users wth django rest framework, im using perform_create to save it and override a custom field but not sure how to properly hash the password sent in there
def perform_create(self, serializer):
ref_id = self.request.data.get('ref')
if ref_id is not None:
serializer.save(ref=ref_id)
else:
serializer.save()
send token to user, hash on his side and decrypt on yours probably
@young oyster can you show us your serializer
err so is this the correct channel to speak about nginx and websockets?
trying to build a chat app
and idk how to set up my config file
The field admin.LogEntry.user was declared with a lazy reference to 'home.customuser', but app 'home' doesn't provide model 'customuser'.
m getting dis error @gaunt marlin
Good morning everyone, does Python have an equivalent of Elixir's Phoenix Live View? For those who don't know Live View allows you to dynamically render changes to a client side ui just like React however it is actually happening on the server side and the client updates through data passed via websocket. Why would anyone want to do this you ask? Because for smaller SPAs you don't need to bring in all this complex web tooling associated with JavaScript ie: React/Redux, you handle all your state server side and only use one language
how can I use scss?
i impot this
<link rel="stylesheet" href="{{ url_for('static', filename='styles/animation.scss') }}">
Hey guys. I am trying to make a website connected to my bot. When you hit sign in on the site, it redirects you to the ouath2 link for the bot ("The bot would like to access your username and profile")
etc
And I want the website to display the username and profile after logged in
My bot is in discord.py, I just dont know how to connect the bot to the site in terms of code.
websocket
Hi Guys, trying to scrape a site for a list of US states and send it to a list. i have ```for url in page_soup.find_all('div', {"class": "state-list"}):
states_list.append(url.text.strip())
print(states_list)but the output is all in a single item that looks like['Zip Codes by State\n\nAlabama\nAlaska\nArizona\nArkansas\nCalifornia\nColorado....]```
how can i break that out to its own list
break it down
Django (channels):
I get a value error for No route found for path
Where exactly does django look those paths up ? Is it an issue with routing.py , url.py or consumers.py ?
hey guys i have a question i m doing site for graduation test for middle school from math....what i want to do it is generate math example but i have teoretical question there is like around 25 themes i was thinking i will do for 2 examples one html file and link him with themes site where are writed all themes but wount it be slow ....any idea or used method to do things like this'
this is the themes site btw
@vivid canopy pls give more information. Your english makes it hard to understand exactly what you're trying to do ...
Are you using flask or django ?
Can I introduce new method in class based view in django(not overriding)
sorry my eng is so bad ...D i m using flask....just want to know how is normal to do something with a lot of themes. i was mainly meaning that if i will have a lot of html's files for example first two themes will have one html file --> it means there will be 13+ html files just for themes and all of them will use a lot of def from main.py ....i m asking if its normal do it this way or is there some other option like have all themes in one html file and what should be right way to do it (think on that i want on one theme to generate one concrete type of math example , calculate an example and comment it ....this i want from one theme )...like will not it be slow that site? if u understand it ....and sry for eng
How can I call method in class based view inside the template django
What's up
!rule 6 @native tide
6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.
What is slug field in django
i forgot website which can create GIF from video, (not giphy).. please?
ezgif also not ...
@prisma jackal a string of characters, like an ID
Hey guys. Im doing my first web scraping project but vscode is throwing me some error that says unresolved import for the both the requests package and beautifulsoup package.
I have the latest version of python installed. I've created a virtual env using the pipenv shell method. I then went on to install:
pip install beautifulsoup4
pip install lxml
pip install requests
I run pip freeze and it shows that they are installed. And I can't really find anything on the internet.
If it helps, inside vscode when I try to select an interpreter in the bottom left corner or using Ctrl+Shift+P, the virtual enviro
I would really appreciate your assistance
Css question
How do I make text have a margin in desktop but full with on mobile?
I used margin right:50% but looks dumb on mobile
i would like to start with web development, i've heard that "django" is one of the best libraries, is that true?
anyone here?
Resolved
Hi
Is there a way I can lock a Flask route so that before it gets accessed again it needs to be finished?
I am using heroku which lets you choose how many processes you want to have running at the same time which then leads to a process being run twice at the same time and accessing wrong data because it hasn't had the chance to get updated
Hey guys. I am trying to make a website connected to my bot. When you hit sign in on the site, it redirects you to the ouath2 link for the bot ("The bot would like to access your username and profile")
etc
And I want the website to display the username and profile after logged in
My bot is in discord.py, I just dont know how to connect the bot to the site in terms of code.
where is the data stored?
I figured it
I am doing this:
lock.acquire()
if data['stock']:
if not product.in_stock:
webhook_url = 'xxxxx'
webhook = DiscordWebhooks(webhook_url)
webhook.set_content(title='An item has been restocked!', color=0x8f68c)
webhook.add_field(name='Product Title', value=data['title'], inline=True)
webhook.add_field(name='Product Price', value=data['price'], inline=True)
webhook.set_image(url=data['product-image'])
webhook.add_field(name='Product Link', value=product.shortened_url, inline=False)
webhook.send()
wu = 'XXXXX'
wh = DiscordWebhooks(wu)
wh.set_content(content=product.url)
wh.send()
product.title = data['title']
product.image = data['product-image']
product.price = data['price']
product.date = data['date']
product.in_stock = True
else:
product.in_stock = False
if data['title'] != '':
product.title = data['title']
if data['product-image'] != '':
product.image = data['product-image']
product.price = data['price']
product.date = data['date']
product.update()
lock.release()
@vestal hound
Basically a multiprocessing lock, I read it on stackoverflow. I basically won't to lock a route to only be done by one process at a time since I am using gunicorn and multiple processes at the same time
use with lock()
you'll get a deadlock if your code raises
I've got a weird issue where mobile devices don't seem to be interpreting vw units appropriately.
The units appear to work properly when using the full-size browser in "responsive mode" but not on either my iPad or my Android phone.
Has anyone run into this problem and found a solution?
But isn't a named lock shared across all processes?
okay I don't do multiple processes much but I'm p sure each process has its own copy of memory
and locks exist in individual copies
I could be w rong
try asking in #async-and-concurrency
hello friends, I would like to listen for webhooks and I would like the practice, would it be reasonable to write this somewhat from scratch? i.e make my own http server that would be listening for several different webhooks and do different things when different webhooks are sent?
When I see examples, they all use flask or django, but this seems like overkill/not the best way to make to do this.
class PostFormHandler extends React.Component {
constructor(props) {
super(props);
this.state = {
values:{},
errors: {},
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
act_upon_response = (response) => {}
async handleChange(event) {
const value = event.target.value;
const name = event.target.name;
await this.setState(prevState => {
let values = Object.assign({}, prevState.values);
values[name] = value;
return {values};
});
console.log(this.state.values);
}
async handleSubmit(event, values, post_url) {
event.preventDefault()
await axios.post({post_url}, values)
.then(this.act_upon_response)
.catch(error =>{
console.log(error.response);
this.setState({
errors: error.response.data.error,
values: error.response.data.input_data
});
});
}
render() {
return (<ChildComponent handleSubmit={this.handleSubmit} errors={this.state.errors}/>);
}
}
I get this error though when running npm run build for the react app
Line 47:18: 'ChildComponent' is not defined react/jsx-no-undef
Why? How Can I fix this?
like a rest api?
Thanks for replying!
no, I need an http server to listen for various webhooks.
specifically github webhooks
I am also open to other methods to do this. I am just having trouble finding ways to do CD, without adding tons of tools inbetween
my original idea was to use SimpleHTTPServer but it seems like a terrible idea to use in production
Github webhooks use json I think. Using a flask server is probably the easiest way.
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def webhook_route():
data = request.json()
print(data)
return {'state': 'request_received'}
app.run()
@acoustic oyster
i am not great with react, but is ChildComponent supposed to be built in to react?
ok, ty. I saw that same example, I am unfamiliar with flask, so I am not sure how much boilerplate would be needed for that to work. So idk if that is a great solution? edit: I literally am unsure, pretty new territory for me.
Yeah the code posted is it.
would I need to use gunicorn or similar to serve it on a port?
Are you going to integrate it with another program?
it is going to be a handler that calls bash scripts (most likely) based on webhook data set from various webhooks
Also: some reason youβre trying to roll your own cd? Why not just use GitHub actions since youβre already listening for GitHub webhooks?
If light usage you can easily host that for free on heroku. Itβll help you set up the wsgi server etc with little for you to do.
Then you can just do the following things:
1.
pip install gunicorn
- Create a a file called
Procfileexactly like this:
web: gunicorn app
pip freeze > requirements.txt
- Change the following:
app = Flask(__name__)
to
application = app = Flask(__name__)
- Create a github repo and push your project
- Create a free tier heroku project and push the repo
- Boom you got urself webhook receiver
@acoustic oyster
I am using github actions, however I have not found a solution I like nor one that I can find good info on. The one webhook that is commonly used has a big red banner on the docs saying "do not use" for the exact thing I want to use it for
@rustic pebble nailed it.
Haha
It is so stupidly easy to deploy something for free these days but most people don't know how and what to do
@acoustic oyster see what I sent above
tyty
ok, I was unsure if flask made the most sense here. But I think you have convinced me haha
Yea haha
Flask is perfectly suited for this. Itβs by far my default go to.
@warm igloo Are you good with flask?
what "editors" do you guys use? the only good thing ive seen so far is dreamweaver.
and i dont even know if thats that good
i dont even know where to start lol. id like to use django but i dont even have any html pages made or anything yet
the free host i use doesnt even support django it seems. i wanna be able to modify my website, ie add photos to a page and make 'posts', without having to always edit the html and access it via FTP
i came across joomla, any good?
i see
think im gonna stick with joomla at the moment, i dont need anything really complicated. its just a personal site
i am by no means a designer lmaoo
anyone there?
please please help me
I am using Reactjs
and its throwing this error
Objects are not valid as a React child (found: object with keys {type, message, ref}). If you meant to render a collection of children, use an array instead.```
const onSubmit = data => {
console.log(data);
axios.post('/api/register/', data)
.then(response =>{
const token = response.data.token;
localStorage.setItem('token', token);
//setJwt(token);
})
.catch(error =>{
const api_errors = error.response.data.error
console.log(error.response);
console.log(error.response.data.error);
console.log(Object.entries(error.response.data.error));
for (let field_property in api_errors) {
setError(field_property, {type:'manual', message: api_errors[field_property]});
}
});
}```
this is what am doing
so I am using react-hook-forms and for the error object that the api returns, I want to set errors in the form's fields
{data: {β¦}, status: 400, statusText: "Bad Request", headers: {β¦}, config: {β¦},Β β¦}config: {url: "/api/register/", method: "post", data: "{"email":"","username":"Magical","password":"abcd1234","last_name":"","first_name":""}", headers: {β¦}, transformRequest: Array(1),Β β¦}data: {error: {β¦}, input_data: {β¦}}headers: {allow: "POST, OPTIONS", content-length: "228", content-type: "application/json", date: "Sat, 21 Nov 2020 05:07:35 GMT", referrer-policy: "same-origin",Β β¦}request: XMLHttpRequestΒ {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: Ζ,Β β¦}status: 400statusText: "Bad Request"__proto__: Object
authenticationForms.jsx:20 ```
this is the error object returned by the api
data:
error:
email: ["This field is required."]
first_name: ["This field is required."]
last_name: ["This field is required."]```
please help me whydoes this error arise whatcan I do to stop it
Do I still need virtual environment if I have docker?
pls ping me when help, thanks!
@twilit needle you're rendering javascript object instead of a string/text that's why you are getting this error
If you intentionally rendering javascript object to the dom then use JSON.stringify(<your object here>)
no
I just want to set error with the data in the object
not render the object
@naive sparrow
Try console.log your data you would figure it out what's wrong
I did
I got the data
the problem is with the loop I guess
const api_errors = error.response.data.error
console.log(error.response);
console.log(error.response.data.error);
console.log(Object.entries(error.response.data.error));
for (let field_property in api_errors) {
console.log(field_property);
console.log(api_errors[field_property]);
setError(field_property, {type:'manual', message: api_errors[field_property]});
}
});```
So the error object is like this
Can you share screenshot of your code that would be helpful to figure out what's wrong
data:
error:
email: ["This field is required."]
first_name: ["This field is required."]
last_name: ["This field is required."]```
@naive sparrow
@twilit needle also send the screenshot of the code
Ok let me see
@twilit needle your api is returning 400 response
yeah
I wanted it to respond with 400
because the form data is invalid
it also returns errors
I guess you are setting a wrong error message somewhere
wdym
The property is misspelled or not exit somehow
On the error object
I can't tell you what's wrong b/c i never tried a hook-library for form validation i usually use joi for that
for (let field_property in api_errors) {
console.log(field_property);
console.log(api_errors[field_property]);
//setError(field_property, {type:'manual', message: api_errors[field_property]});
}```
I checed the for loop
its fine
the problem is with the setError function
;(
Ok Good luck
email
authenticationForms.jsx:24 ["This field is required."]
authenticationForms.jsx:23 last_name
authenticationForms.jsx:24 ["This field is required."]
authenticationForms.jsx:23 first_name
authenticationForms.jsx:24 ["This field is required."]```
the for loop printed this
it logs in console fine
but cant set error
I know the error
can u pls help me fix it?
setError(field_property, {type:'manual', message: api_errors[field_property]});```
So over here
field_property and api_errors[field_property] are objects
and not strings
so in the error object when its set, we aren't setting the string message value, but an object
how can I make it a string?
@naive sparrow
@native tide
In django project, if we have to create different apps, which have different purpose but the template should be same. where do you create the base.html, so that you can extend that template on every other apps?
hello
So I am using react-hook-form
I am contacting the api for error responses from it
how can I set the error obtained in my form?
const onSubmit = data => {
axios.post('/api/register/', data)
.then(response =>{
const token = response.data.token;
localStorage.setItem('token', token);
//setJwt(token);
})
.catch(error =>{
const api_errors = error.response.data.error
for (let field_property in api_errors) {
setError(field_property, "manual", api_errors[field_property][0]);
}
});```
this is what I am doing
when I console.log the field_property and api_errors[field_property][0]
the values are printed
but when I try to set an error with the same,
I get this error
```Objects are not valid as a React child (found: object with keys {0, 1, 2, 3, 4, 5, ref}). If you meant to render a collection of children, use an array instead.```
why?
I also try to set a sample error like this
```js
setError("username", "manual", "please choose a different username");```
I get the same error
```Objects are not valid as a React child (found: object with keys {0, 1, 2, 3, 4, 5, ref}). If you meant to render a collection of children, use an array instead.```
Can you please help me resolve this error?
https://mystb.in/AccordanceClipMelissa.javascript
this is my full code
can you please help me when you're free, thanks!
this is what I referred to also
https://react-hook-form.com/v5/api/#setError
help here will be appreciated, thanks!
https://github.com/react-hook-form/react-hook-form/discussions/3490
hey is anyone decent css
i have these links and i want to make them transition to a different colour when u hover over it and some sort of movement of the text. is this possible
can u please help me if so
sure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Mr. Canino's Class!</title>
</head>
<body>
<nav>
<div class="logo">
<h4>Mr. Canino's Class</h4>
</div>
<ul class="nav-links">
<li><a href="#">Home</a></li>
<li><a href="#">Web Development</a></li>
<li><a href="#">Python Programing</a></li>
<li><a href="#">Scratch Programing</a></li>
</ul>
</nav>
</body>
</html>```
that is the html
ok
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
nav{
display: flex;
justify-content: space-around;
align-items: center;
min-height: 8vh;
background-color: #2e2a27;
font-family: 'Poppins', sans-serif;
}
.logo {
color: rgb(226, 226, 226);
text-transform: uppercase;
letter-spacing: 5px;
font-size: 20px;
}
.nav-links {
display: flex;
justify-content: space-around;
width: 50%;
}
.nav-links li {
list-style: none;
}
.nav-links a {
color: rgb(226, 226, 226);
text-decoration: none;
letter-spacing: 2px;
font-weight: bold;
font-size: 14px;
}
.nav-links::hover {
cursor: pointer;
color: black;
}```
i was sending both π
and when you scroll down and it fades away
How to store the user uploaded pic in django
.nav-links a:hover{
color: /* color code u want */;
transition:0.25s; /* this eases transition */```
If suppose there are 2 users we have to store those in django.How would i do it?
just like social media thing
so make a new file
@rotund token
the other people ddossed here so am reposting.. pls ping me when help!
@twilit needle it isn't working
what isnt working
dw
assuming the color,
this is overwriting it css .nav-links::hover { cursor: pointer; color: black; }
how do i make it go away when i scoll down
.nav-links a:hover{
color: /* color code u want */ !important;
transition:0.25s !important; /* this eases transition */```
this prevents overwriting props
check out the animation.css lib
how do i use it and import it
and link it with onscroll event in css
the website has documentation
$ npm install animate.css --save```
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>```
here's an example
.my-element {
display: inline-block;
margin: 0 0.5rem;
animation: bounce; /* referring directly to the animation's @keyframe declaration */
animation-duration: 2s; /* don't forget to set a duration! */
}```
can u add it to my code and then teach me how to install it
do you have node.js?
no π¦
okay
go to your project root and open a cmd line there
type
yarn add animate.css```
to install the lib
sorry I gtg
so will be fast
then, go to the head section of your html
add this link there
ok im in the root now what
this
thats the setup.
After that you can use it like
yarn didnt work
wait
on windows?
yessir
better install it ur gonna need it in the future and now
so that should be it
I really should go now, if you have any doubts ask it here someone else will answer it :)
ok
try something like
console.log(button,innerText)```
in django?
so you need to send that to django?
yup
i sent evrythng except that boolean field
which is bydefault false
"isteacher" is the name in DB
https://github.com/react-hook-form/react-hook-form/issues/3491
any help pls? thanks
you can convert it to Boolean in your view or...
this is the form on codesandbox
change your form so you can use this https://docs.djangoproject.com/en/3.1/ref/forms/fields/#booleanfield
me?
no
well ive done it
okay
so your problem is not in Django but how you send the data to Django
are you using Django Widgets?
idk what that is
ok. Share your html
<button class="btn btn-outline-secondary" name="isteacher" value="True" type="button" >Teacher</button>
<button class="btn btn-outline-secondary" name="isstudent" value="False" type="button">Student</button>
</div>```
this is in a form
ok, hold on
Hey @green snow!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.
Feel free to ask in #community-meta if you think this is a mistake.
ok
Hey @green snow!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
man how do i send it
Hey @green snow!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
lol, just use https://paste.pythondiscord.com/
yep
Hey I need some help with deploying flask app on heroku
I pushed the code, added environment variables, upgraded the database and restarted the server
Still there is an error
@green snow what don't you replace those buttons to checkboxes?
I don't think buttons can hold states like you are trying to
if you don't want multichoice then you might want to use radiobutton instead
ya like the user can either be a teacher or a student not both
i thought wat i was using so far was radio button
those are regular buttons
though you won't get a True/False value from it
you will get "isteacher" or "isstudent", decide what to do with that info in Django, I guess?
Hi, I facing some problem on Django, when I run manage.py collectstatic, it bound from django.contrib.contenttypes import generic, ImportError cannot import name generic
@gusty hedge
so that "options" will return : whatever u will put in place of "Active"/"Radio"/"Radio" , correct?
I think you are missing the value attribute
<input type="radio" name="options" value="True" id="option1" checked> Teacher
</label>
<label class="btn btn-secondary">
<input type="radio" name="options" value="False" id="option2"> student
</label>```
@gusty hedge dis does?
Dafuq is this guys?
it worked @gusty hedge thx a lot , this is my ,firsttime doing a web project so i make such silly mistakes
glad to know, don't punish yourself, we all make mistakes everyday
Personally i think a drop down would make it look alot better
When i enter this it's doesn't do anything
ill try dat bro
guys hola
while fetching stuff from the database there are such strange things, does someone know how to fix it?
What was in your db?
just in the database is what is displayed in the picture.
@native tide settings
I can't see
in your settings.py
best way to get started on node.js
a/
?
can someone tell me the best way to get started in node.js?
Hey guys. I got a blog website up, and i want to improve it. Right now, blog post as text in the data base, but it's very limited. I rather use html or markdown.
My website is written in flask
Build a project.
how
i m a complete beginner to server side programming
i know my client side well
html and css
To start i would try the documentation, and searching github for examples.
ok
what is the easiest way to deploy a flask website?
also what is this gunicorn thing i keep hearing about when i search for deployment options?
i didnt install that. neither did i make a venv .so am i f*cked?
gunicorn is a wsgi server, basically, it converts your raw HTTP request to a readble python object(a dict)
and then this dict is passed into your flask/django app
a common setup is
nginx -> gunicorn -> flask/django
so flask uses gunicorn behind the scenes?
ye
ok
what
there should a bunch of tutorials online
u just said it uses it
my app somehow runs without that
you can also see the docs, they use a wsgi server
https://flask.palletsprojects.com/en/1.1.x/tutorial/deploy/#run-with-a-production-server
they use waitress instead of gunicorn tho
thanks . ill look into it when i get the time. ive been on for five hrs and i cant even type
thanks @marsh canyon
Anyone know about Flask Jinka Extension
*jinja
tried to creat jinja env with loopcontrol extension, still {% break %) not working π₯
anyone have experience running running a web server using express js, we are having issues with cookies not working, but in vscode live server they do
Trying to understand how Django verifies if a user is still logged in, I get how it logs in, sends the I'd and pass over through post and it's checked through backend, but how does it verify that a user it's still logged in without having to send the I'd and pass again...
Warning
If the SECRET_KEY is not kept secret and you are using the PickleSerializer, this can lead to arbitrary remote code execution.
An attacker in possession of the SECRET_KEY can not only generate falsified session data, which your site will trust, but also remotely execute arbitrary code, as the data is serialized using pickle.
If you use cookie-based sessions, pay extra care that your secret key is always kept completely secret, for any system which might be remotely accessible.
The session data is signed but not encrypted
When using the cookies backend the session data can be read by the client.
A MAC (Message Authentication Code) is used to protect the data against changes by the client, so that the session data will be invalidated when being tampered with. The same invalidation happens if the client storing the cookie (e.g. your userβs browser) canβt store all of the session cookie and drops data. Even though Django compresses the data, itβs still entirely possible to exceed the common limit of 4096 bytes per cookie.
No freshness guarantee
Note also that while the MAC can guarantee the authenticity of the data (that it was generated by your site, and not someone else), and the integrity of the data (that it is all there and correct), it cannot guarantee freshness i.e. that you are being sent back the last thing you sent to the client. This means that for some uses of session data, the cookie backend might open you up to replay attacks. Unlike other session backends which keep a server-side record of each session and invalidate it when a user logs out, cookie-based sessions are not invalidated when a user logs out. Thus if an attacker steals a userβs cookie, they can use that cookie to login as that user even if the user logs out. Cookies will only be detected as βstaleβ if they are older than your SESSION_COOKIE_AGE.
Performance
Finally, the size of a cookie can have an impact on the speed of your site.```
NVM found it, got the security warnings I wanted
I have added new pages to my Django site but they only appear on my Dev server(localHost) and not my actual server using nginx and gunicorn. Both server contain the same files. How do I get it to update?
Dev server:
Real server:
Not one detailed guide on file based sessions π
Hello everyone, I was wondering if I could get some help. I am passing a dictionary from a route to an html page. I want to unpack the dictionary in the html page and display that information via a <li> tag but can only either get all the information in two <li> or only the key's value depending on which I choose. Ex) test = {key1 : [chapter1, chapter2, chapter3, etc] ,
key2 : { chapter1_link, chapter2_link, chapter3_link]
can anybody explain how flask_sqlalchemy is different from regular sqlalchemy?
hi was wondering if someone could help me trouble shoot setting up gunicorn in docker. been trying to convert my local to a dev server i think i have a slight error in my docker command but not sure what
How would I add markdown to a django website?
I just want the markdown to work in the content
blog/models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
so a markdown field instead of text
{% for img in image %}
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{{ img['url'] }}" alt="img['caption']">
<div class="carousel-caption">
<h3>{{ img["caption"] }}</h3>
</div>
</div>
{% endfor %}
I'm getting a data set from a database, and it results in something like:
[{"url": "this", "caption": "This"},{"url": "this", "caption": "This"}]
However, this is the result:
Any help would be appericated
Please ping me, I need to go soon
Guys would it be better to use Javascript as frontend and backend for my web applications, or use Javascript as frontend and Python (Django) as backend? Please ping me and thanks in advance π
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% if is_paginated %}
How do I render the post.content in markdown
Currently it is a Django text field, and it won't highlight links, bold etc.
Here is all the code
ummmmm, idk anything about web development, so i can't help, sry
Ohh... That's fine, this is just a hobby project for me
@native tide The alt attr in the img should be wrapped with {{ }}. Check if the url works as intended
@surreal horizon Its your choice actually, both will do the same thing in the end.
@small crest you would need a package to render text to markdown
You can also do that in the frontend by using JavaScript marked library
Hello, IΒ try to custom validate a field using flask appbuilder
I got exactly this issue :Β https://stackoverflow.com/questions/58610943/is-there-a-way-to-add-custom-validations-on-user-input-data-while-using-flask-ap
the UI it says "invalid input" ..
Someone knows how to deal with from validation in Flask AppBuilder ?
{% if {{ tasks.count }} > 0 %}
<button><a href="{% url 'todo:delete_all' %}">Delele all</a></button>
{% else %}
<button style="display: hidden;"><a href="{% url 'todo:delete_all' %}">Delele all</a></button>
{% endif %}
hey i wanted to make a button appear when the items in my todo list are more than zero
and to disappear when it is zeo
but this doesn't seem to work
tasks is the list of all the objects i.e all the items in the list
I have a doubt
So I make a post request to the api and it responds with a token for authentication
where and how can I store this token?
And how can I use the token to access token info?
yo
How can I grab the pk variable from url and make it available to view, I am using django
you can store it in db
I want it to be available inside the class based view
heyy plss can someone help me with this one
try tasks|length instead @winter spindle
Trying to figure out the best practices for Django.
So do I really need to create a separate app just for user registration and login?
Or should I store this all under an app called mainApp?
id reccomend seperate app
also it will be easier if u want to reuse it
but im no expert
I just find it a bit annoying creating so many apps.
i think it depends on what u r making
I'll create a new app, thanks @green snow
yea
im unable to use list index in an html page
(im doing a django project)
the thing is the list is being displayed {{listname}} but {{listname[1]}} isnt working
error: Could not parse the remainder: '[1]' from 'nests[1]'
okay so the thing is u cant do this normally like u do in python
{{ listname.index_no}}
{% endwith %}```
add this to your code it will work
it is working now ,thanks
hey guys
I just started learning Flask today and i'm stuck
i'm getting this error
help
Linode best site to host my web app?
$5 linode vps enough ?
Starting out? Less then 500 users per month?
hry guys how can i put a background wall paper to my website
@haughty turtle Thatβs plenty. If you really want go with a t2.micro from AWS.
Which should be free.
You would probably want to set the background of your body to the image you want.
Let me see the css plz
body {
background-image: src = "htmljpg.jpg") no-repeat fixed;
}
body {
background-image: url= "htmljpg.jpg") no-repeat center center fixed;
}
this one too
!code
body {
background-image: src = "htmljpg.jpg") no-repeat center center fixed;
}
body {
background-image: url= "htmljpg.jpg") no-repeat center center fixed;
}
yes this is the correct way
You have the right name for your image?
yeah
Itβs in the same directory as your css file?
yeah
Can I see your directory tree and paste bin your entire css file for me?
how can i do that
Uhhh, go to the root directory of your project and just take a screenshot I guess
How many lines of code is your css file? If itβs small just put it in a code block
Are you not using a css file? You are using a style tag?
Where are you writing the code you posted earlier?
Vs code
I mean which file
Ok the css code, is it wrapped inside of a style tag?
yeah
Ok, can you post everything inside the style tag?
<!DOCTYPE html>
<html>
<style>
<body>
body {
background-image: url(βhtmljpg.jpgβ);
}
</style>
<h1> Welcome to web </h1>
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url(βhtmljpg.jpgβ);
}
</style>
</head>
<body>
<h1> Welcome to web </h1>
</body>
</html>
i try this?
Try that
nope
there is something wrong with the url i think
how can i make sure the url is working
What is the name of the file that contains that?
Is the h1 tag showing?
Hmmm, One second
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("htmljpg.jpg");
}
</style>
</head>
<body>
<h1> Welcome to web </h1>
</body>
</html>
That should work assuming your jpg is in the same directory as the file with the html code
@haughty turtle don't create new apps for individual things, like login/signup, make apps more generally
So just create a mainApp for non complicated functions? Such as linking to my index and login sign up etc?
@native tide
Yeah so say you had a dashboard, keep everything that's linked with that dashboard inside that app. Maybe you have a landing page with the login/signup form that appears, keep that linked inside the landing page app, etc
how can i make my background not repeating
Do you guys know any good learning sites for Django?
The Django documentation has a good tutorial
Just add no-repeat in background in your CSS file @tawdry oasis
background: url() no-repeat;
background: url("htmljpg.jpg") no-repeat;
Use that and remove the background-image you have
@tawdry oasis
Really I suggest you follow some CSS videos in detail so that you can search w3 for all CSS attributes @tawdry oasis
@devout coral got a tc2 set up for testing purposes, what should I use to serve my files Nginx or Apache
I see people say to use both one for Static files and one to serve the python files is this true?
Iβve used Apache in the past but itβs also old. Iβm currently transitioning to using Traefik.
Granted thatβs because I have everything in Docker containers now. If you have a simple Django set up Apache2 will probably be the easiest.
got it thanks π
@surreal horizon ummm JavaScript and Django are not the same o.o
i see
Your going to fail miserably with JavaScript as a backend and you should not be doing so. Have people really used JavaScript for backend...
You use JavaScript to send sensitive information over to your backend as JavaScript isn't build with security in mind to serve as a backend.
Could be Node.js?
It seems to be a framework
Heyy i need some help with Instagram API.
Anyone here who can help?
Hello, my django sends wrong Content-Type content type headers for my js files. How could i change that?
Content-Type is text/plain but should be text/javascript
Error from firefox:
And chrome refuses to load files at all
@serene prawn
Take a look at that link
Also it's a warning not an error, is it preventing you from achieving something?
Hey, I'm learning FastAPI, anyone has an idea for a website? I have already made a blog
I'm a student so I have a lot of free time right now because of the pandemic
my web breaks when I send files larger than 10MB ~
is flask restricted somehow ?
@haughty turtle @surreal horizon You can use JS for backends - and it's very popular w/ Express. Idk which one is more popular: Django or Express, but they have their own uses.
And a lot of people start with JS as their first language, learning something like React pairs well with JS backends like Express. It's harder when you're trying to juggle languages.
Django is still more popular atm
though its pretty tight
Express is easy for people to get into but god damn does it doesnt protect new users anywhere near as much as Python frameworks
That's surprising, which would you say is the most popular backend framework then?
Out of all them
Laravel π³
backend?
flask and django are frameworks for sure
django has some backendish stuff but ...
what?
FastAPI is better though
:d
No it depends on what you do
But it can be scaled up to whatever you want it to be
got simple question, how can I verify if upload picture is ok, before uploading and checking in next function?
It depends on what you mean by "ok"
check size and extension
@app.route("/upload", methods=["GET"])
def upload():
"Image is beeing uploaded here"
@app.route("/process_image", methods=["GET", "POST"])
def process_image():
"I check image in next url"
I upload image in first page, then user gets redirected by form action
<div class="container">
<form action='{{ url_for("process_image") }}' method="POST" enctype="multipart/form-data">
<div class="form-group">
<!-- <div class="custom-file">-->
<input type="file" class="custom-file-input" name="upImage" id="upImage">
<!-- <label class="custom-file-label" for="image">txt2.</label>-->
<!-- </div>-->
</div>
<button type="submit" class="btn btn-primary">Confirm</button>
</form>
@native tide
How can I get the State of a checkbox in html using flask? Ping me with responses
(venv) PS C:\Users\chris\Documents\Programming\Github\React-App\DRF-Django> coverage run --omit='*/venv/*' manage.py test
Fatal error in launcher: Unable to create process using '"c:\users\chris\documents\programming\github\react-app\venv\scripts\python.exe" "C:\Users\chris\Documents\Programming\Github\React-App\DRF-Django\venv\Scripts\coverage.exe" run --omit=*/venv/* manage.py test': The system cannot find the file specified.
can anyone help me re-configure the file path for coverage?
currently can't view any .exe views to change the file path.
no idea yet, but I will find out and do this π
Sorry for answering SO late but i'm serving these files through django.contrib.staticfiles, guess i can use something like apache/nginx for this?