#web-development
2 messages · Page 189 of 1
PROTECT sounds like, parent element will not be able being deleted, until it is out of childs
try placing the class definitions at the top?
You need to import both Students and Admin as well as create the tables for those model classes
they're already created
>>> Students.query.all()
[Student:Students.id Students.fullname Students.dialling_num Students.branch]
``` i dont get the content inside those
Has it stopped showing 'Students' is not defined?
That's probably because the data is not being saved(or committed) to the database
yeah i imported them from models
actually it is in the database
and here's the app
see the same info
Yeah, I see it. Do you still have the same problems? And can you state all the current problems?
well i ahd this but it's kinda minor still bothers me when i first created the app i had been accessing all the modules or the files idk what to name them but i could access them easily with just for instance
i was typing
from models import student ...
now i always have to include
from Flaskiproject.models import students,admin ...
idk what changed
2) i still have the same problem of not accessing data from the db shell
Regarding
- Check if the folder path you're running the commands from in your terminal has the same root as the 'models' module
- I just saw your previous code again, and noticed that you're calling the class attributes instead of the instance attributes
Admin.id should be changed to self.id and so on,
Same goes for Student.id and others```
also another thing i had the issue with is i couldn't render the whole table of the database
return render_template("Admin/profiles.html",Students = Students.query.get(1),date=eleganter_date)
``` i do understand about the get()
but that's the only way it rendered data from the database
i couldn't render all the data in the database while doing Students.query.all()
Students.query.get() gets only one object while Students.query.all() returns a list of objects which you have to iterate through in your template
it fucking worked HHHHHH daaamn boi hahahah thank you sooo much
Sure. You're welcome
I am trying to figure out why this purple space is there, and how to get rid of it>
The website only works on mobile right now, let me know if you know how to sort this
============
Fixed it with this trick https://stackoverflow.com/questions/6040005/relatively-position-an-element-without-it-taking-up-space-in-document-flow
when i do this does it delete the super user ?
So I have a question, let's say I have a REST api backend. If the frontend and backend are hosted in the same host will there be a delay when I call the backend from the frontend?
Or does it depend on the internet connection
The frontend is executed on the user's machine. If you make HTTP requests on the JS side, they're made from the user's machine.
Wait so what will be faster?
1- Make a REST backend that will call an external Api and sort the data then return it
- Call the external Api directly fromt the frontend then sort it
@dry obsidian second option, but you might want the first option if you want to cache external API data and distribute it between users (resulting in less external API calls - which saves cost if its paid).
Oh true, caching the data will be helpful
But is there a big speed difference between the 2 options?
The first option you're sending a request to your backend (and also to the external API), so it'll be slower by the amount of time to request your backend.
Not much, I'd say 200 ms more.
Ok good to know thanks!
I prefer to handle all API work on the backend, because it's easier to work with data using python than JS (opinionated) and it gives you the option to cache. Also if you request from the frontend, users can see the endpoint and abuse it. Routing it through your backend means you can rate limit each user.
Ok I'll go with this option, it fits my project the best 👍
@dry obsidian If the external API requires an API key, you can't go with the second option
Oh true, didn't think about that cause I plan on using the YouTube API
Hello, Ive got some questions about Django apps within the framework that im hoping someone could better explain. I get the reason why you should create apps for user profiles and etc. but i am struggling to know when to create an app for something for a website.
if anyone would be interested in having a chat in the discord voice channels, id greatly appreciate the help
good evening, I would like to put some text (the name of the pizza) on a slice with the hover tool, can anyone help me?
that's what already happen when i used my mouse on a slice
help me tidy up this monstrosity please lol, this is probably the worst solution to the problem but my brain can't think of a better way to do this atm
all I want is to add the "active" functionality to bootstrap's navbar so that the buttons reflect what page you're on - it works but it's so embarrassingly janky lol
<li class="nav-item">
<a class="nav-link active" id="home" href="/">home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/projects">projects</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/contact">contact</a>
</li>
{% if path != "" %}
<script>
console.log('{{ path }}');
$(document).ready(function () {
$('a[id$="home"]').removeClass('active');
$('a[href$="{{ path }}"]').addClass('active');
});
</script>
{% endif %}
path is HttpRequest.path[:-1]
yeah okay sorry about the above mess, this should make more sense I think (?)
I'll go with this for now, but of course if you see me doing something silly here do let me know
I'll just have to split the path string later when I make subdirectories
I think you can get the path via request as it's passed in to the Jinja context. For example, you could do:
<a class="nav-link{% if request.path.endswith('projects') %} active{% endif %}" href="/projects">projects</a>
I want to use jquery so that the specific div of the web page does not change even if I request the page again. What should I study?
sorry I'm a noob here
how do i go to a url with the username as the input
what changes should i make here
<form action="https://twitter.com/" method="get">
<input type="text" name=""/>
<input type="submit" value="Search User"/>
<form>
eg: I type in "elonmusk" and hit submit
and it takes me to this url "https://twitter.com/elonmusk"
im trying to run some simple code to play around with selenium and ive installed everything required (i think)
im currently running this code
but i kep getting this error
Change the form's method to POST.
Change the action so that it's one of your routes (either a new route or the route that serves this page).
In the route that you decide to handle the POST, do the redirect there.
@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
@formal vault help bro
@cerulean badge Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
!paste @cerulean badge
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok thanks
Here is the solution to the problem I was looking for for the search feature in django
from django.db.models import Q
class SearchContact(ListView):
model = AdressEntery
template_name = "main/search.html"
context_object_name = "result"
def get_queryset(self):
query_input = self.request.GET.get('q')
result_obj = AdressEntery.objects.filter(Q(name__icontains=query_input),active=True, user=self.request.user)
return result_obj
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['counter'] = self.get_queryset().count()
return context
<form action="{% url 'search' %}" method="get">
<input name="q" type="text" placeholder="Search...">
</form>
Traceback would be very helpful 🙂
@app.route('/ed/<num0>/<num1>/<num2>')
def ed(num0=None, num1=None, num2=None):
total = num0 + num1 + num2
return '''
Addition is ''' + total```
It's not really getting added but getting concatenated. How can I add?
convert to int
whether in the route
or using a path converter
preferably the latter
it gives an error.
total = int(num0) + int(num1) + int(num2)
which is it framework btw?
I am highly sure that returning
return '''
Addition is ''' + total
is not acceptable
you should return some sort of Response class with body inside it
preferably in json format
Thanks a lot dude.
It worked
def ed(num0, num1, num2):
None values serve nothing, perhaps to remove it
It can concatenate strings not int.
so i did this ```py
@app.route('/ed/<num0>/<num1>/<num2>')
def ed(num0=None, num1=None, num2=None):
total = int(num0) + int(num1) + int(num2)
Total = str(total)
return '''
Addition is ''' + Total
thank you friendo
Hi there, I hit a wall with Django forms.
I made a contact form that posts an email and it works just fine. does what its supposed to.
However, when I try and include the same form in to my home page the post functionality just stops working
the contact_form.html is as follows...
{% csrf_token %}
{{form}}
<button type="submit">Submit</button>
</form>```
and this works perfectly
but when I include this file in my home.html
{% load crispy_forms_tags %}
<div class="container">
<!-- Contact Section Heading-->
<h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Contact Section Form-->
<div class="row justify-content-center">
<div class="col-lg-8 col-xl-7">
{% include 'contact/contact_form.html' %}
</div>
</div>
</div>
</section>```
it does not work
You need to use <form></form> tags
Oh wait you already have them
What exactly isn't working?
Is the request not being sent?
correct, when posting from home.html it does not post
but it does from contact_form.html
my forms.py is as follows
name = forms.CharField(max_length=50)
email = forms.EmailField()
inquiry = forms.CharField(max_length=150)
message = forms.CharField(widget=forms.Textarea)
def get_info(self):
"""Method returning a formatted string
:return: subject, message
"""
clean_data = super().clean()
name = clean_data.get('name').strip()
from_email = clean_data.get('email')
subject = clean_data.get('inquiry')
msg = f'{name} with email {from_email} said: '
msg += f'\n{subject} \n\n'
msg += clean_data.get('message')
return subject, msg
def send(self):
subject, msg = self.get_info()
send_mail(
subject = subject,
message = msg,
from_email = settings.EMAIL_HOST_USER,
recipient_list = [settings.RECIPIENT_ADDRESS]
)
contact/views.py is
from .forms import ContactForm
from django.urls import reverse_lazy
class ContactView(FormView):
template_name = 'contact/contact_form.html'
form_class = ContactForm
success_url = reverse_lazy('contact:success')
def form_valid(self, form):
"""
call the custom method of our ContactForm class
"""
form.send()
return super().form_valid(form)
class ContactSuccessView(TemplateView):
template_name = 'contact/success.html'
this is whats rendered in contact_form.html
and I am almost sure that I am importing this the wrong way in my home/views.py the wrong way
from contact.forms import ContactForm
def home(request):
""""""
form = ContactForm(request.POST)
projects = Project.objects.all()
context = {
'projects': projects,
'form': form,
}
return render(request, 'home/home.html', context)```
the projects render just fine and the view of the form but it does not post
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I want to make a progress report model which is of 3 types report,invoice and quotation progress.. So How can I make django Model for it.. Because report has own fields, invoice and quotation has their own.. So how can i make django model for it.. I want to make dropdown or radio field for type of progress that is (report, invoice and quotation)...
oh man i tunneled so hard on jquery this approach never occurred to me, thank you so much!
although i think i still have to pass in the path from views.py, doing request.path.endswith('projects') in the template block throws an exception: Exception Value: Could not parse the remainder: '('projects')' from 'request.path.endswith('projects')'
in django how can i fulltext search with a mysql db? do i need to do a raw sql query?
i need help with css
I work with sqlite3 in dev and postgres in prod. I run queries on fields with an `__icontains' query and that works very well. However, I have chosen to veer away from full cross-DB searches, and instead focus on targeted filters/searches within tables.
You need a functional or class based view to render out the form for each template. Given that you've not shared the views.py code to highlight that, I'm wondering if you're missing that piece?
Does anyone have good recommendations for a client-side library or mechanism to play and record voice in a Django project?
how do u batch create using restframework
and if the info for the batch create is from an external api where should the fetch requests be defined
I want to create a website with django,
but I don't know what to create the website for. Is there a list of people online anywhere that want a website made for them? Because I have literally no ideas
It would have to be a made-up concept
which isn't very good, I'd rather do a real-life concept
how I solve this
sqlite3.OperationalError
sqlite3.OperationalError: no such table: posts
don't we all 😄
Table posts doesn't exist... did you create it before?, or maybe path to DB is wrong?
how should the table post look like?
this is how my folder looks like
@amber grove
your database does not have the table "posts"
If you are learning build a portfolio page for your self. That's what I'm doing as well. It's a fantastic learning experience! Also you can build a blog for your self where you can either write made up content or stuff you are actually interested in
Maybe even document your learning journey
I found what the my problem was!!
In my home/view.py I am using a TemplateView to render the page,
the TemplateViews need an explicit POST method which I did not have!!!
I had this declared in my contact form/views.py and implied it in my home/views.py.
(boy was this a lesson to remember!!! 😅 )
BTW I would not call what I did in my forms.py as logic, the get_info() method is simply just cleaning up the data. This is something I came across in the docs. Passing in there the send_mail() function from django.core just made me think at the time of writing that it will allow me to keep my views.py a bit more straight forward 🤷♂️
As I am new to Django and development in general, is this somehtig that one would label as not the best practice? Or is this a subjective thing at this point?
P.S.
Thanks for answering me, it was a massive help in finding my answer!!
could anyone tell me why my django static dir isnt working
Settings.py^
Template link^
error
STATIC_URL = os.path.join(BASE_DIR,'static')
@whole sierra shouldn't the backslashes be forward slashes?
yeah , that too
changed.
still doesnt work
@plucky wadi
@opaque rivet
i think the weirdest thing is the fact that i never changed any of this...
was working perfectly fine this morning
Hello, can anyone suggest the best deployment options for a flask production app that uses elasticsearch?
fixed.
haha, was it a forward slash missing? 😆
Dumb question, what is the cleanest way to store methods I'm using ? (for example, I'm using methods that use values in the URL to display a few things on the view, where am I supposed to store them ? I stored them in a file in the same directory than the tests.py, urls.py and so on, but I definitly feel like it's not their place
Question on Flask. Below is a piece of code in my html document.
<script>
var res = JSON.parse('{{ res | safe }}');
console.log(res.data);
</script>
How come this ^ works but when I put the middle lines inside the js file thats loaded in the html body
<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>```it does not
With error:
at JSON.parse (<anonymous>)
at index.js:34```
Does the {{}} have to be only in the html file to be accessible? If there a way to access it in the js file? Please do tag me if anyone has an explanation 😄
all that did is generate a url for that file
so it just did src='https://my-website.com/static/index.js'
you can use the include block and pair it with with context in your script tag
@warped heart What is "that" youre referring to
the js file works and loads fine, it just doesnt like {{}} where as the first snippet inside html doc does
I don't really have any ideas for what to put on my portfolio page though.
I don't understand how to get a good idea for a project. Like I would want a real life organisation to ask me to create something of use
Build an MVP clone of some software you currently use. Instagram? Look at the list of Kindling projects. Todo list. Blog. Design an API around some data set. Depend on what type of job you're going for as well.
in my Django rest framework project, I used Djoser for authentication. I customized my user model. the problem is only email and password are stored, other fields like names are not stored in my database. how can I solve it?
how can i store data in cookies using quart
Where's a good place to learn css?
did you try to use serializers.ModelSerializer?
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
yeah, not working
did you set on your settings the auth_user_model ?
class UserRegistrationSerializer(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta):
fields = '__all__'
Yeah. It’s top of my first picture
.
How do I make the serializer a form on in the browsable API? https://paste.pythondiscord.com/ibisusided.py
This is the one for class based view.
https://stackoverflow.com/a/14626971/6499765
How do I the same thing for a function based view.
Is it paid?
it is a book
I am too torn apart how to answer this question, but I guess yes, yeah.
Yeah, I feel your struggle... I have been/am struggling with getting good ideas and I have just lately understood how to go about this.
The approach that I am taking is that I do the usual projects found on Medium articles and youtube. Such as a task manager(to do list), blog, photo album etc... These give you good insight on user registration/authentication CRUD functionality, working with REST APIs and the list goes on...
Once you start seeing what you build and how to build it, you will start some ideas of your own...
The struggle is real, I know but you just have to start and pull through the first couple of tutorials. Check out realpython articles on django, there's a good one for a project portfolio. Build that up and hook it up with a free bootstrap template (that's what I'm doing right now) it will be an amazing learning experience!
Just don't rush your self, take it easy and consider the small apps as a project and sooner than you think those projects will turn in to apps of a bigger project.
Hey guys, I am trying to print out the id from a database but I am not sure why it is not coming through
Is it something that you can't print out into the api? Really new to python flask so sorry if it is a straightforward question
Should I post the code and the current output?
Hi,
I'm building an Blog App using Django and just added the comment functionality on my Posts.
An HTML page will display a Post and all the comments below it. Also, it will display a form to submit a comment on that Post.
Previously, I was fetching the comment form data and saving it to the DB and return the result with context and other things via a render() method.
Now I know when we submit forms we should not return with render but rather with HttpResponseRedirect.
Now I want to that how can I make sure that a user's comment is added on that post? When using render() I was sending a new_comment variable with my context and checking it if its None or contains something later on my template and showing comment added in green color.
Now I can't send my context via HttpResponseRedirect, how to do this after adding comment? I read online and some forum said to use message? Is there any other option? Here's my code:
def post_detail(request, year, month, day, post):
# Gets a post object if found, or return a 404 error
post = get_object_or_404(
Post,
status="published",
slug=post,
publish__year=year,
publish__month=month,
publish__day=day,
)
# Returns the list of all the active comments on a post.
comments = post.comments.filter(active=True)
if request.method == "POST":
# A comment is posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create a new comment but do not commit it to the database
new_comment = comment_form.save(commit=False)
# Assign a comment its respective post
new_comment.post = post
# Commit to the databse
new_comment.save()
return HttpResponseRedirect(
post.get_absolute_url()
)
else:
comment_form = CommentForm()
context = {
"post": post,
"comments": comments,
"comment_form": comment_form,
}
return render(request, "blog/post/detail.html", context)
Also, I tried using HttpResponseRedirect with reverse() but can't get that to work. So I used that get_absolute_url to return the url of my current post.
Version I tried:
return HttpResponseRedirect(
reverse("blog:post_detail"),
kwargs={
"year": post.publish__year,
"month": post.pubish__month,
"day": post.publish__day,
"slug": post.slug,
},
)
But this above code returned Reverse for 'post_detail' with no arguments not found.
The URL is matched but the error was there.
Please tag me if you have any clue. I'll go offline in some time.
Ping
how can i use ipc between a running python program and a website
i would like to send variables from the python program to the website
Does anyone have any experience with using QR or barcode readers with their django app?
Should I start with django and all that stuff or should I start making a static web page?
To get practice with html, css and js and then start with django or flask
Alright
hi folks, does anyone knows how to add class to django form filed in html?
for exapme when we render form
form.field_name
so here how we can provide a class name?
Question on Flask. Below is a piece of code in my html document.
<script>
var res = JSON.parse('{{ res | safe }}');
console.log(res.data);
</script>
```How come this ^ works but when I put the middle lines inside the js file thats loaded in the html body
```py
<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>```it does not, with error:
```Uncaught SyntaxError: Unexpected token { in JSON at position 1
at JSON.parse (<anonymous>)
at index.js:34```Does the {{}} have to be only in the html file to be accessible? Is there a way to access it in the js file? Please do tag me if anyone has an explanation 😄
thumbnail=models.ImageField(blank=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
desc=request.POST.get('desc')
file=request.FILES('file')
thumbnail=request.FILES['thumbnail']
author=request.user
if ValidationError:
messages.error(request,'CAN ONLY UPLOAD PDF FILES')
return render(request,'index/create.html')
entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
entry.save()
messages.success('Notes updated successfully!')
return HttpResponseRedirect('/')
return render(request,'index/notes_upload.html')```
when i click on thumbnail select button
it shows this error
code is ^^
<div class="field">
<label for="thumbnail">
Select Thumbnail
</label>
<input type="image" name="thumbnail" class="">
</div>```
Ohk coming
what's wrong with this?
What API are you querying?
the documentation doesn't match the implementation
it says it allows only PUT and OPTIONS types of requests, while you tried performing GET
Can anyone check #help-mango ?
I have a question there.
spotify
nope, i've also passed put_=True in the parameter, so its supposed to do put
Less talk, show the code
please have a look at it, it has whole code
Navigation to the spot :
Anybody by any chance experience with wagtail. I'm trying to figure out what to do to get some sort of sub-menu/hierarchical menu to work. I kinda get mixed feelings- some github issues seems to suggest they aren't supported, yet the documentation/cms make it looks like there, and I'm just puzzled by it.
Let me know if you find the issue in the code @inland oak
Why are u performing get request, even if u already made post and/or put request
spotify/util.py line 77
response = get(BASE_URL + endpoint, {}, headers=headers)```
Make your mind and use if, elif, else at least
so i'd just change it put?
get request was to fetch the base url and endpoint to make the api request
if post_:
post(BASE_URL + endpoint, headers=headers)
if put_:
put(BASE_URL + endpoint, headers=headers)
response = get(BASE_URL + endpoint, {}, headers=headers)
try:
return response.json()
except:
return {'Error': 'Issue with request'}
isnt it already there?
for put and post
and then lastly the get req
i mean using elif or else and doing this is the same thing isnt it?
if post_:
response = post(BASE_URL + endpoint, headers=headers)
elif put_:
response = put(BASE_URL + endpoint, headers=headers)
else:
response = get(BASE_URL + endpoint, {}, headers=headers)
try:
return response.json()
except:
return {'Error': 'Issue with request'}
at least this
okay let me try that
oka lemme try
if post_:
response = post(BASE_URL + endpoint, headers=headers)
elif put_:
response = put(BASE_URL + endpoint, headers=headers)
else:
response = get(BASE_URL + endpoint, {}, headers=headers)
try:
return response.json()
except Exception as e:
return {"error": str(e)}```
like this?
Nvm
U should be able to read the error from console log
If your launched server
If u did not silent the error higher
you see console.log doesnt show anything when play/pause is clicked
Check new errors ;b
The error is silenced or happens earlier then
Best practice would be writing unit tests instead of guessing where the error
or is it because of the function i wrote in the js file for the onClick?
It could be anywhere
Without tests you can search for a long time
Tests show the place of the error
okay, thankss
Try working with pytest
For back side
And check with smth like jest for front side
Just checking back should be enough to eliminate 90% of error places though
cool will do
The {{}} syntax is Jinja2 and is rendered by flask, so when you put them in a script tag(within html), it will be converted/rendered with data from flask. But when you include it in a plain js file, it is read as it is because it is not rendered by flask.
Hi,
I'm building an Blog App using Django and just added the comment functionality on my Posts.
An HTML page will display a Post and all the comments below it. Also, it will display a form to submit a comment on that Post.
Previously, I was fetching the comment form data and saving it to the DB and return the result with context and other things via a render() method.
Now I know when we submit forms we should not return with render but rather with HttpResponseRedirect.
Now I want to that how can I make sure that a user's comment is added on that post? When using render() I was sending a new_comment variable with my context and checking it if its None or contains something later on my template and showing comment added in green color.
Now I can't send my context via HttpResponseRedirect, how to do this after adding comment? I read online and some forum said to use message? Is there any other option? Here's my code:
def post_detail(request, year, month, day, post):
# Gets a post object if found, or return a 404 error
post = get_object_or_404(
Post,
status="published",
slug=post,
publish__year=year,
publish__month=month,
publish__day=day,
)
# Returns the list of all the active comments on a post.
comments = post.comments.filter(active=True)
if request.method == "POST":
# A comment is posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create a new comment but do not commit it to the database
new_comment = comment_form.save(commit=False)
# Assign a comment its respective post
new_comment.post = post
# Commit to the databse
new_comment.save()
return HttpResponseRedirect(
post.get_absolute_url()
)
else:
comment_form = CommentForm()
context = {
"post": post,
"comments": comments,
"comment_form": comment_form,
}
return render(request, "blog/post/detail.html", context)
Also, I tried using HttpResponseRedirect with reverse() but can't get that to work. So I used that get_absolute_url to return the url of my current post.
Version I tried:
return HttpResponseRedirect(
reverse("blog:post_detail"),
kwargs={
"year": post.publish__year,
"month": post.pubish__month,
"day": post.publish__day,
"slug": post.slug,
},
)
But this above code returned Reverse for 'post_detail' with no arguments not found.
The URL is matched but the error was there.
can anyone tell me wh yam i getting error 404 in terminal
i added a css file and thats not working
plzz help
any django developer here
?
OK... I just got a nosebleed cause of this lol, someone please help.
I am rendering some images from a database
title = models.CharField(max_length=50)
description = models.TextField()
technology = models.ManyToManyField('Category', related_name='projects')
link = models.URLField(blank=True)
image = models.FilePathField(path='img/')```
where the img/ is under my static directory. Like this my admin panel keeps crashing with a FileNotFound exception cause it can not seem to find the img / directory. If I change the path to static/img than admin panel works well but I get a 404 for the image cause django is looking for it in static/static/img. regardless of what I define there as path it will prefix it with static/
I had the exact same problem a week ago, and all of a sudden it was working with the img/ path. Like, everything worked. Now I added a new item to the DB and its doing the same thing again.
This is suuuper weird....
I found the same issue on stackoverflow from some months back but it has no answer. 🤷♂️
@marble spire what's the issue my dear
How would I send data from python to js script? I’m making a custom table in js and need websocket list data from py sent to js
Maybe some better way than jinja
Hi can some one help me with this error Invalid block tag on line 200: 'static'images/home_slider.jpg''. Did you forget to register or load this tag?
what library are you using
style="background-image: url({%static'images/travello.jpg'%})"
while doing this I get error
I even did {% load static%} and in setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
what library are you using
hey just wanted to ask is it legal to use someone's photo in a website who's popular such as python's founder Guido
Django 3.2.5 @native tide
channel is preoccupied rn
oh sorry
yeah
see when I use static for "{% static 'styles/bootstrap4/bootstrap.min.css'%}" this it works properly but when I use for this style="background-image: url({%static'images/travello.jpg'%})" it throws me error @native tide
this error mentions home_slider.jpg
though
not travello.jpg
?
see this error occurs for this type of lines url({%static'images/it-can-be-anything.jpg'%})"
and there are few images inside url(....)
for every image inside url when I mention static this error occurs
I did this style="background-image: url('/static/images/travello.png')" instead of this style="background-image: url({%static'images/travello.jpg'%})" and it works @native tide
u wrote {% load static %} ?
yeah I did
because the error says "Invalid block tag on line 200: 'static'images/home_slider.jpg''. Did you forget to register or load this tag?"
so you have not loaded static
I did all the things in settings.py either
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')```
@rustic narwhal but it did not worked
it worked after style="background-image: url('/static/images/travello.png')" doing this
instead of this style="background-image: url({%static'images/travello.jpg'%})"
okay
did it work ?
No @rustic narwhal
{% static 'images/travello.jpg' %} it's important you add spaces around "static". Otherwise you get an odd error like you did.
@versed lotus ok
what is zip_file?
it's invoice_zip, the second part is from a function.
I've tested with other parts of the form (which takes in an excel file) & I'm not able to functions to process as files, not file paths.
okay, yea, but what is it? ZipFile expects a path, path-like, or file-like object. what is form.invoice_zip.data then?
it's a zip file? I don't know if it's being processed by file name or as a file object.
I'm using Flask requests for this.
if it's flask, it seems to be some kind of FileStorage object. not a file-like. not sure how to use that. if it's even "file-like" and can be used like that
so I'd need to convert FileStorage to a file-like object?
maybe, I wouldn't know for sure. Never done it like that.
you can use invoice_zip.save( ... ) - see the flask docs how to securely save uploaded files
good idea. maybe then I can find out whether it's really storing as an object & not as a file name.
it depends on where you get the picture from, most people aren't gonna C&D a photo but it's smart to be safe. Photos from wikipedia are all creative commons so you could use one of those though like this: https://en.wikipedia.org/wiki/File:Guido-portrait-2014-drc.jpg - you just have to link back to it or the license
though correct attribution is often necessary
does anyone know how I can host a simple website with a single image, nothing else
this may help
Sorry, bit busy rn
ohk
can u just go through my code once and find out the error
i linked my css file but that is not working
tell me when u r free
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]```
first import os
os.path.join(BASE_DIR) this means the root where app the apps nd manage.py is there
just create static there
and put like this static here is folder name
simple and then load static and in each where u wanna load "app.js " to "{% static 'app.js' %}"
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
desc=request.POST.get('desc')
file=request.FILES('file')
thumbnail=request.FILES('thumbnail')
author=request.user
if ValidationError:
messages.error(request,'CAN ONLY UPLOAD PDF FILES')
return render(request,'index/create.html')
entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
entry.save()
messages.success('Notes updated successfully!')
return HttpResponseRedirect('/')
return render(request,'index/notes_upload.html')```
<div class="field">
<label for="thumbnail">
Select Thumbnail
</label>
<input type="image" name="thumbnail" class="">
</div>```
error iz
TypeError at /notes_upload/
'MultiValueDict' object is not callable```
@dusk portal request.files is a MultiValueDict, it's not a callable.
Access files via request.form['form_name'] instead of calling it request.form('form_name')
This is incorrect. STATICFILES_DIRS CANNOT include the STATIC_ROOT. STATIC_ROOT = where staticfiles are collected when you collectstatic.
STATICFILES_DIRS = the locations of staticfiles to be placed in the static root when you collectstatic. This cannot include the static root.
Also when you use the static tag in your jinja2 template, it has nothing to do with your static root or static dirs - that uses your static URL.
@marble spire django docs say it well:
https://docs.djangoproject.com/en/3.2/howto/static-files/
He's asking for static files
;_;
He's asking this
simple and then load static and in each where u wanna load "app.js " to "{% static 'app.js' %}"
See my whole answer
can i share my screen and can u check the code and find out the mistake
What u wanna do load the css and js files that are already in ur device ?
@dusk portal
Sure
thanks
@dusk portal cool, apart from the fact it doesn't really make sense what you're saying, the static tag uses STATIC_URL.
@marble spire Have you added a path to serve your staticfiles in urls.py?
@marble spire
let me show u guys my code
hold for a moment
i guess i did
Well, let's see some relevant code then.
Do u code at Angular too?
i am learning through a udemy course so it is a bit confusing
nope
Try docs first then Corey Schafer playlist then any other course + freecodecamp 1 video
And Django king CodingForEnterpreneur
but i iam in mid of a project in that coourse from udemy how can i leave that
which vc to join
@marble spire show relevant code, like you said?
thanks for asking
but aryan solved it
soo
it s done
👍 Good to hear
👍
Hi guys, not sure if this is a python issue or html, trying to pass a dictionary to HTML, but when I try to pass it with {{ stashData | tojson | safe }} I just get null, any thoughts pls?
Is there some way to differentiate between a string and a list in Jinja
I have some entries that are strings and others that are lists of strings and, to my knowledge, jinja doesnt have a way to do type checking.
flask or django
React 🙂 👍
@versed lotus are you able to dm me
flask
Depends 🙂
Flask got me off to a great start. Been working solely in Django for 2 months.
How complex is the web project?
I'm trying to use bs4 to scrape from indeed, base on the job offer, i want to scrape the detail of the job, but the link id are based on the job_id, so is there a way for me to solve it?
Does indeed have a public api you can use instead?
Django help
So my app is being served over HTTPS and everything is verified works as it should.
using the deployment check, I got a warning about SECURE_HSTS_SECONDS. As a person that's kinda new to all this (although I made sure my site never serves expired certificates with certbot auto renewal) what should I set this to?
Guys I want to deploy a A* Visualized python application and I will be using flask
However for making the a* Visualiser the Tutorial I'm referring uses pygame
So either I have to use some other library , or find a way to integrate pygame into flask ,which from what I read is not possible
I am trying to make a web site that can run opencv python code I got 5 projects the website is nothing fance just want it to have a "how it works" page and then the main page were they are asked to pick from one of the 5 projects
this is for me
cause I want to make my opencv projects run on my phone
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
desc=request.POST.get('desc')
file=request.FILES['file']
thumbnail=request.FILES['thumbnail']
author=request.user
if ValidationError:
messages.error(request,'CAN ONLY UPLOAD PDF FILES')
return render(request,'index/create.html')
entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
entry.save()
messages.success('Notes updated successfully!')
return HttpResponseRedirect('/')
return render(request,'index/notes_upload.html')```
MultiValueDictKeyError at /notes_upload/
'thumbnail'``` still
no error is coming in file
it's coming in thumbnail
thumbnail=request.FILES['thumbnail'] i think your error is here, it doesn't recognize thumbnail as a key
how can I make this into a list going down insted of sideways html <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> DOCUMENT SCANNER </button> <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> ANGLE FINDER </button> <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> QR READER </button> <button style="background-color:red; border-color:blue; color:white";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> FINDING DISTANCE </button> <button style="background-color:red; border-color:blue; color:white";align-items:"center";margin-left:auto; margin-right:auto;display:block;margin-top:5%;margin-bottom:0%"> AUGMENTED REALITY </button>
Use break<br> after your buttons
How do I make a form from the serializers field using api_view(Fbv) on the browsable API page
Hi, anybody using FastAPI?
I have a test server running, now I want to implement a "shutdown" API, when the server receives this API, it should quit the execution (i.e. process exit), is this possible?
@dusk portal that is an error coming from your files, because the only time you mention thumbnail is accessing the files.
I'd debug the view to see if it's actually receiving the file data. Note that your request containing file data must have the content type multipart/formdata
Ohh
So what should i do
Ig Problem isnt in my view
Or model as when I'm doing same thing from admin panel it's working
Problem is in the html
Yes I saw that
Yes I'm 101% I have that
I would check the view to see what files it's receiving.
@opaque rivet Hey bud I need help once more
How to make a Http request to the backend, I mean I am using a api to transfer some dataa from dashboard but whenever the data is uploaded in the api how can will my backend know that some data has been uploaded?
How can I troubleshoot why is my Django API's response time awful when doing authentication? I've got a simple endpoint for testing that goes like:
@api_view(["GET"])
@authentication_classes([BasicAuthentication, SessionAuthentication])
@permission_classes([IsAuthenticated])
def test(request):
if request.method == "GET":
data = {"user": request.user}
return JsonResponse(
data=data,
status=200,
json_dumps_params={
"default": str,
"ensure_ascii": False,
"indent": 2,
}
)
I'm getting ~50 ms response time when commenting out the authentication classes, but 1.5 - 2.5 sec when I'm using authentication. The DB has a response time of around 25 ms from where I run the web server (locally for now)
I would suggest to use flexbox or grid. Using <br> tag is not best practice.
How can I get a value from my html to my python script
@velvet yew simply because the authentication class adds extra middleware. 50ms is good.
@mystic vortex I don't know what you're trying to ask. Do you want to log your API requests?
50 ms is good but 2.5 sec isn't, I need to use authentication on the endpoints
Oh I misread!
@velvet yew does removing BasicAuthentication class help anyhow? I don't see you using that anyway.
Because your request will go through that middleware first before session auth.
Oh let me try I just added it because the guide said so
It does make is fast but then I can't authenticate anymore
And I get {'detail': 'Authentication credentials were not provided.'}
So I guess it's fast because it fails lol
Hi. How can I make sure Search engines don’t list my admin panel?
Robots.txt is a bad idea, because then the hidden url is exposed
put basic_auth with nginx at it
or even restrict access with ip white list
at nginx or iptables level
you can forbid exact urls beginning in both cases
I … did not know all this
why am i keep having json { "detail": "Method \"GET\" not allowed." } whenever i use postman to create a product
have you tried reading the error
you need to make highly likely POST request
^
GET requests can't upload json data
do you know the difference between GET and POST?
if you don't, this would be a really good time to learn
So this question just popped up to mind
Will this work with Django?
Just realized I didn’t mention django admin panel to begin with
yes
it will work almost literally with everything
if we have nginx in reverse proxy mod
@velvet yew hmm, so which method are you using to authenticate? Basic auth?
I am actually using django too
and that's how I covered django admin panel
I think so, I'm just doing auth=(username, password) in requests so whatever that uses, plus what I had in the function
hey guys
hellp me
I want to place google map below the discord username how should I do??
?
CSS FLEX BOX
Hey @swift glen!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
@sharp breachhttps://code2care.org/pages/how-to-place-two-div-elements-next-to-each-other#:~:text=If%20you%20want%20to%20place,use%20a%20CSS%20property%20float.&text=As%20the%20name%20goes%20the,left%20w.r.t%20to%20its%20container
goodevening guys. I've been stuck for a week trying to send a simple email using python django and angular as a front end. stackoverflow had no clear answer for this. any idea how to do it guys?. here's my own code btw
:incoming_envelope: :ok_hand: applied mute to @swift glen until <t:1631539093:f> (9 minutes and 59 seconds) (reason: attachments rule: sent 8 attachments in 10s).
!unmute 715204879857090681
:incoming_envelope: :ok_hand: pardoned infraction mute for @swift glen.
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
bro
its not working
<div class="mapouter"><div class="gmap_canvas"><iframe width="511" height="277" id="gmap_canvas" src="https://maps.google.com/maps?q=2880%20Broadway,%20New%20York&t=&z=13&ie=UTF8&iwloc=&output=embed" frameborder="0" scrolling="no"
marginheight="0" marginwidth="0"></iframe><a href="https://123movies-to.org">123movies</a><br><style>.mapouter{position:relative;text-align:right;float:right; height:277px;width:511px;}</style><a href="https://www.embedgooglemap.net">google map api for website</a><style>.gmap_canvas {overflow:hidden;background:none!important;height:277px;width:511px;}</style></div></div>
</div>```
look at line 5
I have added
float right
and also tried to do it in css.map_wrapper{ float: right; }
@swift glen
what should I do??
student table
->Name
->rollno pk
->age
->school Foreign key of school table
School table
->Name:zzz
->id:101
->“location:paris
->branch:c15
student
{
“name”: “Abc”,
“rollno”:12,
“age”:14,
“school”:{“Name”:”zzz”,
“id”:101,
“location”:”paris”,
“branch”:”c15”
}
}
how can i get the output like above json output, like to create a dictionary output for foreign key linked table
in Django
like school table dictionary in above output
i have no idea, 😆 im kinda stuck on my own problem as well haha
Anyone?
How would you allow moderators to access the admin panel if it's blocked via nginx?
Especially if you can't allow just certain IPs.
That's really vague. What do you mean exactly? To get that output, you just create a dict with that data. What specifically are you trying to do.
You can create a serializer, if that's what you're wondering?
To convert an object to JSON.
yes , but i need to get foreign key table details for specific field
i.e in that output ,student field got every detail from school record
fetch student school record from School table as result for that field
guys is there like a front end framework for python?
like, html but python based
I'm learning django atm, and there's mostly backend stuff
and some html for frontend
maybe there's something like GrapesJS but for python yk
Since front-end is usually in javascript, there's not really a python front-end framework.
Even if there is one I expect it would be a very hacky way to do things.
f alr
Basic auth as most simpliest method
it will appear in advance before the admin panel, moderators only will need to write correct password, before they access admin panel where they will properly authentificate as second step
whilisting ip is required for more... thorough defense
we could white list all ips from our company network
in one line/rule
something like....
Allow 165.65.0.1/16, if I wrote it correctly
will allow all ip addresses from 165.65.0.1 to 165.65.255.255 range
or actually even better.
we could allow only access to servers, from computers which have enabled our private company VPN 😉
which could connect only from company network ;b
@inland oak you opened my mind through this.
any ssas or opensource tool to get this done ?
I am using open source OpenVPN, it comes even pre installed into my Ubuntu
https://opensource.com/article/18/8/open-source-tools-vpn
a bit of eyeing wireguard, tried that before. rumours say it has 20 times less overbloaten code
awesome i heard about it before getting into coding, great stuff
https://www.cyberciti.biz/faq/ubuntu-20-04-lts-set-up-openvpn-server-in-5-minutes/
here is a simple instruction how to setup it in 5 minutes
a bit of silly instruction tbh, since it is using shell language for all of it to run
bit at least it is user friendly
thanks buddy
how do i update a part of the html without refreshing the page? do i need a api that send a json with data that i want and then js magic to update the html?
hi. anyone available to point me to a direction for a django project? just general question, no code help.
more like.. a conceptual question.
Is there a way the image doesn't separate the paragraph and the h1? I moved the image to the right with margin-left
Like that
i had a prob
class Students(db.Model,UserMixin):
id=db.Column(db.Integer(),primary_key=True)
fullname=db.Column(db.String(50),unique=True,nullable=False)
email=db.Column(db.String,unique=True,nullable=False)
personal_email=db.Column(db.String,unique=True)
password=db.Column(db.String(),unique=True,nullable=False)
dialling_num=db.Column(db.String(),unique=True)
branch=db.Column(db.String())
occupation=db.Column(db.String())
company_name=db.Column(db.String())
linkedin=db.Column(db.String())
github=db.Column(db.String())
website=db.Column(db.String())
def __init__(self,fullname,email,personal_email,password,dialling_num,branch,occupation,company_name,linkedin,github,website):
self.fullname=fullname
self.email=email
self.personal_email=personal_email
self.password=password
self.dialling_num=dialling_num
self.branch=branch
self.occupation=occupation
self.company_name=company_name
self.linkedin=linkedin
self.github=github
self.website=website
and later on when i was adding people into the database so they can be recognized by the platform, i added none on the last 4 company linkedin github and website cuz there are info that the user will add in and not us
but when i went to the platform and did wanna do some updates it didn't update a thing
here's some dummy data that i wanna update
as you can see it didn' tupdate the branch and occupation
please anyone knows why
https://pastecord.com/isehuqiwij.sql i had an issue before this tho
i was adding users to the table and for the stuff that should be added by them i left it blank for instance
company_name=""
There are at least three ways to do this that I am aware of:
- AJAX. I've not personally worked with AJAX, but it has been around for a number of years.
- JS: This is definitely a candidate for managing page behaviour. I'm getting ready to work with JS, researching a Framework currently. However, so far I've used the following...
- HTMX: I've been working with this tech recently. It only has a couple of lines to call the JS script (just as you would for a css framework such as bootstrap/tailwinds). You can then invoke all sorts of tricks to update partial pages. The documentation is solid. I'm using it in a couple of instances in a Django web application to amazing effect. There is no script overhead that I can observe, and it results in really fast DB updates. In short, I'm astonished at how effective HTMX is. If you want to see it in action DM me.
Whatever the case, both the above methods can be researched to deliver what I believe you are looking for.
AJAX is just a fancy acronym for 'asynchronous HTTP requests'
How can I access an ng-input combobox with its dropdown values inside a ng-select listbox?
I'm using selenium webdriver
Or do you need the whole dom structure to tell?
its an angular based website
its a dropdown menu
is there something like django-q, but for flask? (ie. pip installable, all python)
rabbitmq uses erlang, which isn't an option. needs to be python
Redis is in C at least... why does it have to be written in python?
I'm running it on pythonanywhere, which is limited
Limited how?
I think you can use redis as a broker for django-q
as in it has to be python :)
I see. Are you using the free tier? You an get a linux server for $5/month on DigitalOcean. Having those kind of limitations seems like a huge PIA.
I sent you my referral link, you get $100 to start with if you sign up with it
Anyone able to help me with my website?
For some reason my website doesn't change the grid item width for when its less than or equal to 574px, it works for the 768px one. Don't really know why.
@media(max-width: 574px){
.toggle-button{
display: initial;
}
.collapse{
max-height: 0;
overflow:hidden;
transition: all 0.7s cubic-bezier( .42, 0, .58, 1 );
}
.collapse .nav-link{
display: block;
text-align:center;
}
.search-box{
border-right:none;
}
.grid .grid-item{
width: calc(100% - 18px);
}
}
@media(max-width: 768px){
.grid .grid-item{
width: calc(50% - 18px);
}
}
What help u need
Im also a beginner i cant help sry

no worries i figured it out
title=models.CharField(max_length=60,blank=False,null=False)
subject=models.CharField(max_length=50)
desc=models.TextField(blank=True)
thumbnail=models.ImageField(blank=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
file=models.FileField(blank=False,null=False,upload_to='Notes',validators=[FileExtensionValidator(allowed_extensions=['pdf','doc','docx'])])
author=models.ForeignKey(User,on_delete=models.CASCADE)
published_on=models.DateTimeField(auto_now_add=True)
<main id="upload">
<div class="title">
Upload Notes
</div>
<div class="error">
error messege here
</div>
<form method="POST" enctype="multipart/form-data" >
{% csrf_token %}
<div class="field">
<label for="title">
Title
</label>
<input type="text" name="title" placeholder="video's title" required name="title">
</div>
<div class="field">
<label for="description">
Description
</label>
<textarea name="description" name="desc" id="" cols="30" rows="10"></textarea>
</div>
<div class="field">
<label for="video">
Upload Notes
</label>
<input type="file" required name="file" accept="pdf/doc,docx" name="Video" class="">
</div>
<div class="field">
<label for="thumbnail">
Select Thumbnail
</label>
<input type="image" name="thumbnail" class="">
</div>
<br>
<button class="submit">Upload</button>
</form>
</main>```
heyo, anyone know if there's an easy way to use the height of an element for another setting in that element?
dunno how to word this really, but my use case is using the height of the element as the margin.
I'd be happy to elaborate if needed
A css variable is probably the easiest way
yeah I just decided to do it in js
cuz I'd have to use js to set the css variable anyways
for my use case
heya
im sending a request to a site, and im currently using a session (requests.Session()), and im assigning it headers
however when i print the headers, its not printing the ones i assigned it
as i say that it works 
I dunno if this is the right place but is there anything unique about Firefox Developer Edition?
And if it's worth installing or should I just stick with regular Firefox
👍
okay, different issue
now my django admin page is not found
@inland oak
less talk, more code ;b
we can't help if we can't see your code
location /admin_url {
auth_basic "Restricted territory by website owner";
auth_basic_user_file /etc/apache2/.htpasswd;
}
the password works and all
a bit more full config file
so, no problem already? or still having a problem?
there's gonna have to be a lot filtered out, but okay
the auth side works, but now I get a 404 after
use code highlighter
nginx
server {
server_name [removed];
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/django/projectfolder;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
location /admin_url/ {
auth_basic "Restricted territory by website owner";
auth_basic_user_file /etc/apache2/.htpasswd;
}
well, that's most of it
the rest is just certbot stuff
server {
server_name [removed];
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/django/projectfolder;
}
location /admin_url/ {
auth_basic "Restricted territory by website owner";
auth_basic_user_file /etc/apache2/.htpasswd;
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
how about having this
okay, now I got my admin page back
still gotta test that message though
yeah either it's not showing, or it's my browser
you can't insert correct username/password?
oh I can
it is not accepting them?
it is
it's the message I'm inda worried about
well that's interesting, it shows on my iPad
I'm gonna guess because of cache
why are you worried about the message
yeah, test with freshly reopened incognito browser
clean from cache by default
well it ain't showing there either, but whatever
I know it at least works
I kinda feel like combining it with specific IP access, but my IP is dynamic and I'm not always home
so that... nah
well, thanks man
u a welcome
now, I don't have to worry for a while
that's basically everything I needed to take care of
just in case, you can allow pass with IP or password being right
location / {
satisfy any;
allow 217.115.32/24;
allow 127.0.0.1;
deny all;
auth_basic "You shall not pass!";
auth_basic_user_file /etc/nginx/htpasswd;
}
in this way
satisfy any; makes allowing if at least one of the rules were pased
mhm, lol
noted!
this project took longer than I wanted it to, but at least I didn't rush and possibly make an error (I made sure I didn't)
I have a project I am working on already a year %
now I'm kinda "burnt out" from it for a while, so I'm just gonna leave it running for a bit before I start making the changes
a year? oh boy
mine took a few months on and off
yeah, it is a bit big one.
more off than on tbh
it is meant for infrastructure of 200+ servers at minimum
and at the same time they hired just one developer
for everything 😐
I am not picky I guess while I am just learning stuff
oh god
that's a lot for one person
I was just creating my website
yeah that's a lot (maybe too much)
it is a good learning experience at least
learning, learning, applying at practice, applying at practice
I need to colour my background white and then make my words light pink
I have tried the background element but it didnt work
Hey @wraith topaz!
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:
Code?
cant past it its too long
but
this is a update
error
if I add thishtml <section style="background-color: black; padding-top: 114.375px;" data-test="page-section" data-section-theme="light" class="page-section to my section which for me I think is the whole background and run it it does nothing
thats just one part of the section
there is only one section
@glacial moat
NVM I GOT IT YES
Hey @thin lance!
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:
Hello, I need help in django conform delete
what i want to do is show the user the option "yes" or "no" when deleting a contact
- yes = delete contact
- no = return to contact list - i know there is this back option (window.history.go(-1);)
my template conform_delete.html:
<div class="form" style="text-align: center;">
<h2>Are you sure you want to delete the "<b>{{ obj.name }}</b>" contact?</h2>
<!-- <form action="/api/contact-list/" method="POST" novalidate class="test">
{% csrf_token %}
<br><a href="{% url 'contact-list' %}"><input class="btn btn-success" id="yes" name="yes" type="submit" value="Yes"></a>
</form> -->
<a href="{% url 'contact-list' %}"><input class="btn btn-success" id="yes" name="yes" type="submit" value="Yes"></a>
</div>
my views.py:
class DeleteContact(DeleteView):
model = AdressEntery
context_object_name = "obj"
template_name = "main/adressentery_confirm_delete.html"
success_url = reverse_lazy("contact-list") # this is redirected to a specific url for the parameter using the name expressed in urls .py
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)
return super(DeleteContact, self).dispatch(request) #dispatch method will override the second method and allow us to do redirection
#return redirect('/api/contact-list/') #render(request, self.template_name, {})
def get_queryset(self, *args, **kwargs):
queryset = super(DeleteContact, self).get_queryset()
queryset.filter(id=self.kwargs['pk']).update(active=False)
return queryset # filter by clicked contact card get id and set active false
note: I don't want to delete my object, I set the flag acticve = false.
If I put a button in the form, the contact object in the database is deleted,
but without the form just by clicking on the previous delete link leading to conform_delete, my contact is instantly set to active = false so this button only does redirection.
where are you setting flag to false?
is get_queryset even called?
i dont think it would be
in my model there is a field "active" if it is false I do not show contacts
this line queryset.filter(id=self.kwargs['pk']).update(active=False)
Hi, I need a bit of help. I have a model, that contains a FilePathField(path='img/') for which the path should be static/img/
though in this form my admin page raises a FileNotFound exception. If I change path to static/img/ than admin page works fine but, django keeps looking for file in static/static/img/
I am not sure why this keeps happening. I found this question being asked on django forum and stackOverflow but they have no answers...
Delete View doesn't call get query set method at all.
The file would be uploaded to MEDIA_ROOT setting.
Set it to "static"
Though i would advise against it since the static folder is not for user uploaded content
how am I supposed to do this?
It should be FileField(upload_to='static') not path
this won't be something that's uploaded by users. These will be images served by my website for each project. I figured to use this way so that I don't have to hard code images to my HTML
i need help
is this a good way of doing it?
someone help plz
from flask import Flask, jsonify, render_template
from threading import Thread
app = Flask(__name__)
@app.route('/')
def home():
return render_template("main.html")
@app.route("/dashboard")
def dashboard():
demo = "discord"
return render_template("dashboard.html", demo = demo)
def run():
app.run(host='0.0.0.0',port=1)
def keep_alive():
t = Thread(target=run)
t.start()
if __name__ == "__main__":
app.run(debug = True)
keep_alive()
this is not starting the web server with 0.0.0.0 host
whats the error
no error
its just not starting
making the server with a different host
127.0.0.1:5000
Sorry whats happening when you do 127.0.0.1:5000
but its making with 127.0.0.0:5000
0.0.0.0 is not a host. Its a network
I'll check and run your code.
I have some info callback in the GET request on my localhost, but whenever i try to do request.GET to get the results of the info callback, I get Attribute error, object has no attribute GET
how can I get that info?
Why are you doing threading like this?
i fixed it
@raw compass
sry for ping but need help
i want to run in 0.0.0.0 but its not running in it
you still need to put in 127.0.0.1 in the browser
or get your IP address and that should work on your network as well (depending on firewall)
i am trying to make it 0.0.0.0 but its not working in anyway
if __name__ == "__main__":
app.run(debug = True, host='0.0.0.0',port=random.randint(2000, 50000))
@raw compass is it correct
if __name__ == "__main__":
run()
what??
wdym?
you have made a run function and you were not using it
well i have made one
thats why in your most recent example you needed to change it.
Yes your most recent example makes sense
Though you may as well delete your def run(): function
not working till now @raw compass
still not 0.0.0.0
from flask import Flask, jsonify, render_template
from threading import Thread
import random
app = Flask(__name__)
@app.route('/')
def home():
return render_template("main.html")
@app.route("/dashboard")
def dashboard():
demo = "discord"
return render_template("dashboard.html", demo = demo)
def run():
app.run(host='0.0.0.0', port=random.randint(2000, 50000))
if __name__ == "__main__":
run()
its still not 0.0.0.0
0.0.0.0 means the program accepts connections for all IPs it can handle
As opposed to specifying the ip
yea i want that
But 0.0.0.0 is still not a valid ip
how can i get that '
You need to use either local host or 127.0.0.1
(In your browser or whatever you’re using)
but how can i make 0.0.0.0
When I run your code
python discord_flask_wildcard.py
\ * Serving Flask app 'discord_flask_wildcard' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://192.168.0.4:31186/ (Press CTRL+C to quit)
So if you have 0.0.0.0 in you config the program will accept connections for all ips the pc has
how can i do that/
That is usually local host (127.0.0.1) and all ips that are assigned
i want to make it like all the users will be able to connect
cause i am making a bot dashboard
Yes that means you need an IP address that is reachable from the internet
maybe, i want it like it will accept any request
Then you specify 0.0.0.0 in your config and the program will accept all connections regardless of the ip used to connect to the program
but how to do that
i am new to web dec
dev
i just started a day ago
So let’s say your server has access to 2.3.4.5
ok
That means that traffic for that ip is sent to your server
Then the program will accept connections if users use that ip to connect
wdym?
i am trying to make it accept all requests but no its not accepting
its only accepting from me
What ip are you using to connect?
@echo summit ^
ok, so where are you running the porgram?
My production server uses gunicorn where can I see print statements???
what command are you using to run gunicorn
but by default gunicorn doesnt print or log print statements
Hey there, wanted to quickly ask if I (via django for-loops) generate Id's for Div elements. I can not target them via css/scss right? I have to do it via JS ?
why do you want to do that in the first place
ids and classes are mainly there to identify their css style
if you want a unique id for targeting them in js code you can add an additional id or class
I want to change the color of some of them. Because some of them have different backgrounds so in order for them to be readable nicely, they need to have different text colors.
Like if you see here, the second one is very badly readable. So I want to change the text color of it.
Everything is loaded from a Database. So the image always stays the same.
then why bother generating ids
just make two ids and style them independently
or make a general style and then add an inline style like this:
<h1 style="color:blue;">A Blue Heading</h1>```
The id's are generated automatically because there is a for loop that is generating the elemente.
i can not add inline styling
That's the code that generates these two images (cause there is only two right now).
then you could add the colour you want to the portfolio object and add that to the repeating template
Yes that works changing it on all of them. But I would like to only do that to some of them. If that's not an option then I guess I find a different colour or background to make it work. Maybe the easier solution here.
you could do a default color
like py {{portfolio.colour if portfolio.colour else "#fff"}}
that means that if the colour is set it uses that colour else it uses the default
ahh I see. that could be helpfull. Thank you ❤️
hi there I am using django LoginView to login a user and on invalid credential it is not showing any error
np
i tried
{% if messages %}
{% for message in messages%}
{{ message }}
{%endfor%}
{%endif%}
but its not working
is that the whole template?
no i am using default and login
can you show the whole file/template?
sending
this is default
login template
views using built in LoginView
so the for loops and if blocks do nothing because they're not valid html
they will just add the text to the html but it will just be ignored
so how i show the errors here if users credentials are invalid
Hey, I want to store the _Rolename in a separate variable as a property (string) then what should I do ?
class Roles(models.Model):
_RoleName = models.CharField(max_length=80)
@property
def RoleName(self):
return self._Rolename # Is this correct?
not that sure how django does this, but maybe someone else can handle that
Anyone ?😅 just started django 4 days ago
in your template you do this.
And then in your views you will need to add a message object. Like this for example.
Now in my template the message "your profile has been updated" will appear.
I can't use this I am using built in views
you can extend build in views.
how ?
https://dev.to/nuh/django-loginview-and-flash-messages-4k9k This explains it very well. I also followed this.
Thank you I just found the problem but I will look it as well
I am using my own forms so they dont have that functionality to show errors
thats why I am not seeing errors
ah but you can just ask is form valid normally if it builds on a default form. If not then ye you gotta build that in.
yeah
but I'm sure you find something. Django has lots of answers
I am trying to handle email confirmations and I keep getting this error in flask-mail
Anyone knows a way I could fix this? Perhaps I am missing something?
Thanks
@login_required
@cache_page(60*2)
def notes_upload(request):
if request.method=='POST':
title=request.POST.get('title')
desc=request.POST.get('desc')
file=request.FILES['file']
thumbnail=request.POST.get('thumbnail')
author=request.user
if ValidationError:
messages.error(request,'CAN ONLY UPLOAD PDF FILES')
return render(request,'index/notes_upload.html')
entry=Notes(title=title,desc=desc,file=file,thumbnail=thumbnail,author=author,published_on=datetime.now())
entry.save()
messages.success('Notes updated successfully!')
return HttpResponseRedirect('/')
return render(request,'index/notes_upload.html')``` this is my code which integrates and send post request from the frontend side
class Notes(models.Model):
title=models.CharField(max_length=60,blank=False,null=False)
subject=models.CharField(max_length=50)
desc=models.TextField(blank=True)
thumbnail=models.ImageField(blank=True,default='default_notes.jpeg',upload_to='thumbnail_notes',validators=[validate_image_file_extension])
file=models.FileField(blank=False,null=False,upload_to='Notes',validators=[FileExtensionValidator(allowed_extensions=['pdf','doc','docx'])])
author=models.ForeignKey(User,on_delete=models.CASCADE)
published_on=models.DateTimeField(auto_now_add=True)
this is my model
so when im filling the form it's like raising error that i provided in Validation error message
after filling the form
im choosing .pdf file
then too
anyone wanna make a website together?
what kind of website?
Can anyone tell me why this doesn't auto download when I click the button? In both Firefox and Chrome, nothing happens. This is a valid FTP link and I want to be able to click the button and it auto download, which is what I read the download tag is for. Is something wrong here?
<a class="btn btn-info btn-sm" download href="ftp://myuser:password@hostname/path/to/file/File.zip"></a>Click to Download</a>
Hi some one please help me with is I am trying to use and I'm using Django redirect when I am at http://127.0.0.1:8000/travello/accounts/register/ return redirect('travello/') but it is redirecting to http://127.0.0.1:8000/travello/accounts/register/travello/ but I want it to redirect to http://127.0.0.1:8000/travello
have you tried it with /travello ?
👍
Any good free mailing service which I can use for my django web app?
I tried mailgun but it asks for company information
Use flask for python web development
:incoming_envelope: :ok_hand: applied mute to @mild marsh until <t:1631637932:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
scroll to where error is
aka red text
send screenshot
so it cant find the template
lets try to figure out why
is your html file named exactly index.html
and is in templates
its not in templates
templates is a folder
create that folder in your project dir and put the html file in there
it will be fixed
send screenshot of files again
yeah
would help
@native tide actually just send entire project folder
it could be the placement of files or the code itself
i need it all
Hey @native tide!
It looks like you tried to attach file type(s) that we do not allow (.zip). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
Anyone know if it’s possible to build an iOS app with a Python/FastAPI backend? Haven’t been able to find any documentation on this particular implementation
For sure
Just use a front-end framework like React Native
and fetch from an API built on whatever you want to use
What kind of
Don't write templates/ inside render templates it identifies that itself bruh
How many concurrent requests(requests per second) can a Nginx server handle with specifications 1vcpu and 2gb ram and using Ubuntu 16
I followed the following link to deploy my django website,
Which is best to use for django views, def example(request) or def example(response),?
Started learning django a few days ago
What r u saying lol
Response is like return but in rest Framework
;_;
And and yes in both the parameter is request
Example
def babe(request):
return render(request,"babe.html")```
from rest_framework.response import Response
def babe(request):
return Response("babe")
Or JSONRESPONSE
We won't use html here as it is given my django
And Functionality
Noted, Thank you
Yes
Take ur time
First CleverProgrammer 8 hrs video on which he covers docs
U should take 1 week to do that if u code 6 hrs a day
Cez u urself have to code as he copy from docs + read the docs
Then Corey Schafer playlist
And remember
3 gods of django
JUSTDJANGO
CODINGFORENTERPRENEUR
DENNIS IVY
They mostly post django
Kind of obsessed as I am too
basically the user sends a http request to the server and the server sends a response to the user, in short this is what happens, yes?
and thank you will look at those definitely
U r somehow right and wrong but I won't correct u
I will let u explore and find it on ur own
Pro tip do not learn from any 1 learn from all to be a master
Practice alot
hello there fellows, i am working on a model for students to login to a certain platform, so am i going right with the model yet? i mean i am using AbstractBaseUser as following
https://paste.pythondiscord.com/xojimaciso.py
What do you mean by going right?
am i making a correct model for my usage now, i mean i m really beginner with django and used to go with the django auth and not making a model for the user
@dusk portal I dabbled a bit with game dev using Godot last year, but I feel web dev is best field to get into at the moment, did my basic overview of the different developer fields at college this year. But I find backend web dev very interesting, that's the path I would like to go, hence why I started learning django.
Looks fine. There's a good page for creating your own user model...
Make sure you include your custom user model in your first migration.
thank you sir
sir please, so i am not forced to use from django.contrib.auth.models import AbstractBaseUser, BaseUserManager?
Ohh cool
I'm looking to learn how to use bootstrap, and maybe pickup react afterwards, while trying to build projects on my own with django to learn it.
@dusk portal are you working in the backend or are you full stack?
I hate frontend but I handle till some end idk js ,scss and one page technologies
Mainly Backend
Api
Nd the DevOps part too (learning)
oh ok that's cool with backend what do you work with on the daily? I'm curious and interested to learning more about the backend.(To know what to learn next)
Anybody know how to link a django site to a physical robot on the same network using either sockets or http or something else. If you could help that would be great
What's the purpose? Send commands from the site to the robot?
how can I move my img to the top right conner of my header
i tried this align="right"but it not working it only moves it a lit bit
yes, do you have any experience using sockets with django. if so, any help would be hugely appreciated
fundamentally, you're just sending data to an IP address
I'm assuming the robot has a working client
or server?
anyway, one needs to initiate a connection to the other
I have the client code written I just dont know how to make the view
what are you using?
django-channels?
I haven't used channels before, only socket
🥴
like
the Python stdlib socket library?
do the server and robot need to talk to each other?
or one way only?
For right now only the websit needs to talk to the robot
and will that change later?
Maybe, but for now lets just go with tihs
What was your question about socket?
I'm trying to pass data from my app.py in flask to a server-side application that has a googlemaps api
My issue is the data isn't being passed from flask to my serverside and results in a webpage error. But when I try to acesss the page from my flask application it returns the correct json data.
Here is the code for my app.yp
from flask_cors import CORS
from flask import Flask, jsonify
from processdata import processdata
app = Flask(__name__)
CORS(app)
@app.route('/displaylocations/')
def displaylocations():
l = processdata()
return jsonify(l)
if __name__ == '__main__':
app.run(host = "127.0.0.1", port = 5002)
I basically copied this with a few adjustments for the rest:
Someone can assist me, I can't do that show me the hostname when I want to read a file url since other view with Django. Without the host I can't read the file with pandas
Hello, I'm getting a non field error in django but when I checked the request payload in the network tab the credentials are correct
Anyone who want to help me in django.. I have asked a quetion in pie chats..
i am trying to deploy a django app to heroku
-----> Building on the Heroku-20 stack
-----> Determining which buildpack to use for this app
-----> Python app detected
-----> Using Python version specified in runtime.txt
! Requested runtime (python 3.8.12) is not available for this stack (heroku-20).
! Aborting. More info: https://devcenter.heroku.com/articles/python-support
! Push rejected, failed to compile Python app.
! Push failed
but clearly
3.8.12 is a supported version
the app runs locally without any issue
So i am using django. and i have following model
class Collection(models.Model):
title = models.CharField(max_length=10)
class Item(models.Model):
collection = models.ForeignKey(Collection)
object_id = models.UUIDField()
seq = models.PositiveSmallIntegerField()
from the frontend Item can be drag&dropped to change its seq value. Hence i need to update the seq value. If seq value is duplicated, i have to add 1 to the previous one and place the new one instead. I am thinking collecting all the items and updating each one but is there any other optimal way to achieve this?
Any good docs to learn django forms
i have setup redis broker for celery and i want to use redis db for recommendations as well, is there a configuration i need to do to prevent conficts?
nothing is better than it's official https://docs.djangoproject.com/en/3.2/topics/forms/
from flask import Flask, request
App = Flask(__name__)
@App.route('/')
def HomePage():
return '''
<form method = "POST" action = "/create" enctype = "multipart/form-data>
<input type = "text" name = "longurl">
<input type = "sumbit">
</form>
'''
@App.route('/create', methods = ['POST'])
def Create():
print(request.form.get('longurl'))
return 'Done'
if __name__ == '__main__':
App.run(host = '0.0.0.0', debug = True)```
its keep printing `None`, how i can get text from input form?
Hi can some one help me to understand what is the use of reverse() in Django, I tried to understand but I'm unable to Thank you
How can I setup HTTP server that just prints out every request info?
If you're on Windows:
py -m http.server
Run this in a folder with presumably static website files like index.html and whatever
Does it print out requests?
Well I'm just gonna give it try
Damn it works
thanks a lot
Ik this a dumb question but i dont understand how input labels work in html
hm?
what about them
I don't get why they can be used without nesting in input element
ah
you mean in conjunction with for?
like <label for...>
Yep
honestly
that's just a HTML thing
I don't think there's any explanation other than historical accident
Ohh, thanks
HTML has evolved a lot from a long time ago
at the same time, backwards compatibility is a thing
so I wouldn't worry so much about it
Ah, I see
in django I am storing some images for my portfolio projects in
model.FilePathField(path='/img') and this makes my admin panel crash with a FileNotFound exception cause of the /img dir.
Project photos do not load cause django is looking for them in /static/static/img instead of static/img.
If I change the path attribute to model.FilePathField(path='static/img') admin page works but I still get a 404 cause django is looking for files in static/static or static/home...
Someone please give me a hand cause this is the only thing holding me back from deploying my portfolio page. And its been bugging me for weeks by now...
I truly have no idea which constant in the settings.py is prefixing the path with static. I have played around with a multitude of things

