#web-development
2 messages · Page 187 of 1
I have Django-cors-headers and allowed hosts
CSRF Cookies? Decorators?
if none then sorry I dont know what would the solution be.
I am using a class based view
okay, did u include the JS CSRF Cookie function?
Thanks for trying to help 
I am using a python script to test the api
np, I hope u find a solution asap good luck!
🙂
what's the problem?
any luck?
need a way to pass into the community id into the template so im gonna pass it as context
Great
it doesjnt work
You added the path to the view?
Share some code and we can look over it.
the form and the view
Show the whole form,
the view, and the full url/path
See you're cutting stuff off with screenshots. It's better to paste actual code.
But post your view as well, where you handle the post request.
No worries, we can look at it later.
thats the view
Did you try printing in it to see if you're even calling the function?
its not being called and im not sure why and yeayh
Where did you put the print statement?
on the top of the method
Show me where, I don't know what on top means.
put one as the first line in the class
and then submit the form, do you get anything printing in the terminal?
and I assume you're logged in?
what happens if you remove the action= from the form all together and then submit?
ive used the createview in other instances and the action wasnt even needed
same thing happens
Yea it's not necessary.
But now that you've actually hard-coded it, and it still doesn't get into the function, means you have something obviously not making that connection, and my guess is something isn't written correctly. Is that url called 'create-question' at the end?
yeah
Can you explain what a meta class do? 
I am rendering http content on a https page, therefore getting the mixed-content error. I have searched on web what solutions there are for this issue and for now I have chosen to create a proxy server that uses https and will forward the request. If you know a better way except not using http let me know. I am not using https because I cannot change that system.
I am rendering images on my website this way.
<img src="http://image.com/image/12" />
I am wondering if it is possible to use the proxy inside src attribute. Something like
<img src="https://someproxy.com/http://image.com/image/12" />
I am using django and I could also try to make the request in python and send the image to the dom. But since I have already configured the proxy I want to try using it inside src attribute.
it's misspelled again, are you making the changes?
It might have something to do with the 'community/<int:pk>/create-question/ and 'community/<int:pk> urls
Do they all need / at the end?
But then you wouldn't see the page either... 🤔
yeah i added it when the other guy told me to
but not to all of them
i have no idea why the view just doesnt want to work
Hi Guys
I want to do something like that
using django rest framework
can anyone help me?
I fixed it, the reason why it wasnt being called is because the form data wasnt validated lmao
What did you add?
That is just a json object. You don't "do" that. It's just an object. What is it you want to do?
You can, for example, return a json object via DRF but that's very general and you would need to share what you're trying to accomplish.
hello why i get this error: ImportError: cannot import name 'Oauth' from 'oauth' i just copied swastik
Just had to get rid of the fields I wasn’t displaying on my template on the model form
Everytime I was submitting they were being left out so it wasn’t being validated
hey guys
im writing an API i should use which name formatting??
camel case right??
I think that depends. In graphene you query with camel but backend is still lowercase with _'s
Question Web Dev Friends,
Are you able to use any/most bootstrap templates with Django?
Sorry for the late response
#web-development message
My Django web app uses Bootstrap 5.
Hi all, I'm struggling with finding analytics for my site...
Was going to decide Google Analytics, but that's a privacy compromise
was told about https://ackee.electerious.com/ and other self-hosting solutions
but I've never self-hosted something like that before and I'm not sure what I'll do if my site ends up blowing up
(using DigitalOcean
how to use ajax in django
Quick stupid question I didn't find an answer to, but is it possible to link an image in css / scss file that is online? Or do I have to have them localy? nvm I just had a typo. fml
@eternal blade what are your DEFAULT_AUTHENTICATION_CLASSES in settings.py?
My guess is you have some middleware requiring a token.
knox.auth.TokenAuthentication
So that means that all your views have the knox.auth.TokenAuthentication middleware which requires a token, I'd find a way to take that off your LoginAPI view
Thanks, I'll try to do that
Are HTTP requests between docker containers SSL secured?
Does anybody have any good resources on modern web design? (Not web development, but actually designing beautiful websites)
I doubt it
with 90% there is no SSL in between
unless you set it on your own
yeah, thats a complicated question. Design and development are not really the same things. I know that when I have design questions, I take them here https://discord.gg/srhkZ52w
Perfect - Thanks a lot! I'll check it out 🙂
you have in general several options
setting reverse proxy with attached even unverified certificates I think
or you could use something like this, I was advised to try it at least
https://www.stunnel.org/
or you could just enable firewall ;b
I went so far with firewall option
Ah, thanks, not looking to do it just wondering.
beware, UFW firewall is not working for docker 😉 due to some conflict in records
but iptables works
hey guys, how can I make it so that when I close the sidebar, the elements on the white background must occupy the area of sidebar and when I close it, do the opposite...
Hey can we ask HTML and JS queries here?
no they need to run in a browser
i think you can get bots to render html. not sure about js
that was a joke btw
Hello, is there a way to unregister Token from the admin dashboard the Token im using is from rest_framework.authtoken.models import Token.
When I try to register it in the admin it displays two Token tables
yes
thanks I'll!
If you're not using models for your rest API is it possible to do a put request for your dictionary? I'm new to this, I'm trying to do it but it doesn't work.
Do you know any way I can do this? I tried using knox.views.LoginView but I still got a status of 401.
guys anyone?
If I have a function in django views.py, how can I call that function in my react frontend app, when for example pressing a button, which is displayed on the website?
@glacial yoke you're looking at making an API endpoint and making http requests to it from your frontend.
by api endpoint, do you mean an APIview?
and also, how could I make an http request to one?
@eternal blade I'm on my phone, but what I can tell you is that authentication class is default so it affects all views.
@glacial yoke You can use JS. A request lib like axios to send http requests.
Yeah, I've tried using axios, but how exactly should I send the request?
So should I remove knox.auth.TokenAuthentication from the settings.py and then make all classes (except the LoginAPI) inherit from knox.auth.TokenAuthentication
I've tried something like this:
function login(){
const response = axios.get("/login")
}
But then how do I call it?
@eternal blade yes, maybe it has some docs on how to set the authentication class on a view.
Thanks 
@eternal blade https://james1345.github.io/django-rest-knox/auth/
Here is an example for how to set the authentication / permission classes on a view
Thanks
@glacial yoke axios.get returns a promise. To access the response you can await it or have a .then() block
and then, would I just stick the function into a button, and it should work, right?
and also, can you please show me an example of a proper api view, because I'm not too sure how to set it up
hello, I have a question regarding FLASK.
My FLASK application sometimes has to process a folder of files, and I would like an update to come back as they're finished.
But right now, it's like:
@app.route('/processfiles'): def processfile(): for x in dirname: process_file(x) return "status text"
and that status text doesn't get returned until everything is finished
is there a term I can google to get more information ?
What kind of update?
so let's say i'm processing 100 files ... ideally i would like output after each file is done. filename and success/failure code
Just in the terminal?
no, through the browser using FLASK
You would need to probably handle the for loop on the front end in that case, and print something for each thing it iterates over.
return the context/array, and iterate on the front end, printing for each item.
the problem is that FLASK only takes 1 return, and that return gets put on the page
i could be wrong because i'm new at this 🤔
Hmm, Is see what you mean... I'll have to think about it.
Maybe handle it like a % done indicator?
I can do it in the terminal no problem
it's getting it to do it in the browser i'm having trouble with 😅
Yea, so I would probably look into how to setup a % status complete indicator on the front-end.
And just print "done" instead of changing the %.
great, thanks! I'll take a look
How long does it take to process the folder?
it depends on the time of the month but between 10-20 mins
there are a bunch of excel sheets to lift info off of and screenshots to be made
it's for a local application, so requirements aren't high
but people get suspicious when the page just says "loading" for that long 🤣
This looks about what you need.
thanks! except I probably can't do celery or redis 😅 but i'll take a look. maybe I just need the idea
it's cuz we're on windows because of Excel
Hello..I want to learn django..but since moat of the tutorials are on django 2 ..what should i do
there isn't much difference between django 2 and 3, and also, django 2.2 is still going to be well in support until the end of 2022
Thanks @glacial yoke ...
There are tons of Django 3 tutorials - and they are essentially the same. There are changes for D3 - mainly async if you want to use that - but the major changes aren't necessary for core features.
Thanks @dense slate .
for django is there a way to pair contexts? im iterating a qs with users and im trying to get a count of related objects using a filter
u mean u want to count the objects that is returned after filtering it?
I want to count all of the objects set for that user
but i want to filter that objects set
I'm trying to decide on Django REST framework or FastAPI for my backend for a new project I want to work on. Anyone have any suggestions or experience with either of those?
try
Model.objects.filter(..).count()
is there a way of getting a count through the user though?
because im iterating through a user qs
for user in users?
yeah i have a user qs, and im displaying a list of users, i want to show a count for all of the objects set for that specific user with a few filters on too
for user in users:
objects = user.objects.all()
return objects.count()
something like this? btw I am just trying to help you with how I understand what you said, sorry if I did not understand you well
Don’t worry I appreciate it :)), so I’m iterating the user query set on the template not on the view
if its correct, just replace it with the blocks
hello I have a django question
{{ }} & {% %}
def forms(request):
inital_dict={
"text": "Some initial data",
"integer": 123,
}
form = TestForm(request.POST or None,initial=inital_dict)
data = "None"
text= "None"
if form.is_valid():
data = form.cleaned_data
text= form.cleaned_data.get("text")
return render(request,'first_app/forms.html', {'form': form,'data': data, 'text': text})
is it okay to remove "or None" inside TestForm?
Yeah like that I’m trying to figure out how I can get a count of all related objects through the template or if I can pass it as another object but still have it related to that specific user
in the view
objects = None
for user in users:
objects = user.objects.all()
number = objects.count()
return render(request,'template.html',{'number':number})
in the template
<h1>{{ number }}</h1>
NOTE: I didnt try it
im using a class based view, and im passing in 'users = user.objects.all()' as context right, now i want all of the related objects with additional filters on it, for eg, 'users.modela_set.filter(fk = 2)' and pass that in and make it match the correct user
do you get what im trying to do?
but who is the correct user? are u trying to get him with id or?
im iterating through a list of users and they all have objects related to them
so they are linked through an fk
oh u mean u want the user who matches the fk of other models?
kinda and i need to display the list of each user and data that relates to them
is it one fk ? or multiple
I've got a login system using django social auth app, and it has it's own integrated sessions and etc.
I'm trying to make a function which would find out if the user is logged in or not, can someone help me with that?
u arent using tokens?
nope
I don't really need to, because if a user is logged in, they'll just have a permanent session
until they log out of course
def my_func(request):
if request.user.is_authenticated():
print ("Logged in")
or
from django.contrib.auth.decorators import login_required
@login_required
....
I Hope thats what u were looking for
Thank you very much
I’ve been looking for this for the past 2 or so hours
np
Btw, how could I request this function from react front end, for example if I wanted to render the log in button if the user isn’t login, but if he is, I would render the logout button
Would I have to create an apiview?
You will need an api url.
Ive never used Sessions with an api so im not sure if it works correctly, u will need Token based authentication.
Then if the user has a Token with him that means he is logged in, else he is not.
So I would have to setup a jwt token system?
u have more than one option, there is also basic token & I think that will be easier for u as a first time
yeah, but jwt is probably easier to manage, especially using DRF
hii
this question is a bit more about electron but I think I can ask it here?
I wanted to call a function in a .py file using electron, without having to use stdout, stdin, etc
is that possible?
I only found stuff about python-shell so far, which doesnt fit my requirements...
okay if that is what u are comfortable with. I think jwt tokens generates a new token for every log in, so u will need to take the token from the login response in react
what does the function return?
yeah, but if they log in, their session should be permanent as long as they don't log out, right?
I think u can also set a timer for the token
ok, I need it to be permanent, so it's fine
Permanent tokens aren't safe so make sure you're not doing that in a sensitive app.
an array with dictionaries in it
I just dont want to use stdout and stdin
specificly
I dont want to change the function
okay how do u want to call the function? u want to see the array or access it?
acess it
my idea is to use the data that the python function returns to me to build the page
well
i mean
whatever
if it returns only text of the result i can use it as json, right?
i just havent found how to get anything from it
u can convert it to a JSON object instead of making it an array
but idk how electron works tbh, is there a way to import files?
wanted to ask since u mentioned that, are basic tokens safe enough? they are stored in the db and are permanent unless logged out
Tokens are generally stored in cookies. How are you using them in the DB?
Hello guys if my frontend is React how would I store tokens generated from backend? I can’t even see HTTP headers
localStorage and document.cookie doesn’t seem to be very secure
rest_framework.authtoken
And about WWW-Authenticate response header, how would I do that in frontend React?
Try axios
No its a react library
Then backend respond with WWW-Authenticate
U will get response data and take token from it
I can get token but how do I store it
In user’s browser
I cannot make httpOnly cookies
idk that sorry
Nor use Authentication
Unless I use a template rendering tool which I am not planning to
Since I’m using React-router-dom
Generally I mean. Tokens are typically created on the front-end with a time limit with refresh token saved in the DB.
If you just have a permanent token, why not just use sessions with django auth?
Why can't you?
That's the way you should be storing them, as httpOnly cookies.
Nevermind that
I will use a separate file
That once runned
Will get a specific module and function
Using the string values passed by this system
That is a good enough workaround my issue I guess
I can’t access httpOnly cookies in React can I?
you can't access httpOnly cookies with JS as they do not appear in document.cookie. You can set these cookies from your response - include a Set-Cookie header in the response to set a cookie and you can make it httpOnly, read the docs on that.
Like login session
How do I remember a user
I’m going to host my website on netlify so my backend would just act as a database and REST API
I know how to make httpOnly cookies I just need to access the user token in frontend while also making it as secure as possible
Yea you can.
Oh access them.
Do U mind linking the docs for that?
I need a secure way to store login sessions
I set the access token in state, and then use an httpOnly refresh token to refresh it upon refresh or opening a new window.
Hmm
After each refreshToken is used, you set it to invalid in the DB and assign a new one.
I don’t really understand can u map it?
When a user logs in, return the access token to React and set it in state.
Along with sending an httpOnly refresh token into a cookie.
Use the access token until it expires or state is cleared, such as on a refresh.
When the access token is invalid in that case, use the refreshToken to silently grab a new token and reset the state.
Yes
and repeat as necessary.
That help?
How do I know refresh Token in React then
damn, why can't you just save it as a non-http cookie? 😂
If the state is reset
You grab it on the backend.
sounds complicated
How do I verify it’s the user’s browser?
Wait no, sorry. I use django-jwt to run a functionin React to run a refresh command on the backend. That function grabs the token from the browser.
I see
The refreshtoken is saved in the DB
so it validates it against that
when it uses it, it invalidates it and sets a new one in the DB
How does Django-jwt run a function in React
that last part to invalidate is just extra security.
I don't know, the library handles that. 😄
kk
I’ll check it out
token-security-conversation
^^^ ignore that I just need that to control-search later
It took me like two weeks to wrap my head around it and get it working, but now that I understand it, it's pretty easy to setup.
hey is there a good way to get a count of all related prefetched objects?
I wanna display it on the template
qcount = Query.objects.count()
return render("page", {"qcount": qcount})
Hey guys. I wanted to make a Django website where the window is divided into two divs of equal size. The left side has links and the right side has an image. When I hover over any link the image should change on the right as per the link without the page reloading. The images and the links would be dynamically added from the backend using models. Is that possible?
Then use qcount in the template.
That sounds like fetching all the objects up front and then affecting what the window displays with css.
Yeah. Can it be done using models?
What do you mean done with models?
Basically if I have to add new content, I could do so from the admin panel.
By new content I mean link and image
Im displaying a list of users within a group, and i wanna display the count of objects related to that user and group
Yea, so did I answer your question above?
Yea that's fine... you need to query all the objects in the table and return them to your template. When you add a new item in the DB via the admin panel, that will automatically be fetched in future queries.
Thank you very much, I shall do that!
problem is it displays the count of all objects instead of objects related to that group
So you need to query the right thing first, and just add .count() on the end
So filter the query to get the stuff you need.
query.objects.filter(group="correct_group").count()
aight, how could i then match the count to the correct user?
because i want to display a list of users and a count next to each user
What exactly are you counting?
Elaborate on this.
Anyone good in CSS know why this is happening?
When I change overflow-y to scroll it just does that
The middle row is the exact size of the container div if that helps
this is the container div:
.rightSlide {
overflow-y: scroll;
position: absolute;
display: flex;
flex-direction: column;
height: 100vh;
width: 6vw;
margin-left: 85vw;
margin-right: 2.5vw;
justify-content: flex-start;
align-items: center;
-ms-overflow-style: none;
scrollbar-width: none;
}
there is a m2m relationship between my users model and custom group model, I have a page listing all of the users within a certain custom group, I also have objects such as 'questions' that are linked to the custom groups and users, how can i get a count off all of the 'questions' that are linked to the user and group
this is react-calendar
.rightSlide .react-calendar {
position: absolute;
margin-top: 25vh;
background-color: gray;
color: white;
border-radius: 10px;
padding: 10px;
width: 20vw;
height: auto;
}
I tried z-index but that’s not the issue
this is refering to my old so called problem
so I've set up a social authentication in my django app, and whenever someone logs in a jwt token is made to manage their session
firstly, how can I refresh this token, if it expires when the user is active
and secondly how can I check on my react frontend if the user is signed in or not, would I just check if the jwt token equals to none, but how exactly would i be able to refer to this session, because I can't really refer to a user, because he is "anonymous", because he is not logged in yet
This might have your answer.
I've tried that, even though it gets a count for a specific user, it doesnt take into account if it is linked to the same group or not so it gets a count for every single 'question' for that user
aight ill have a lookj
it gets the count of every object for that user instead of every object for that user and group :((
I just can't quite picture what you want to show.
You have a list of users.
You want to count the questions that belong to both the user and the current group and show it?
correct
So like... Questions.objects.filter("user"=user).filter("group"=group).count()?
I'd have to see your models i think.
well to display the users i got community.users.all()
oh yea ok, show your models
what part would you like to see?
You're probably going to be best off doing something like adding a method to your model class where you pass the user and group ids into the method and then in that method query the questions where user and group equal those ids. Then in the template, make a for loop that runs that method for each user in the group.
That make sense?
Give me a moment and I can.
so under your model class, you'll have a method like
def count_stuff(self, user, group):
qcount = Questions.objects.filter(user=user).filter(group=group)
return qcount
In the template, you'll make a for loop, and inside of it you'll do {{question.count_stuff}} for each user
(question is the model class name that you returned to the page earlier)
what model would this go under?
The user
so in the for loop you'll do {{user.count_stuff}}.
Because you originally queried users right? to display?
On the page, are you only querying the user or the user and group?
im querying the users through the group
Show me your queries and how you display them in the page. When I just have bits and pieces I can't give you solid examples.
community = Community.objects.get(id = self.kwargs['pk'])
users = community.users.all()
context['users'] = users
return context
hopes this helps
thats how im querying the users
And community is the group?
yeah
So users is just the users in a particular community already?
no, users and community are m2m
but you're getting community.users, so users is the set of users in that community, yes?
oh yeah mb read that wrong
so in the User model, write a function/method that states:
def count_questions(self, community):
count = Question.objects.filter(author=self).filter(community=community)
return count
Right? That gets all the questions for those two variables.
in the template:
{% for u in users %}
{{u.name}}: {{u.count_questions}}
{% endfor %}
that will list the question count for each of those users in that community
so you just have to modify that however you need it
so would author = self, and how would the community get passed into the method?
sorry if im being slow
Ah right, so that might have to be pulled from the URL. Maybe put request in the method like the above edit and pull the communty id from your URL.
Trying to think of another way but that's the first way that comes to mind.
im able to pass in the request?
Yea you can't pass that. Hmm I'm trying to think how to get that variable in there.
You might need to create a custom templatetag
yeah i heard about that but i try to avoid it
But I feel like there's another way. I just can't think of it now. I'll look at it again later.
thanks for your time :))
I think using sets will get you there but I don't have a lot of experience with that.
Was following programming with mosh's beginner django tutorial and keep getting this error when trying loading it. Any ideas?
I'm assuming its the "running scripts is disabled on this system"
Figured it out, for someone reason vscode default terminal to powershell 😴
Hello, I am building an API for my website and when the user is being rate limited I don't want to display an error but rather do..nothing. Would anyone have a good way of doing so? I am using Quart to do it.
I'm having a difficult time with my django, can someone help me? I'm getting this error on my front-end
here is my form tags
don't know what went wrong 😩
hey y'all i'm making a web app in flask and i want to have my log in involve a redirect but i want the redirect to have all the html form info to be invisible in the url of the page the user gets redirected to, i.e. like using POST, but when i do the redirect i end up getting the info in the url. for example, if the user's username is "zeljko", the url will be something like "localhost:5000/dashboard/zeljko". i don't want the "zeljko" to be there, meaning something like "localhost:5000/dashboard" while still having access to the form data. is there any way around this? here's the code with descriptions if it helps:
## /join pulls directly from the method="post" form on login.html, where the user logs in
@app.route("/join", methods=["POST", "GET"])
def join():
username = request.form.get("username")
## basic log in logic, checks if passwords match and if user is verified, etc.
## if all matches, then:
return redirect(url_for("dashboard", username=username))
## if not, then:
message = "Looks like the username and password don't match."
return render_template("login.html", message=message)
## /join redirects to /dashboard when login is successful
@app.route("/dashboard/<username>", methods=["POST"])
def dashboard():
username = request.form.get("username")
return render_template("dashboard.html", message=username)
nvm i got it lol
I have a flask app, running on AWS Instance, i want to make some kind of websocket to sync a slider, i've tried flask_websocket but it doesn't seem to work.
Question is:
Does anybody know how to serve a websocket with one flask app?
i also used python socket, it works for both server and client, but... i cannot combine it on one ip address
class DeleteContact(ListView):
model = AdressEntery
template_name = "main/contact_list.html"
context_object_name = "contact"
def get_queryset(self, *args, **kwargs):
queryset = super(DeleteContact, self).get_queryset()
return queryset.filter(id=self.kwargs['pk']).update(active=False)```
I need help in Django, how to redirect the url?
i know this method contains http_method_not_allowed ()
in html form there is a link that looks like this: http://localhost:8001/api/contact-list/delete/35 - and after clicking on the link it leaves me on that same page
and I want it to redirect me to this page: http://localhost:8001/api/contact-list/ - shows contacts
yy
:incoming_envelope: :ok_hand: applied mute to @inland copper until <t:1630572378:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
RIP
i decided to use webpack and babel to bundle and transpile my react frontend, and now I have problems with my project
I get this error when I runserver in django
"GET /main.js HTTP/1.1" 404 4309
this is my webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: path.join(__dirname, "src", "index.js"),
output: {
path: path.resolve(__dirname, "./build/static/js"),
},
module: {
rules: [
{
test: /\.?jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
},
},
{
test: /\.?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
},
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: ['file-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "./build/index.html"),
}),
],
};
this is my babel.config.json
{
"presets": [
[
"@babel/preset-env"
],
"@babel/preset-react"
],
"plugins": ["@babel/plugin-proposal-class-properties"]
}
these are my dev dependencies in package.json:
},
"devDependencies": {
"@babel/core": "^7.15.0",
"@babel/preset-env": "^7.15.0",
"@babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"html-webpack-plugin": "^5.3.2",
"webpack": "^5.51.1",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.1.0"
}
and this is how it manages static files in settings.py:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'apps/frontend/build/static')
]
So I am taking input from users in number. How can I add all and print it on a page?
I've got the same issue but with Flutter. +Django
I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE.I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.
it used to work perfectly for me, before I installed webpack and babel, and now idk how to get it to work again
It's my first time doing a full stack web application and i've got no idea at the moment as to why it's not loading, certainly feel like missing part of the puzzle unless i've overlooked something!
These labels for my models... what class and attribute can I change these labels in admin.py?
This pattern worked in Python for Regex, but lookbehinds like this aren't allowed in JavaScript or something?
How do I convert this into something that works in JavaScript? I don't know JavaScript or Regex well.
The regex is trying to match words beginning with underscores but not words with underscores inside them - works fine in Python.
regex = r'(?<![a-z])_[a-z]*'
Edit: For my purposes it was fine to not do the look behind and just use a character like ![a-z])_[a-z]*
if you fix the problem, can you let me know, please?
there is literally redirect function
https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/#redirect
possibly python manage.py collecstatic command is missing or something like that
https://docs.djangoproject.com/en/3.2/howto/deployment/
if I wouldn't have run that, then it wouldn't even grab the static files
Right here the problem is, that it's searching for the static files in localhost:8000/main.js
why are you trying to access main.js file though
should not it be index.html?
and not just grabbing it from static files
I used webpack to bundle the build
So it's literally just an html file and a main.js file
the main.js file is inserted into the html
django can get the html, but for some reason not the main.js
Right here the problem is, that it's searching for the static files in localhost:8000/main.js
I thought you expected to search at this route
which route you expected to have?
according to your settings
/static/main.js
should be current address of this file probably
if you want your static files served without /static/
change STATIC_URL variable to /
or explain your problem further
right
and this is how it looks in the main directory/static
pretty much, what django does, is it take all the files from the staticfiles dirs, as it's stated in settings, and puts all of them into the main directory/static, which is the static root
and then from there it should display them onto the website
the problem is that it's searching for main.js's directory as localhost:8000/main.js, when quite literally it's not a website directory, so it should search for it in the website files(static files)
the correct path should be /static/js/main.js for this file
yes
so... your links in frontend are broken to search main.js at /main.js url
that's your problem?
could be
let me check
<script defer src="main.js"></script>
it looks fine in the html file
so, you have relative path written here
you access index.html at folder /
relative path searches for the file in / (the same path as /index.html is)
it worked correctly.
<img src="picture.jpg"> The "picture.jpg" file is located in the same folder as the current page
if you wish to access the file from /index.html... you have next options:
- changing path to "js/main.js" | "static/js/main.js" or something like that
- changing to absolute /static/js/main.js
- changing static_files in django settings, to collect all statics into one level folder instead of having sub folders (it will lead to collisions for same named files)
- perhaps there is some webpack/react/frontendframework solution I don't know, like using some special flag during front building
ok, thanks
Morning everyone.......I have been trying to create an API using rest framework that allows user react to a comment and I got stuck somewhere....Anyone familiar in DRF?
hi there i am a complete beginner to web development in python. i don't know python even. from where do i start?
and python itself too?
yes
thanks
is it your first or not first language?
first
uh.
?
idk they're too long sort of like 2000 pages, can't i have something short?
I'm currently working on my small Flask project and I got stuck at some point. I got stuck on Response method because it doesn't work as I expected. When I use it in my code it's available only in 1 tab unless I run it with Gunicorn with more workers and threads, but that's not what I want. I want it to be accessible in multiple tabs with same content. Is there maybe some other method that I should use?
you are right about redirect but the problem is that ListView and get_queryset do not allow HTTP methods e.g. response or redirect.
Thanks for the answer, I found a solution to this with the help of override method
class DeleteContact(ListView):
model = AdressEntery
allow_empty = False
template_name = "main/contact_list.html"
context_object_name = "contact"
def get_queryset(self, *args, **kwargs):
queryset = super(DeleteContact, self).get_queryset()
return queryset.filter(id=self.kwargs['pk']).update(active=False) # filter by clicked contact card get id and set active false
def dispatch(self,request, *args, **kwargs): #this method allows us to use methods such as (post, get, put ..) and allows us to return HTTP methods such as (response, redirect)
super(DeleteContact, self).dispatch(request) #dispatch method will override the second method and allow us to do redirection
return redirect('/api/contact-list/')
Guys why am I getting redirected to this link: http://127.0.0.1:8000/projects/undefined (to undefined)? I have a file called projects.html and implemented correct redirecting methods.
Can you show the code?
ofc.
return render(response, "projects.html", {})```
urls.py:
```urlpatterns = [
path("", views.home, name="home"),
path("projects/", views.projects, name="projects"),
]```
Redirection was working up until I changed the name of the html file
What a chaos car 😸
But I start liking it's drifting 😁
Btw, of you want to make more points for the 3k needed, stay in Pro league.
Very slim races in Elite, I needed to quit EIGHT races to get back to Pro as there are almost no races except 1v2 or so...
Wrong channel (and possibly server)
Looks like Asphalt 9
Was a nice game
Oh 😁 sorry guys
@native tide go ahead
I am trying to use Model Form's with class based views but I can't get the submit button to work
Here's my code
my forms.py
from django import forms
from .models import Volunteer
class VolunteerJoinForm(forms.ModelForm):
class Meta:
model = Volunteer
fields = '__all__'
my views.py
from django.http.response import HttpResponse
from django.views.generic.edit import FormView
from .forms import VolunteerJoinForm
class VolunteerJoinFormView(FormView):
template_name = 'website/join.html'
form_class = VolunteerJoinForm
success_url = '/join-success/'
def form_valid(self, form):
return HttpResponse('DONE')
my join.html template
{% extends 'website/_base.html' %}
{% block title %}Join Us{% endblock title %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% endblock content %}
Whenever I click on the submit button, I get redirected to the same form page join.html
And no data is getting saved into the db
basically submit is doing nothing
you have to define the get method and post method
In my CBV you mean?
yes
see my code
class Events_view(View):
model = EventForm
events = Event.objects.all().order_by('-updated_at')
context = {
'events':events,
'form':EventRegistrationForm,
}
def get(self,request,*args,**kwargs):
if(len(self.events)==0):
messages.info(request,"no events for now.")
return render(request,'events.html')
return render(request,'events.html',self.context)
def post(self,request,*args,**kwargs):
form = EventRegistrationForm(request.POST)
if(form.is_valid()):
form.set_event(request.POST['event_name'])
form.save()
messages.success(request,"form submitted",extra_tags="success")
return render(request,'events.html',self.context)```
see ive overrided get and post and returned rendered response according to that
I will try to do as you told me and get back to you
Can you please format your code, it's hard to read on Discord
Surround the code with three backticks
ok
\```
\```
done
Try to write the word python right next to the first set of backticks at the top
it should also add syntax highlighting
ok
Can anyone please help with this?
bro def projects(request)
not response
same in render(request)_
if i correctly understood your code
I get the same error
i did
what is the error saying
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/projects/undefined
Using the URLconf defined in .urls, Django tried these URL patterns, in this order:
admin/
debug/
[name='home']
projects/ [name='projects']
portfolio/ [name='portfolio']
The current path, projects/undefined, didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
it's getting redirected to undefined
stays at projects for a while
and then goes to projects/undefined
https://docs.djangoproject.com/en/3.2/ref/urlresolvers/
apply reverse url, that's cooler than writing direct html
are u using js in this html
yep
so check if u write some redirect code there
wdym
you can redirect using js also
so if u wrote some js code which redirect you to some value
because undefined is a js data type
How to display the names instead of pk in the list viewset in Django Rest Framework?
https://www.django-rest-framework.org/api-guide/relations/
u start to use nested serializations
Django, API, REST, Serializer relations
thanks for the reply bro will check this out !
ive read it before but ill see
yup i tried it before didnt work
@manic crane what did you try, exactly?
You can override the .to_representation() method of your serializer, or use StringRelatedField
I'm getting this error in React:
Warning: [object Object]: ref is not a prop. Trying to access it will result in undefined being returned.
However I used this exact code in another project and it was working. Is ref just bugging out here or can I really not use it? I don't get this error in the other project.
this may help you? https://stackoverflow.com/questions/38089895/react-ref-is-not-a-prop
I'm using it in another app and I'm using it with forwardRef so it should work according to this: https://reactjs.org/docs/forwarding-refs.html
I want help in django please
when I open django admin dashboard then all model tables are show but add delete edit option not showing?
what should I do?
I already ran command makemigrations and all tables are showing but option like add edit delete not showing?
Did run the command migrate?
python manage.py migrate is required to make the changes to the DB. makemigrations is just prepping the files for the change
And again, admin does NOT show edit or delete commands for the DB structure, only data. You edit/delete models in models.py
okay
You use admin to edit or delete records. But the DB structure is all driven by models.py and makemigrations/migrate commands
I'm not talking about commnds
I'm talking about buttons which are appears in django admin such as add new, or delete item
Right. But you've not migrated the changes to the DB yet
yes exactly I want to edit or delete records only
yes right
And to do that, you need to run migrate to change the DB model.
will do it
thanks a lot
I would suggest watching a tutorial or reading a book on understanding how the Django ORM works.
yes I will do
You're welcome.
As a tip, I backup with version control before makemigrations and migrate. Those two commands can have interesting results if your model is not perfect.
oh okay got it
The only time I've ever needed to hard reset a git branch was on changing the model and having a field setting incorrect. In particular, default values for image fields are nasty if you get them wrong.
I am using django-rest-knox everything like login and register from postman is working fine but I can not create user from admin panel as it do not show email field
Do I also have to update admin.py for django rest knox??
Django question: I have just created a new template with an image. In dev the template and image renders perfectly. In prod it will not load.
When pushing the new image to prod I can see the additional count in collectstatic. So I know the image is brought over. And bear in mind, this is an established prod deployment that has many images.
Why would an image in the same static directory successfully serving up images not load in prod when it clearly loads in dev? Using nginx.
The irony is, I'm only creating this page because I need to get a URL path to be able to render these images for articles.
Does anyone know how to get context data within a function based view in Django?
I know how in a class based view, but that's not translating for me.
not translating in a function based view.
you would normally make a dict containing the context then pass it through with the request
What if the data is in the model?
what do you mean by that
I have a function based view to create an object, and within that object I want the end user to select a specific object from the model to attach it to. Like, Book to Author, the user can name the book and then choose from a list of authors and assign the book to the author.
The list of authors is coming from the model.
so you want the list of authors as context?
I think so, yes.
all authors or specific authors?
Specific, I want to filter based on the user to entered the authors name.
are you going to get the authors name through a form? if so you can access the POST/GET data through request.POST or request.GET
Yes, I have a form that they'll be filling out.
so I'd say filter the authors using whatever author the user puts in the form and pass that in as context, are you trying to access the data the user is inputting into the form?
So what is the issue? Is it the drop down or filtering the authors?
Once you get the list of authors you can iterate it for the drop down
I don't know how to get the list of authors from the model within a function based view.
I know how to do it in a class based view, not a function based view.
And you want to filter the list of authors depending on the book title?
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'].fields['author'].queryset = author.bjects.filter(customer_id=self.request.user)
return context
No I want to filter the list of authors based on the creator
That's what I use for a class based view and it works well, but I want a function based view due to some extra processing and that's what I'm more comfortable in.
What are you specifically filtering for when it comes to the authors because im a bit confused
I want to list all authors, and then filter for authors that were entered by the logged in user.
For example, if there are 100 authors in the model, I want to only display the authors that I've entered myself.
So you want to list all the authors the user can pick right and which ever one they pick all books from the author will be shown right?
basically.
You want the user to input it though a drop down or input?
I want the user to select the author through a dropdown.
Will the books only show when the author is selected or will it show before and after when the author is selected?
You’d want to pass in 2 querysets, one for the authors and books
It's not that complex, I literally have a blank form, I want the user to enter a book title and then select from a dropdown list the author.
Book Name "Harry Pawter"
Select from a dropdown list of all authors that I manually entered.
Django question: I've deployed a web site in production through Docker/Nginx. When I add static images I can go to the docker container and collectstatic. Is there a way to configure the ngnix.conf file to update static files after the build? Currently, this is not happening automatically.
Get whatever the request.GET data is and pass that in the filter for the for the books.
I can do a get within a post request, or would I perform it on the outside of the post request.
@ionic raft I can't answer your question specifically but Django has a 3rd party app called WhiteNoise that will allow Django to serve the static files no problem.
Thanks. I'll keep that in my back pocket. The existing deployment is working very well. I can manually collectstatic after a docker build, but I am wondering if I can enhance the existing application
What do you mean by this?
The end result is this: https://lanesflow.io/articles/article/4/
btw @nova sonnet I really appreciate your help on this.
You can check if there is any GET data through an if statement in the function (such as if request.GET: <do something>)
Ok, I'll try to figure it out then.
I did some further testing. it turns out, if you run collectstatic the docker build/nginx caches static files for future builds. I only have to run collectstatic once for new files. That's a relief 😄
from flask import Flask, request, redirect, render_template, abort
from steambot import client
from panel import *
import multiprocessing
import steambot
import json
app = Flask(__name__,template_folder='template')
@app.route("/")
async def overview():
return redirect("/prices")
@app.route("/prices")
async def prices():
return render_template("prices.html", items=get_pricelist())
@app.route("/pricelist")
async def pricelist():
return redirect("/prices")
p = multiprocessing.Process(target=lambda: __import__(steambot))
p.start()
if __name__ == "__main__":
app.run(debug=True)```
why my flask app wont start? only steam bot is running
guys so I am making a os and I dont know the place to go to!
Unfortunately, this channel is not going to much help for making an OS.
I have no idea. And no, I don't know Grepper. This is a Discord for the Python programming language, and this particular channel is for web development using Python, typically Flask or Django
hello django newbie here I have a question
How to get the request user in .save method in django
It's best just to ask away 🙂
Can you elaborate? Are you trying to save the user triggering the request somewhere?
If so, I would look to store the user into a user field in a Model.
No. Because by doing that you're hard coding the letters pk into the path. The int:pk is explicitly telling Django that it's a variable. It will look for that variable from the static link in the template.
thanks
is it better to use generic views or class/function views?
Hello, "Unable to log in with provided credentials." I have this error but when I check the network tab and check the request payload my credential was correct.
Just searching for some more information, I'm trying to make an full stack web application with Flutter & Djanjo, but apparently if I do this, it's actully called a ' Progressive Web Applicaiton' ? Would you still call it a Full Stack Web Application?
Hmm have you tried using lighthouse and check it if your application considered as a PWA? In the project I have right now I'm trying to make the application as a PWA.
https://discord.gg/code try to go here. they have OS channels
The other invites are also related to the question, right?
I'll add it to our allowlist
I've got a prod server with docker containers running. Say I wanted to push an update from dev -> prod, do I always have to git pull, then restart my containers? Or is there a better way about this?
I prefer doing it with ansible
it allows me
- relaunch the deploying script from my working PC for quick update
- or having ability to destroy server and install to fresh one from zero with the same one command
no attachments that pollute the server beyond your code, everything is version controlled
But in either case, the prod server will not be usable once the update occurs right? So the website will be down?
ansible => connects to servers => installs docker if it is missing => copies the code and builds the image and runs
yes. There is quick solution about it though
for example if you would be using Hetzner provider, they allow Floating IPs
temporally attached to any server
you could have it attached to your domain
and when you update
you... create new server
install, check that everything work
and then in one click reattach ip to new server
if everything goes ok, you destroy old server, if not, switch back
same could be done manually if you will have additional server with reverse proxy
Cool, so essentially a second server on the old codebase while the main prod server gets updated. I think AWS has some feature like that too
I think it is called Blue-Green deployment, when both environments exist at the same time
essentially, old server has old code base, new server is installed with new code from zero.
switching accurately traffic from first to second one, while looking if we need to switch back in case of emergency
(context django)
https://paste.gg/p/anonymous/656a1af07ef042628e7ebee644265f77
in product create page productimageform is having product field why?
Say you had a domain and an A record that points to your prod server IP. Could you add a second A record to use if that first one can't connect?
Redirecting to a different server essentially
as far as I know A records work like... primitive load balancers, users got sent randomly to one of them
you could have several servers raised with identical software
and distribute your user load between them
through DNS usage
Hmm, this is definitely worth a read. I feel like there is definitely something out there with AWS that probably solves this. I'll have a look there later.
I appreciate the help :)
you could ask, what would be issue, and why would it be primitive? Answer: there is no healthcheckers. If one of servers is down, % of users would be still sent to dead server
normal load balancers (like Haproxy) can have healthcheckers
sending only if the servers are alive
u a welcome ;b
quite loving a bit of devops. it makes life easier to devs.
I'm liking it too. All started with Docker! Lovely to have on the CV too :)
me three 😉
tbh I even decided having devops as my secondary direction
I'll first finish learning essentials for high level backend though
then I will dive in a more advanced devops
Yeah I've seen that, although I thought Full Stacks, didn't do PWA to be honest, I'm not sure if this is frounded upon rather doing full applications
tried stringRelatedField
@manic crane OK, and how did "it not work"? Did you create a str method for your model?
question: CORS does not stop cross site forgery requests, correct?
class PostSerializer(serializers.ModelSerializer):
clique = serializers.StringRelatedField(many=True)
class Meta:
model = Post
fields = ('content', 'caption', 'posted', 'clique' , 'user', 'status')
'Clique' object is not iterable
What's your model
AttributeError: type object 'CliqueSerializer' has no attribute 'StringRelatedField'
hi i want to know what these signs are called like r and w+ or $
What's your model
Need to see some code to be able to help.
what is the point of using python venv inside docker image?
(context django) best way to add a markdown editor for a textfield?
i am looking for something like the editor on stackoverflow
**where to start
Everyone wants to learn new skills and deciding which skill to learn is easy. But, the difficult part is WHERE TO START? People often get lost on this huge web in the quest of the best, personalized and easily available course.
Organized Learning
An issue we face when it comes to learning multiple skills is management/organization. It becomes hard to organize what, when, how and where you have to learn.
EdTech for Rural India
Urban and Rural students often face differences in terms of financial conditions, exposure, language, etc. despite this, they all deserve a friendly platform to learn.** which one i can do asap and easiest plz suggest
@opaque rivet @inland oak
Is there anyone with experience architecting django?
I stand before the decision on splitting an app into small apps or modules but I do not have enough experience architecting django and some consultation would be very useful.
It's difficult to ask a more specific question on this topic.
django apps represent basically modules
each django app has separate set of tests / views / model
best recomendation is usually separating into django apps, if you feel that those are two different entities and logically they should be tested separately
usually separating into another django app... comes from the size of the thing
how can i put the text on the picture and how can i make the picture on the whole screen?
if you know that it will eventually be big one, feel free to separate, in order to not overbloat the current app
Does anyone know if its possible to manage the search results of google by geo location? For example, when having a real estate listings website, and you are in New York... when googling for offices. You will get Offices in new york... But for real estate listing websites this is crucial. I want to show my top visited pages or most important ones, and not the one where the user is located at. Anyone have an idea how to tackle this? Please tag me.
@gusty wagon could use the IP of the user to determine their location. Then show listings based off that.
What can u do with web-development in python ?
anyone worked with ckeditor?
sorry for the late reply man
it's fine, could you format the code to make it more readable?
like that ?
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.
oh okay 3 back ticks each
class CliqueObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(level='public')
options = (
('private', 'Private'),
('public', 'Public')
)
name = models.CharField(max_length=200, null=False, blank=False,default='')
occupiers = models.IntegerField(null=False,blank=False,default='')
created_at = models.DateTimeField(auto_now_add=True)
occupation = models.CharField(max_length=90,null=False,blank=False,default='')
level = models.CharField(max_length=10, choices=options, default='public')
objects = models.Manager() # default manager
cliqueobjects = CliqueObjects #custom manager
def __str__(self):
return self.name
class Post(models.Model):
# filters posts so only published posts are avaible in the home screen .
class PostObjects(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status = "posted")
options = (
('draft' , 'Draft'),
('posted' , 'Posted'),
)
clique = models.ForeignKey(Clique, on_delete=models.PROTECT, default=1,related_name='cliques')
content = models.TextField(max_length=400,null=False, blank=False,)
caption = models.CharField(max_length=400,null=False, blank=False,)
posted = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clique_posts',)
status = models.CharField(max_length=12, choices=options, default='posted')
objects = models.Manager() # default manager
postobjects = PostObjects() # custom manager
class Meta:
ordering = ('-posted',)
def __str__(self):
return self.caption```
first thing that comes to mind:
clique = serializers.StringRelatedField(many=True)
The Clique model has a one-to-many relationship to Post (with Clique being on the one side, and Post being on the many side), so many should be False.
clique will always be a singular object, which is not iterable, hence the 'Clique' object is not iterable error
but der can be many cliques ?
one Clique object to many Post objects unless I've missed something.
oh no i can make more than one clique
can you elaborate?
like i the drf request page it lets me make more than one clique
more than one post
wait actually just revised on one to many relationships
i am getting this error
An invalid form control with name='description' is not focusable.
i rendered the form with crispyforms
and have this
<script src="https://cdn.ckeditor.com/ckeditor5/29.2.0/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create( document.querySelector( '#id_description' ) )
.catch( error => {
console.error( error );
} );
</script>```
what i got to know is that ckeditor makes the input hidden and it is required.
this error is raised when you submit the form because the input remains empty when validating
i added `blank=True` to description field but i want it to be required you know of a better solution?
ohhh i get the many to many relationship one clique but many posts !
one-to-many, yep
what if you attach that function to the onSubmit attribute of the form?
ok so to fix is to set many false ?
it would be a step in the right direction
thanks dude
which function?
Possibly you could make this into a function?
<script>
ClassicEditor
.create( document.querySelector( '#id_description' ) )
.catch( error => {
console.error( error );
} );
</script>
its ckeditor script, you need it for wysiwyg editor
ah okay. wasn't sure what that does. i'm not sure then!
i have a django question. can someone help me ?
go ahead
the date doesn't show on the template. I am using generic views
show the view? is the date a datetime object?
class AuthorDetailView(generic.DetailView):
model = Author
context_object_name = 'author_detail'
template_name = 'catalog/author-detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['author_list'] = timezone.now()
return context
yes date time object
that I know of, objects can't be represented in templates. So you can convert it to a string:
https://www.programiz.com/python-programming/datetime/strftime
In this article, you will learn to convert datetime object to its equivalent string in Python with the help of examples. For that, we can use strftime() method. Any object of date, time and datetime can call strftime() to get string from these objects.
i heard you can do something like this : {{ book_detail.date_of_birth|date }}
or like {{ book_detail.date_of_birth|date:'Y-m-d' }}. but it didn't work for me
I'm not sure as I don't work with templates, but you could .strftime() in the get_context_data() method
ok thanks. i'll try
Does anyone know if it's possible in Django to access management form attributes inside a template? I'm trying to dynamically add new form fields but I think the management form TOTAL_FORMS field needs to be updated for extra forms to be submitted. Any ideas?
Yeah, 1
1 for sure
thanks 👍
A LOT. Django/Flask are web development frameworks. Google sites built with Python and you'll see some big players come up.
Flask is great for getting going. Django is amazing for more complex sites (there's a link on my profile to a site I built with Django/Python. Didn't know any Python before April 16, 2021.
oh
Side by side for sure. More obvious that it's a choice
If you want a fancy front end you can add a JS Framework like React of Next.js to the mix. However Django/Flask are very powerful application layers. When you pair Django with a Postgres DB you have a stack that is truly enterprise ready.
You need to combine both. For example, {{ article.date_written|date:'F j, Y' }}
You can use strftime in the view, but I typically go with a consistent format in the DB and use the |date:'F j, Y' formater in the template.
Interesting question. The bottom button has greater separation, and feels more suited as a CTA. However, if the text 'Let's dive in' is not clickable I wondering if it might distract...
That said, once you pick your CTA colour and consistently apply, I say that lighter blue is better. It flows with the darker blue above and yet stands out.
Ok, I'll remove the "Let's Dive in" and have them the blue color
What is more important...that the user finds or reviews?
this is for the mobile view which is a bit different
I'd say they're the same
What about both buttons the same lighter blue? Maybe see that with a screenshot of the entire view?
Oooo...
Is UniHalls a hyperlink?
Footer, redirects to main page
I have to say (and this is but one opinion) I definitely prefer the lighter blue, and a consistent CTA. But then that's a preference. I want to train the user to know what to click and they don't have to think about it.
With the clickable logo being the same colour that fits
What about 'Contact us' text also being the same CTA blue?
Nice, I agree
Will do. Gonna go for a run now though ;P
this is the view on a computer
and this for the mobile. added some shadows and I think it looks nice
In short, everything that is a CTA is that blue. And seeing the lighter blue on the darker blue...yes. I like.
I'd change the two buttons on the computer view to the lighter blue too
I'm a HUGE fan of button shadows...
Interestingly, I break my own rule with the Support and Signout buttons.
All text links are the light blue. But the signout I make white so that it stands as a secondary click.
Support is dark blue because I'm not looking to drive them to create support work for us 😄
I think it looks worse. Maybe because of the "lets dive in"
Actually it looks alright... hmmm
Agreed. Either remove the Let's dive in, or change to dark blue.
But I think it's a redundant invitation.
Also, change 'contact us' to same lighter blue perhaps?
But then, you've posed the question...Ready to get started? This is the invitation. Let's dive in doesn't add anything. The buttons are clear implication for behaviour
Hello guys! I want to send {{projects.thumbnail}} object in Django (which contains an image) to onmouseover="DisplayThumbnail()" as a parameter inside DisplayThumbnail so that it can be processed by JS. Is it possible?
I would keep the space between the words and the buttons equidistant above and below. If you remove the dive in, keep the white space...And now that I think about it, keeping contact us as dark is solid option too. Contacting is not really a CTA
i love it dude
@ionic raft I'll test out colors later, heading on a run.
@fossil pond you think light blue > black?
Enjoy. 😄
Thanks! 👍
The light blue and black combo looks sick yeah.
I think that the lighter clue as the CTA is a very nice combo with the darker blue...
I mean, for the color of the two buttons, on the light gray background
Aah, design is my downfall 😁😁
At least I can change things quick with tailwindcss
Yeah I can relate. Having a designer as a partner would be pretty amazing ngl.
The lighter blue is definitely preference for me on the light grey background...
Here's my latest UI...very close colours to what I've gone with...
My big challenge was picking a CTA colour for a data rich experience. This is a portal for project management after all. In the end, making all text links that light blue really pulled them forward. I'll be curious what alpha testing reveals
Your focus on the smartphone app form factor is ideal. Your target market will mostly be using this on their phones.
Hi Everyone
As a JavaScript & PHP software engineer, I am looking for a full-time job using my skills recently.
If you have any jobs, please let me know.
Actions Speak Louder than Words
I hope your business is doing well
Thanks for your time.
how I can make a login and registration in Django using email not username please help me anyone
is anyone there ?
take a look at that link
https://www.codingforentrepreneurs.com/blog/how-to-create-a-custom-django-user-model
HI Everyone.
I have been out of a job search again due to lack of experience.
how did you guys? They know of a project where I can collaborate with Django to gain experience
Thank you bro for helping Thank you so much
I was looking for this for hours
My project is giving me the error with status code 500, which means that I haven't got the same methods used in my http requests/api calls. Even though the methods are the same in both my django views.py, and my react frontend axios get function:
class UserView(APIView):
def get(self, request):
function isAuth(){
const response = axios.get("/user")
console.log(response.data)
}
this is the error:
createError.js:16 Uncaught (in promise) Error: Request failed with status code 500
u a using promise based js library
https://github.com/axios/axios
correct get requests with it:
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
speaking in python terms, you used coroutine function, which you did not await ;b
So if I await it, it should work?
nah, better use then instruction
Does it make much difference tho?
const response = axios.get("/user")
console.log(response.data)
replace to
axios.get('/user')
.then(function (response) {
// handle success
console.log(response.data);
})
my javascript knowledge is enough to know that this version will work
Ok, thanks, will try it out
while await I am not sure if will work, because it could be requiring additional requirements... like async env, what needs for that in js I have no idea.
Ok
nope, it still gives the same mistake @inland oak
I've tried to add async and await to it
and it gave me this error:
Uncaught ReferenceError: regeneratorRuntime is not defined
oh right, that's probably because my babel config can't transpile it
give me a sec
ok, I fixed the babel part, but I still get the error 500
How else can I try to fix this? @inland oak
@inland oak .then() is just syntactic sugar for await. However, I don't know how you'd handle errors (non 2xx) with await.
Enable debug true
it is
from the console?
assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
[03/Sep/2021 22:24:49] "GET /user/ HTTP/1.1" 500 80418
this is what it gives in console
Or see django error log
if it says anything to you
You return something wrong in /users view
In python
I am facing a certain issue with Django. When I upload picture to my model it gets saved on static/images but when I run the code it looks for the image in the folder static/images/projects (projects is the name of the html file
It's returning json
How it returns Json
as a serializer
user = SteamUser.objects.filter(steamid=payload['steamid']).first()
serializer = SteamUserSerializer(user)
return Response(serializer.data)
Response() is a rest_framework function
Looks legit
Hello can someone help me , when i type py manage.py collectstatic there's no css for the admin page while my static settings is
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Let's start with saying, that whitenoise is bad
Really bad
@fossil pond what's the code?
ok gonna remove it but i believe that wont create css admin
No idea how u run the server
urlpatterns = [
path('admin/', admin.site.urls),
path('__debug__/', include(debug_toolbar.urls)),
path('', include('main.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)```
settings.py:
```STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'main/static/images')
i have css for my admin on other site while they have the same static settings
check your templates code in settings.py
Enable debug then.
Runserver is for dev anyway
it's enabled
projects.html:
<ul class="list-group mx-auto justify-content-center list-group-flush">
{% for project in projects %}
<li class="list-group-item"><a href="#" class= "project-link" style="text-decoration: none;" onmouseover="DisplayThumbnail('{{project.thumbnail}}')"><span class="projects-title">{{project.title}}</span> <span class="projects-summary">{{project.summary}}</span></a></li>
{% empty %}
<h4 class="display-4">There are no available projects as of now :(</h1>
{% endfor %}
</ul>
</div>
<div class="col-6" id="ImageContainer">
<img style='height: 100%; width: 100%; object-fit: contain' id= "thumbnail" src="{% static 'images/rdr2.jpg'%}">
</div>```
project.thumbnail is the image basically
Shrugs then.
Fell asleep
Didn't change anything its basically this:
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]```
hmmm, seems strange
how is it imported into your html/css?
yea have to manually place images on that folder quite cumbersome
what shall i do then , nuke my project ?
hahaha
i have css admin in staticfiles folder
but not in static folder
gonna copy it and add it in static folder
they are the same so
views.py for the main app:
def projects(response):
projects = Project.objects.all()
return render(response, "projects.html", {'projects': projects})
Other than that it's all basic stuff
can you send the error traceback
No error traceback. When I make the folder and put the images they get displayed. When the folder isn't there i get a 404 saying image not found
Not Found: /projects/coolman.jpg
[04/Sep/2021 01:12:52] ←[33m"GET /projects/coolman.jpg HTTP/1.1" 404 3102←[0m (when I don't manually place the image inside the projects folder)
wait, so if you are uploading the image to your model, then it should save in db, right?
Uploading it from the admin panel. It's a model class attribute.
title = models.CharField(max_length=200)
thumbnail = models.ImageField(null=True)
body = models.TextField()
slug = models.SlugField(null=True, blank=True)
summary = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.title ```
Basically the thumbnail
Yeah, I'm not sure if there is a way to fix this
only if you can somehow change the directory of where your images are saved if you upload it from local storage, because usually it is just saved as a link, and it can easily refer to it from anywhere
omg i fixed it!!
replaced project.thumbnail with project.thumbnail.url in the html
worked
yeah, i was thinking that it had something to do with project.thumbnail, but wasn't too sure
well done
any image should has .url
since it directs to the url of the image from static folder
but nice
Think I'm burnt out, think I just spent 2 hrs for a simple react animation
Anyone one the best way to make a select menu like this?
I want to start reading a few technical books. I'm starting from obey the testing Goat. Dies anybody want to join me? We'd act as accountability partners and discuss what we read at intervals
Oh that doesn't sound so good. I'm holding off on starting learning React. Building a billable hours app for consultant subscribers in my web app.
I do need to get to the Map App next though...and that means React!
That's a question that when I started to get answers became a rabbit-hole...uploading media....
In the end, I dropped profile pics and logos entirely. I opted to not use media entirely. If you upload images to the app server (/media/) then you lose statelessness and potential for load balancing. If you upload images to the DB other risks surface. I kicked that can down the road.
It's one thing to have media in development. But in production, it's another matter entirely.
Guys i need help in django, i have two views, one is to delete something and another one get it. However, when i call the view to delete and view to get it at the same time, it actually gets the result before it is even deleted
How can i fix this... i know this is about smtgh like async but i'm pretty weak in this
# profile/<str:pk>/edit/
class UserProfileUpdateView(LoginRequiredMixin, UpdateView):
...
this is not sufficient for this view. Not only should the user be logged in, but they should have to be the exact user specified in the url. in a class based view (same as always) I dont know where to put this logic.
Some form of locks is necessary to deal with it. Which lock implementation to use depends on... what u a building, student/work and etc
If to say simplest choice use redis-locks to block access to object during operation. Redis locks are universal and fast. They use key-value in RAM memory.
If u a dealing with sql database, they have their own database level locks
The most simplest and primitive, would be just blocking by creating file and checking its existence
It will make sure to deal with one object in.. sequence. Depending on which operation will reach django first.
If it is not sufficient for you, you could lock object in advance. Not knowing your case enough to suggest more precise answer
Unless u know for sure, I would recommend redis locks. They are meant for this, fast, comfortable code interface
The most precise locks would be probably database level locks, but I am not sure if there are good libraries to deal with it. Django ORM supports them or not
class UserInRoom(APIView):
def get(self,request,format=None):
print("userinroom")
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
data = { 'code' : self.request.session.get('roomCode') }
return JsonResponse(data,status=status.HTTP_200_OK)
class UserLeaveRoom(APIView):
def post(self,request,format=None):
print("userleaveRoom")
if 'roomCode' in self.request.session:
print(self.request.session.get('roomCode'))
self.request.session.pop('roomCode')
host = self.request.session.session_key
roomToDelResults = Room.objects.filter(host=host)
if len (roomToDelResults) > 0:
roomToDel = roomToDelResults[0]
roomToDel.delete()
print("done deleting")
return Response({'message','You have left the room'},status=status.HTTP_200_OK)
Here's part of it, but i couldn't understand what ur saying hehe
The solution i have atm is
To use setTimeout
But i'm not sure if it's the best solution
In the original case, room is get before it is done deleting
class UserInRoom(APIView):
def get(self, request, format=None):
print("userinroom")
if not self.request.session.exists(self.request.session.session_key):
self.request.session.create()
data = {"code": self.request.session.get("roomCode")}
return JsonResponse(data, status=status.HTTP_200_OK)
class UserLeaveRoom(APIView):
def post(self, request, format=None):
print("userleaveRoom")
if "roomCode" not in self.request.session:
return Response(
{"message", "No room has been found"}, status=status.HTTP_404_NOT_FOUND
)
print(self.request.session.get("roomCode"))
self.request.session.pop("roomCode")
host = self.request.session.session_key
deleted_rooms = Room.objects.filter(host=host).delete()
if deleted_rooms:
print("done deleting")
return Response(
{"message", "You have left the room"}, status=status.HTTP_200_OK
)
a bit of formatting before doing anything
you know.. the simpliest solution would be just
returning proper error that room got dissapeared
where you request the room
return something like
return Response(
{"message", "The room was deleted"}, status=status.status.HTTP_410_GONE
)
pooof. no problem. ;b
hmm.
oh wait
that can be done simplier ;b
see... the problem we have
that you keep in which user room in session
What if userin room is ran before the Response is called
so... if we have always delay between operations
while requests reach the server
think about using cookies 😉
cookies store user info client side
Hmmm
so you can be fast enough to delete information about him leaving the room
or client side local storage, whatever
Are the syntax almost the same
not really
client side operations are made in javascript mostly
cookies can be accessed/created server side at the same time in python
so... it is like a mix of two languages here, and mix of frontend and backend
====================================
essentially you would have something like this....
User creates Room, he gets cookie, preferably JWT Token, that he is in this room, and that he is the host (you have logic like this, right?)
User leaves the room... Request is sent to server to delete the room in case he is host, and his cookie is deleted
Yes....
a bit unsafe, since in order to delete the cookie we will need it being visible to javascript, but it should work
Cookies in the form of JWT Tokens have verifications that they were produced by your server