#web-development
2 messages · Page 132 of 1
all gonna be the same speed rendering wise though 
i recommend flask before django. I am learning and using flask@lilac belfry
but it's all up to you
I already know django and flask. I just want to start a new project and wanted to know the best package to use before I spend ages using one to find out another is better
then it's fine
at the end of the function
return redirect("url")
if you have the url named after something then its even better
for instance
path("", mainPage, name="index")
Then the "url" would be "index"
is it possible to put an alert box under 'Name' and 'Email' and 'Password' by using 3 different divs? (Boostrap)
yep, do it with flask flashing
using jinja2 expressions you can check if there is a flash message, and based on a parameter like "type: name or type: password" you can show that alert where you want to show it
i don't know jinja2, i am just learning flask
flask templates use jinja2
ohh i see
also if you are using some sort of form from WTforms I'm pretty sure you can do something similar by accessing form.field.errors
i will check it
like flash('Invalid Email') and the in html i just create a div and {% with messages = get_flashed_messages() %} then copy the boostrap alert-danger and do it 3 times?
I think this this problem would be more easily solved by just showing the form.field.errors below each field
And flashed messages used for one time alerts, like a success message
ahh ok thanks a lot
@hasty valve sure, can you show us your signals?
{% with messages = get_flashed_messages %} {% if messages %} {% for message in messages %} {(message)} {% endfor %} {% endif %} {% endwith %}
TypeError: 'function' object is not iterable. Can anyone help me with this
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
it does not work
it's in a seperate signals file
@native tide
So profile.objects.create(user=instance) is not saving anything?
Where are you testing this? In manage.py shell?
profile = Profile(user=instance)
profile.save()
Should be good
flash("Username must contain only characters and numbers!")
File "C:\Users\richi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\flask\helpers.py", line 423, in flash
session["_flashes"] = flashes
File "C:\Users\richi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\werkzeug\local.py", line 350, in __setitem__
self._get_current_object()[key] = value
File "C:\Users\richi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\flask\sessions.py", line 102, in _fail
raise RuntimeError(
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. What i am doing wrong here
when i run it in models it works but i want to do it in signals because django recommends it to pretend errors
@hasty valve not sure what you mean here. How are you testing your post_save receiver?
with python manage.py shell?
if so, you have to import both your models AND your signals, which from your previous message looks like you aren't importing your signals.
i'm testing it on my website
hi, is anyone able to help me #help-bread pls? im stuck, i have no clue how to proceed
Small question, on Django, if I decide to load the templates per app (a.k.a., APP_DIRS:True), how do I reference the path to the template on the view?
I keep getting this error: "Uncaught TypeError: Cannot read property '89753857873166336' of undefined"
Anyone know what's up?
function fetchData() {
const xhr = new XMLHttpRequest();
xhr.open("GET", "inventory.json", true);
xhr.onload = function () {
if (this.status === 200) {
obj = JSON.parse(this.responseText);
return obj;
}
else {
console.log("File not found");
}
}
xhr.send();
}
var data = fetchData();
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var userID = getParameterByName('userID');
var items = data[userID];
Does anyone have a quick suggestion on a quick way to setup up an Ubuntu box to receive webhooks? Can that be done easily with Flask? What other dependencies does it need? Nginx? WSGI?
Depends? XD
for testing? flask or fastapi and you can just use the built in python webserver
public and hosted and scalable? yeah there will need to be more involved
Likely a race condition where your data array isn't populated yet but you're trying to fetch that userID from it.
See the "true" in your xhr.open? That says "do this async".
You should wait to do the lookup of data[userID] when you receive the callback.
For instance, try to refactor it so that you do the lookup in the onload if status is 200 instead of doing a return cause it isn't working the way you think it is.
anyone know why im getting a 404 error all of a sudden on my static files. nothing has changed as far as i know
errors in console:
m:1 Refused to apply style from 'http://127.0.0.1:8000/static/frontend/stylesheet-main2.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
m:14 GET http://127.0.0.1:8000/static/mobile/main.js net::ERR_ABORTED 404 (Not Found)
solved, i turned debug off, which put django into production mode. since django isnt built to serve files, it wasnt serving the static files anymore
thanks for the reply, will have to try once my vps back online
Is django hard to learn
basics not really, but theres definitely advanced topics in django
What is the hard part
i am displaying icon on my logout text
<a class="nav-item nav-link mr-3" href="{{ url_for('logout') }}">
<b><i class="fa fa-sign-out fa-2x" type="image/x-icon" style="color: red"></i>Logout</b></a>```
but it display like this
How to store access token without using session?
Hello everyone, is there anyone who has already used validators in django?
yes, what's the question
save it as a cookie
anyone know whats the best way to store images with django? I was thinking of having an image upload and then saving it to imgur or some sort of cdn, and saving urls in db
you can upload directly to your server in django. thats the best way in reality. otherwise youll have to find an api that passes back the url to you to save
continuing to save directly to your server would probably run up the hosting bill compared to uploading to some sort of cdn, I think I'll work with some apis here.
its just no easy to do and be user friendly. set a file size for uploads. or shrink the files server side. otherwise just give them an input to put the url of their image in. but its extremely not user friendly to force users to sign up for another service simply just to upload a profile image for example. youd be surprised at how many images fit in small spaces.
you can also save the image blob in your db. and have the <img> html tag display it.
and 3rd party hosting puts you at the mercy of the 3rd party for download speeds to display it
Is there a HTML validator extension for VScode?
Hey @novel dome!
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:
Hi guys. I am trying to get this project up and running but for some reason doesn this django web application refuse to start and I have no idea where to look. I know that it runs on another computer in the team but I cannot get it running at all.
django.core.exceptions.ImproperlyConfigured: Cannot import 'test'. Check that 'minitwit.apps.TestConfig.name' is correct.
Good morning! I'm trying to generate a XML file using the writexml method from the minidom module. Does anyone know why the root is next to the version thing?
in django, how would you set a field be changed once specifically False -> True and not the other way around?
I personally don't think so
@abstract magnet if you are learning it for the 1st time check out this site: https://realpython.com/get-started-with-django-1/. This helped me get started learning Django.
Wondering if I can get some help with Django, I'm trying to migrate a blog post model. And get this error:
django.db.utils.IntegrityError: column "author_id" contains null values
I added null=True onto the author, but that didn't seem to help.
class PostObjects (models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='1')
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wiki_posts', null=True)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
pub_date = models.DateTimeField('date published')
status = models.IntegerField(choices=PostStatus, default=0)
objects = models.Manager() #default manager
postobjects = PostObjects() #custom manager
# class Meta:
# ordering = ('-pub_date',)
def __str__(self):
return self.content
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1) ```
try adding blank=True for your author_id
also a quick suggestion and a question, why would you return self.content uwu
maybe you dont use the admin panel provided by django, but like if u do it might look messy i dunno
With blank=True, I get this error
You are trying to change the nullable field 'author' on engineeringtheorypost to non-nullable without a default; we can't do that (the database needs something to populate existing rows).
I also tried adding a followup default='', but that landed me back to my first error.
I added it in just so I can see what it does/how it works
hmm... I did a bit of research and found this article: https://medium.com/@inem.patrick/django-database-integrity-foreignkey-on-delete-option-db7d160762e4. It looks like they are not using null=True at all
Also in the article they are user POST instead fo User, maybe that could be where the issue resides
Hii, I want to use service worker with django with angular as my front-end for push notification I tried many libraries over web and could nt find that solve my problem . If I used node as my backend everything works fine . could somebody help me to do the same with django
I am trying to migrate it but can't. Where is the problem Please help me. Thanks in Advance.
do you have api module
With blank=True you dont need to add a default value
??
@arctic sentinel show us your INSTALLED_APPS in settings.py
did you remember to migrate?
Sure
After api.apps.ApiConfig I have given,
Which I have nit given that time
Taking screen shot
Then
Then This crap is coming
And Now I am banging my head against the wall
hi need help regarding flask
from where that api.apps.ApiConfig comes in
what actually is that
maybe its the "api" lib
not sure whats that
if you're trying to make an api using drf is a good choice as well
There is also alot of method on making an api
csrf_exempt is also a good thing when its apos
Apis
INSTALLED_APPS is a list, you forgot a comma between api.apps.ApiConfig and rest_framework
There's your solution
Config for an app, it's in the format of something that belongs in INSTALLED_APPS @toxic flame
Could someone help me get oriented?
I'm wanting to self host a simple markdown/hugo theme'd site with images that are updated every few minutes.
What tools should I be using for this? Do I build with hugo then host with nginx? Am I able to run hugo server inside tmux and have users be directed to that port?
When I change images in /static/images/..., will they update for the user or will they see old cached images?
(edit: I think hugo server is only for testing while building, and nginx is how we're meant to host?)
Can someone give me good css frameworks
Is there any good tutorials for bootstrap
Hello guys ..
Attached is the code to get access token from cache which expires every 10 mins. So every 10 mins I have to refresh the token but I'm not able to calculate the expiry and call refresh token API.
nice font/color scheme
Hello, noob here. Is there any good tutorial to make a login system with flask + pymongo?
Can someone tell me how do you set up pre-orders in ecommerce websites? I'm trying to build one with django and would like to have this functionality present. But I'm stumped as to how this works...
@glacial wigeon you can have an 'Orders' model and have orders with a specific type, e.g. preorder or not
BooleanField
with a status field in your Order model?
just read there this answer - well that's basically what I mean.
So to understand this correctly, I'll be linking the order with the user model, and the order will also have a "preorder" boolean... ? So once the product is in place, I can just change the preorder status, and notify the user for any remaining amount to be paid. Right?
@glacial wigeon yep!
Either give the Product model a boolean field, or the Order model to specify a pre-order. Both work!
Thats the error I get when I use makemigration and migrate
Tailwindcss and bootstrap are good
@toxic flame this is null = True
Blank just specifies whether the field is required in forms.
@dreamy herald can you show me the error? I cant see replied msgs on phone
Hmmm i see
thx @warm seal
can i get some help
sure
can someone help me on hosting a website
im about to buy this host but i want to make sure i can use my code for it
can anyone help im using django
anyone good with flask free to guide/help me? ive been stuck on this issue since yesterday and i dont know how to proceed #help-chili
I used a validator to catch the errors and show them directly in the browser on the phone field.
When I fill the field with a number less than 10, it displays a message such as:
I don't understand what is happening
Can someone help me?
wait!
You're returning nothing to the website
ignore the urls its not the urls
ok
so
add the following
context['form'] = form
remove {'form': form}
and replace that with context
lets see what returns
Okey, i try this
@toxic flame lemme try fix this for a sec bud
heh
also, instead of posting a screen shot of the code
type ` three times and then add py and close with three more
it doesn't work!
show us the code
`def details(request):
if request.method == 'POST':
form = UserFormDetails(request.POST)
if form.is_valid():
form.save()
return redirect('thank')
else:
form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
return render(request, 'home/signup.html', context['form']= form)`
you should rewrite the whole code for him
context['form'] = form
return render(request, 'home/signup.html', context)
implement that on the last two lines
Its also not necesarry for a "context", his method also works
HOO, I see.
i think he wants to return the name to the page
@native tide you can just remove 'context' all together if youre not planning on showing it on the html page
Im curious where this goes
@toxic flame respect the chat and dont type unless you want to contribute
I would but you suggested me to be quiet for a moment
`def details(request):
if request.method == 'POST':
form = UserFormDetails(request.POST)
if form.is_valid():
form.save()
return redirect('thank')
else:
form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
context = dict
context['form'] = form
return render(request, 'home/signup.html', context)`
even that doesn't work
how long have you been coding in python
you need a better understanding of the language to accomplish a successful django project, but I will fix this for you
Finally, wouldn't it be a version problem?
no
you dont have a basic understanding of dictionaries
so i dont understand why you are attempting to create a django project
it will be very difficult
def details(request):
if request.method == 'POST':
form = UserFormDetails(request.POST)
if form.is_valid():
form.save()
return redirect('thank')
else:
form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
context['form'] = form
return render(request, 'home/signup.html', context)
wait
dont copy that yet
what is your html file called @native tide
signup.html or home/signup.html
@native tide
It's not the html location's fault. If it was the error would be invalid template uwu
signup.html in the home folder
ok
def details(request):
if request.method == 'POST':
form = UserFormDetails(request.POST)
if form.is_valid():
form.save()
return redirect('thank')
else:
form = UserFormDetails(initial={'username': request.user.username, 'email': request.user.email})
context['form'] = form
return render(request, 'signup.html', context)
honestly i dont think this is gonna work
It raise an error: context is not define
Look azza, if you don't know what you're doing don't
You're wasting this man's time
if you dont have anything just stop
i do
You told me you wanted to fix it
Whatever my free time is over
@native tide send a screenshot of the page
before or after the error?
send a screenshot of the page that shows up @native tide
No, that is before to fill fields
Okay, thank you both for helping me out. I think I need to rest a little, maybe I'll find the loophole.👍
lol
In HTML/CSS, if I got two images, one larger as background and one smaller as subject, how can I place the smaller relative to the bigger one and then scale them together so they fit the display?
for example, position the smaller one exactly at pixel coordinates X,Y of the bigger one
where should i start learning flask?
I have done that
This one is coming after that
can someone please help me with django-channels here?
https://stackoverflow.com/questions/66130387/channels-how-to-know-the-name-of-the-group-an-event-is-sent-inside
i have index.html page it require image to upload after i upload image the label choose file still remain same i need to change the label instead of choose file-> filename.png i use custom-file label
<div class="row mb-5">
<div class="col-md-6 m-auto mb-5">
</div>
</div>
<div class="row">
<div class="col-lg-12 pt">
{% if form %}
<form method="POST" action="" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.picture.label(class="custom-file-label", for="files", id="files", label="files") }}
{{ form.picture(class="file custom-file-input", type="file") }}
{% if form.picture.errors %}
{% for error in form.picture.errors %}
<span class="text-danger">{{ error }}</span></br>
{% endfor %}
{% endif %}
</div>
<div class="mt-4 text-center">
{{ form.submit2(class="btn btn-outline-info") }}
</div>
</form>
{% endif %}
</div>
</div>```
i try this but it didn't work
<script>
$('#files').on('change',function(){
//get the file name
var fileName = $(this).val();
//replace the "Choose a file" label
$(this).next('.custom-file-label').html(fileName);
})
</script>```
hey so i was trying to create a simple graph with chart.js, but it dosent display anything its just blank idk why tho ```html
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</head>
<body>
<canvas id="lineChart" width="900" height="400"></canvas>
<script>
var ctx = dccument.getElementById("lineChart").getContext("2d");
var lineChart = new Chart(ctx, {
type: "line",
data: {
labels: ['1', '2', '3', '4', '5', '6']
datasets:[
{
labels: "Data Points",
data: [89, 43, 128, 122, 113, 12]
fill: false
lineTension: 0.1
}
]
},
options: {
responsive: false
}
});
</script>
</body>
</html>```
and those datas are recived from flask
maybe its just my eyes, but "ctx. " doesnt look right
new Chart(ctx. {
shoudlnt it be ,
yea i fixed that its still the same
anyone know how to add modwsgi to apache. its installed, but i cant seem to get it to show up
anyone knows SQLAlchemy?
followed = db.relationship('Follow',
foreign_keys=[Follow.follower_id],
backref=db.backref('follower', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
can you explain the backref part in this
as far I know, the value to backref could be used by the other table, to access this column stuff, right? and the other table would have a "variable" called follower(from backref) to access this column,
its like this column followed exits in table Follow under the name of follower
☝️ is that all good?
ping me to reply please
Who is good on django please ?
why am i getting this. im pretty postive my setup is fully correct http://www.safespace.fyi
I don't see the comma, it was not included in your INSTALLED_APPS
guys should i learn django or ruby on rails ? ping me if you have an answer
try both and choose the one you like the most
Wsgi? Htaccess?
These r some major parts of deployment
If someone is more experience with react-stripe-js, I would appreciate any help.
Would I be able to get a job in web development with a pre computer science degree?
Hi, Everyone, As a web developer, I am looking for a remote job. Could you help me?
Comma after the labels list too
Whats the best python webframe?
There is no "best" there is prefered hehe
Which is the "preferred" ?
you could make arguments that both django and flask are good for beginners
both have their pros and cons
but i would suggest flask
its easier to start with
Great ! Thanks to you both
Yea flask for beginners good
Because its light weight
But django is also good and its alot simpler than flask
Django is "monolithic" but it really isnt.
Hello, how can i add Meta Tags to a html file that will display the meta data on discord? (flask)
nvm, ignore it
Anyone got an django socket resources I could learn from would be nice to link me :)
Hey, quick question using Flask SQLAlchemy. Any way to get a default value of a column?
Hello everyone.
I am trying to integrate stripe into my project, but I am having a small problem with my Pay Button disabled attribute.
I am following the basic example of react-stripe-js.
My components in one file:
CheckoutForm and InjectedCheckoutForm: https://pastebin.com/XSr54pMt
The other component where I am calling the function loadSprite that returns a property (this works fine), and I am assigning it's value to a state, so I can pass it to the sprite prop in the Elements component that came from the parent component CheckoutForm.
ViewMembers.js: https://pastebin.com/swvCeQQd
The problem is even though loadSprite function is called, and the prop gets the right value (I am checking this using React Debug tools), the button in the parent component 'Pay', it's still disabled.
Maybe someone can notice something I could not. I asked this question on stackoverflow as well, and I did not have much luck. Here is the link if you are interested - https://stackoverflow.com/questions/66132737/react-stripe-js-button-for-pay-always-stays-disabled
I am sorry If I am asking this again, but I have not had much luck.
Does anyone want to start a web development business? If so dm
is there a way to upload images to my website with a custom link like mydomain.xyz/image/dfoksdfljsdflsjf and python code can upload images to the link
its flask
I need the same thing, but upload images from frontend-API post. Is it doable?
wsgi is setup htaaccess is setup, im getting a python error module not found encodings error so i think its a venv problem, still working on it
you can in django, just google it for flask
Ok, thanks
How does Flask handle scripts responses i.e. JavaScript's operations? I'm planning to create several clickable buttons on a webpage I'm building and attach an **event handler **on each of these HTML elements. So when a user clicks on any one of the buttons, the page displays the corresponding result of a specified function output (defined in a Python script)
@pulsar copper Well, that's a pretty loaded question. Hopefully you understand that Flask doesn't care about JavaScript at all. They don't talk to each other whatsoever. In your example, the JS you mention runs on the client, makes a call to the server, and there Flask app can respond to the request and return data. It doesn't care or know that it was JS, only that an http/https request was made and it should respond. It is up to you as the Flask dev to decide how to respond. Returning JSON for example.
It's very important to understand the client/sever relationship in web apps. I can't tell you how many times I've had to explain this to even seasoned devs.
Ahh I see, makes sense indeed 🙂 In short, Flask doesn't deal with mouse/keyboard events that's processed on the client-side, gotcha
@warm igloo Speaking of JavaScript, can you pass in an instantiated Python class instance object (or its method, for that matter) to a function definition in JS?
You can pickle python objects so they can be sent via https as a bytestream. But js won't know what to do with it...
It is important to note that this is with any backend code be it Python and Flask, C# and .NET, etc. There is the client side (HTML, CSS, JS) and the server side (multitude of options).
Literally all you can pass back and forth is data. So in the pickle example from Busykoala, you can send a string representation of an object, but that doesn't matter. It's just a string.
So as a Flask developer, how do we instruct JS exactly what to do? Are you saying it doesn't recognise this pickle object? I appreciate y'all helping me btw 🙂
Either you can render a template containing js code or only use flask as a rest endpoint
yep
Anyone here experienced with socketio on django?
The documentation sure is detailed for nodejs ( express ) but like for django there is very few
there is certainly a library for it on python but like not too detailed
What kind of pitfalls can I get myself into here if I don't do it the proper way (in terms of best practises, maybe)?
did you ever find a way to do it?
hello everyone? somebody here had ever used a pwa?
@native tide Freecodecamp and Mozilla
Welcome to the MDN learning area. This set of articles aims to provide complete beginners to web development with all that they need to start coding websites.
can someone help me with css bootstrap
Resources for PHP?
looking for honest help setting up an apache server with mod_wsgi for django
ive been trying to get it setup for like 5 days now. im so sick of messing with it and the documentation is absolute trash
Can anyone suggest good courses or videos for web development for data analysis using python?
can someone please help me here
https://stackoverflow.com/questions/66147358/member-related-permission-checking-rest-framework
I am trying to make a permissions system like discord-with django
I asked this question the other day, but wasn't able to find a solution. Hoping a new set of eyes would help.
I get this error:
I have a django model:
class PostObjects (models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='1')
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
pub_date = models.DateTimeField('date published')
status = models.IntegerField(choices=PostStatus, default=0)
objects = models.Manager() #default manager
postobjects = PostObjects() #custom manager```
I have tried addding, null=True or blank=True on the author Foreignkey, but still get an error.
I have also been using makemigration and migrate each time I make changes too.
So it looks like I was able to fix it, by delete all my other migrations and then remaking the migration. What's the downside of what I just did?
Hi guys, what linter, static analyser, or anything do you use to avoid errors like this?
qs = MyModel.objects.filter(something='ooo')
qs.pk # qs is a QuerySet not a MyModel instance, and it will raise a runtime error
if its developement, its not a big deal. if its production, it could cause you db to be out of sync or something along those lines. really dont want to do that if you can avoid it
.get for getting a model instance
.filter filters every object
thank you 🙂 I'm asking about automatic tools that can notify our devs if they make such an issue
i know how to solve the issue, my question is how to avoid it
cab I interrupt your talking for one sec I have a very small question ?
@wet wasp sure
thank you
basically I am trying to change the value of <textarea> by using js but each time it change it for one second and then delete it direcly anyone have any idea why is that happening to me?
function B() {
let v = document.getElementById("Binary").value;
let h=B2T(v);
document.getElementById("Text").value = h.toString();
}
function T() {
let v = document.getElementById("Text").value;
let h=T2B(v);
document.getElementById("Binary").value = h.toString();
}
these are the function that I use them to change the value
but it change for less than one sec and goes back empty
<form method="POST">
<textarea id="Text" rows="20" cols="100" placeholder="Enter the text"></textarea>
<br>
<br>
<div class="Jan">
<button class="space" onclick="B()">Binary To Text</button>
<button class="space" onclick="T()">Text to Binary</button>
<input class="space" type="reset">
</div>
<br>
<br>
<textarea id="Binary" rows="20" cols="100" placeholder="Enter the Binary"></textarea>
</form>
via button
make sure that you don't have any extra js included that might mess around with you
Hello we are looking for dev to new project "enzy" if you know how to use python in scale 9/10 dm Me for more informations
can you explain for me what do you mean?
I meant that you might have some extra code that you forgot about, Usually happens if you have a larger file but in this case i know your issue i think
let me send everything
you have a button inside a form element which by default will act as a "submit" button which will refresh the page
add type=button to the button tag
Very true
yw
it worked
you might want to check out addEventListener and how to prevent the default behaviour of events
so back to this. I'm looking for a tool that can analyse the code and make the CI pipeline fail, so that we don't ever deploy invalid code
we use pylint but it just doesn't work well with QuerySets, I've just installed and tried the pro version of PyCharm and I don't get any warning messages
I'm building a Flask-based webpage and I'm having trouble **displaying ** an **image ** when clicking a button on a HTML page.. I've attached an event handler to the HTML button element and then created a function in JS which should display and make the image visible when the button's been clicked.. but nothing shows up 😦
app.js - Here's how I triggered the onclick event with generateSimpleWordcloud () function
- make sure that the
generateSimpleWordcloudfunction is called (e.g. useconsole.login the function) - make sure that the wrapper is selected properly (e.g.
console.log(simpleWordcloudWrapper) - can you share the related HTML?
html page - How I attached the onclick functions to the HTML button elements
This is how I added the script tag on the HTML page to link the JS file
where is your button? have you tried my 1st and 2nd suggestion? what were the results?
Yeah it works now, idk why it gave me an issue earlier on --- the image does show up when I click on the button --- (and yes I've added the console.logs logs, not sure if that solved the issue)
haha i don't think that console.logs solved the issue 😄 maybe you had some cache related issues
Is it really? 😆 Every time I modify something from my code files, I always be sure to delete the cache that's saved on the browser though 😕
Hey guys do you know any great flask tutorial to guide me through the framework?
That is not too long. I want to have a good overview so I can start building and experimenting with things.
Hello guys and girls of course 😉
Hey, for the web apps I've made with Django, a lot of times I will have "settings" that I want to configure on the site from an admin page while the site is running. Say, for example, a setting that lets you disable and re-enable user registration. I've handled this by making "singleton models" where I store a single object in a database table, but this seems to go against what databases are designed for. Is there a best practice for handling this type of configuration?
Hi which course is good for web development on udemy? angela yu or colt steele?
What do you think about async web-frameworks for python?
Nowadays I'm thinking about to start a new project with fastapi.
Django vs Flask?
Using Flask SQLAlchemy and I'm not sure as to the purpose of a ForeignKey with a backref already in place.
Say I have an Author class with the following relationship:
stories = db.relationship("Story", backref="author", lazy=True)
In my Story class, I can then access the author id using mystory.author.id. Is there any point to including a ForeignKey reference to that user in that case (as below)?:
author_id = db.Column(db.Integer, db.ForeignKey(".id")) # or story.author.id
How can i make a html form that could change a python script?
Yo so in vs code I wanna say like if I type a class, and then “.”, it’ll show me all the attributes and methods of the class, what extension is that called? Or what are the vs code extensions that can do that?
Oh nvm
I found out one of them
It’s called Pylance
so uhh question
i assume flask is utilizing workers
since it's a wsgi server, when it runs locally
i ask because I'm trying to schedule tasks, and it's such a pain
dealing with concurrency issues
im making a d.js bot and are using mongoose
everytime i do nr.bal
it replies 10 seconds after
MongooseError: Operation datas.findOne() buffering timed out after 10000ms
this appears in my console^
So I’m not sure how to even search this. I have a form text area that I’m resizing with the little handle on the bottom right. I can pull that over the submit button and the scroll bar doesn’t change so can’t scroll down on the page. Is that overflow?
Have u considered its maybe ur internets fault
Or you have some dns problems
e
Firebase
Could someone help me with my web server?
if I was writing an api server, what library would I want to use?
this won't be serving webpages at all, but should be scalable
@barren moth I think you and I have different ideas about what constitutes scalable
I'm working with ARU. We need a reasonable choice for a back-end API server that runs behind an NGINX reverse proxy, which will eventually be configured to round-robin requests between multiple machines. The back-end servers do not necessarily need to communicate with each other
Right now our code just extends http.server
Projects we're considering, though haven't researched, include Django and Twisted. In the past I've used cherrypy but I'm not sure if I want to use it here
Hey. I know this is an ambiguous question, but is it possible, and if so, is anybody interested in, making a search engine with Python?
Django in the backend.
Wouldnt take more than a day
@toxic flame , do you mean me, or somebody else?
Seriously?
so earlier I had a django project with a single app but with lots of models.
Now, I have split the single app into multiple apps. But now, I need to make a lot of imports
from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework.pagination import LimitOffsetPagination
from rebox_django.apps.core.views import (PutAsCreateMixin, FlexibleObjectMixin, MultipleFieldMixin)
from rebox_django.apps.core.views import (PutDeleteAPIView, ListBulkDeleteView, EmptyBatchUpdateView)
from .models import (Channel, Category, Box, Upload)
from .permissions import (DeleteUploads, ManageBox, DeleteBox, ManageChannels)
from .permissions import (SendUploads, ReadUploadHistory, AddStars, RemoveStars, ManageUploads, EditUploads)
from .serializers import (ChannelPositionSerializer, CategoryPositionSerializer)
from .serializers import (UploadStarSerializer, UploadSerializer, BoxSerializer, ChannelSerializer, CategorySerializer)
from .serializers import (PartialBoxSerializer, PartialUploadSerializer, PartialChannelSerializer)
from .serializers import (PartialUploadStarSerializer, PartialCategorySerializer)
Is this normal?
Because I split it down, to keep all my abstract classes, I have an app called core
it is possible
I can do it in one day?
Backend yes
Great!
I usually take so long for the fronted
Frontend, isn't terribly important.
django encourages real Rapid development
The backend is what I need help in.
Yeah, I know Django well.
guys any quick opinions?
No, I don't want to google it in the backend 🙂
No, is it possible to actually scrape the web?
Yes but it will cost you several millions of dollars or your pc will burn down the first few days
You know, build what these google guys built back in 1998.
Why?
Sigh
There are millions and millions of websites out there
Millions and millions of combined char for a domain
your pc isnt gonna just take a day to collect every single data
I dont know ask google
Yeah, they have millions of dollars now, but in the 1990s??
They do it now by having the user register their website to be listed on google
If you're doing a search engine just use a third party api uwu
It's also good practice to learn how to use apis
I have to go cya
Sure.
Can anybody tell me if it's possible to do a search engine which requires people to sign up their site?
Yes of course everything is possible
Hey, is it legal to tell my age out here?
Without the philosophy 🙂
i dont think freedom of speech is illegal
But it's tru 🥲
No, but some people make it a crime to give out even your own PI.
well, so I'm just 13.
Not terribly experienced.
Know Python for only around two years.
have school.
anyone have any suggestions on this?
So far, we've heard about or looked at
- aiohttp
- starlette
- fastapi
- Django
- Twisted
- cherrypy
<@&267629731250176001>
!pban 736654399392186459
:incoming_envelope: :ok_hand: applied ban to @fast kiln permanently.
@barren moth Starlette / FastAPI are the most cutting edge of those projects in terms of both speed and use of asynchronicity. Django is more for user-facing stuff -- lots of convenient features but not the fastest.
Aiohttp is more a base-level toolkit for doing asynchronous I/O
also, nothing says this all has to be built on one thing. Django could be used for things that are convenient but not performnce intensive
!warn 756281664090538066 That's not something appropriate to say here. Please don't do that again.
:incoming_envelope: :ok_hand: applied warning to @toxic flame.
oh sorry
i do know that aiohttp does have a server https://docs.aiohttp.org/en/stable/web.html#aiohttp-web @cerulean vapor
which is why that is being considered
it's a very minimal one, though. For something robust you would probably use an actual web server, like Apache or whatnot, as a frontend proxy
NGINX
or Nginx, yes
this is the description #web-development message
but really, anything that supports WSGI or uWSGI (for async) will work
I'd pick at least one of those things I mentioned and try building something with it. Don't succumb to decision paralysis. Just start building stuff with something and see what the experience is like
so is there a relationship between starlette and fastapi?
I heard that fastAPI was built on Starlette
FastAPI framework, high performance, easy to learn, fast to code, ready for production
FastAPI is fully compatible with (and based on) Starlette. So, any additional Starlette code you have, will also work.
Starlette is the substrate; FastAPI is built atop Starlette
so start with starlette if it doesn't work, fastAPI
Starlette might be a little low-level, but sure
what do you mean?
there might not be enough in Starlette to build the things you want without doing that much more heavy lifting. FastAPI may be more convenient
that's also why frameworks like Django are useful, they provide a lot of stuff that people often have to roll when making a site: user management, for isntance. But that comes at the cost of it being pretyt topheavy and not the fastest
but again, you could use Django for the "convenient but slow" stuff and FastAPI for the, well, fast API stuff
so use them both in tandem
Hello, everybody.
I'm planning to build a search engine with Python in the backend. A real search engine, not the kind which Googles the query in the backend. I understand that it's pretty complex to crawl the whole internet, so I want users to register their site.
If you're interested, and you're good at
- Django or
- HTML/CSS/JS (for the frontend, obviously. Especially if you're good at CSS. I'm horrible at design.) or
- Requests, BeautifulSoup, or Scrapy. Or any packages related to scraping or the internet,
then DM me @worldly mist .
Thanks.
Recruitment is not allowed on this server. If you want people to work on an open-source project, feel free to share the link.
you kinda are
But it'll be hard to discuss the project here, so I thought I'll create a seperate channel.
If that's wrong, I'm sorry.
Well, realistically, large-scale indexing is not something to be built with Python.
well... no
C++ is not similar to C anymore, C++ allows quite a bit more abstraction and safety
Is it even possible?
I wouldn't write anything in C. C++ or Rust, I guess.
OK.
I'm not sure what your goal is. If you don't want to pay anyone or make a paid product, why not make the project open-soucre? @worldly mist
hence c++ 20?
?
by "anymore" I mean more like since the start of the century
I do want to start a seperate channel, but I don't want people just pouring in.
So I thought, if they DM me, I can add them.
And I don't really want to share the code online.
Is that allowed?
I'm new to this place, just joined today.
Why do you not want to share the code?
So not terribly good with the rules and regulations.
It's not like it's a necessity, but I'd rather keep it private.
Just.
because of plagiarism?
Yeah, you could say that.
I have a few friends who are developers, too.
And don't want them to get the code and make it their own...
Yeah, I don't want to open source it, but I don't exactly want to do it myself.
Anybody who's sincerely interested is free to join.
@worldly mist
A closed-source project that doesn't make any money won't attract much attention. Thousands of open-source projects thrive, and many of their maintainers profit from it.
Thankfully, we don't treat intellectual property like barbarians. If someone steals your code, it's a crime. You don't have to hide it or anything.
The primary way of collaborating on open-source project is a version control platform like GitHub or GitLab. You can start your project there, and share a link to it.
so that only the people who are really working on it can get it.
so you are also talking from a security perspective
Yeah.
If someone steals your code, it's just crime. But if you keep your code private and someone steals it, you can't even prove that it's your code.
^
I could always open source it later. But when it's small, I want to safeguard it.
So the plan is, start a channel. Anybody who wants to join can. I add them as colabs in my github repo.
Well, we only allow open-source collaboration because otherwise, we can't see what things you're up to in a private group. That's just a practical limitation.
Is it valid if I add all the moderators to the repo and the channel?
That's just unnecessary burden, and... it's not really closed anymore, is it.
What's not really closed?
Sorry, I just realized I keep saying channel. I mean server.
Surely it's not forbidden to start my own server and invite people to it?
Just to be clear, we're not going to make our whole moderation team watch over your server. If you want to share your project here, it needs to be open-source. Which is also the only viable way to grow it, as I said.
Surely it's not forbidden to start my own server and invite people to it?
No, you can't advertise a server here. For the same reason: we can't moderate every single server you're sharing.
Outside of here, for example on r/Python (on reddit) or some other resource, you could share your project.
The rules are very simple: if you want to promote/share a programming project, it has to be open-sourced.
For the reasons described above.
Now let's finish this extremely off-topic discussion, or move to off-topic if you have any more questions.
sorry accidentally sent a message
lol, thanks
Hello, I'm working with Flask at the moment. Anyone know how I can do nested routes? like if I have an account route, how do I specify an account/kits route?
hell
i think you need to do something like thi
you can specify your route in app route via seperating by /
Hello I wanna make a project if you are interested to know and join we then please dm me...
Can you indicate that what is your project about?
Hi there!
I am looking for a web developer with knowledge in SQL. I am looking to code a dashboard for my discord bot that uses OAUTH2. I have no idea where to get started and am looking for someone to give me some serious help in getting started.
esydysy is not being printed, so I know the socket isn't working
Hey there,
I need help in sending html emails from celery tasks in Django.
In my task function, I am not able to get email_template file (.html)
I'd first check if the file you're trying to access is really the file you want to access (log the path and see where it is), then I'd check the file permissions
How can i set a div col-md-5 to the center?
hey, is anyone here familiar with django-cryptography?
use margin auto
or if thats bootstrap im sure it has a text-center class to align elements
or even use flex justify-content: center
anyone know why viewset.ModelViewSet wont post with a foriegnkey involved? ive tried, both the slug value, and and the primary key, and neither of them work.
Hi Guys and Girl, i come here because i've a question (may be esay for you, i hope)
In django project, in a view i need to mix informations from several models. for the moment in my view i do : tag_1 = model_name.objects.all() and i do this opération for each table (so three times)
but i would like create a new object for extract only few information
betwen the 3 table i've table relation by foreignkey
I want add page navigation button I on my django app, but I don't know which keywords should i search for on Google
is there any django expert can give me some advice?
Hi Jet
in your HTML file juste after your data tou can write :
{# Mise en forme de la pagination ici #}
{% if is_paginated %}
<div class="pagination">
{% if page_obj.has_previous %}
<a href="?page={{ page_obj.previous_page_number }}">Précédente</a> —
{% endif %}
Page {{ page_obj.number }} sur {{ page_obj.paginator.num_pages }}
{% if page_obj.has_next %}
— <a href="?page={{ page_obj.next_page_number }}">Suivante</a>
{% endif %}
</div>
{% endif %}
and you can replace "Précédente" and "Suivante" by pictures or logo with a special font
in your view.py do you use listview from django.views.generic ?
hhu
No I don't
Can somebody help me setup Dockerfile for django app?
Hey guys. I often create tools that uses flask/django to automate some work. I think it could be useful for some people and I want to share it. But I don't know how to manage the project to be user-friendly (I think about case how someone will set this application up, how to deploy it and stuff like that). Do you know any popular tools written in python using flask/django that I can look at github? I know that apache airflow is using flask for example, but I want more to see if there's some pattern
By "user-friendly", do you mean you want a clear user interface? Or do you just mean you want it deployed?
I mean that someone that wants to use my tool, could can do this easily, fast and with pleasure 😄 Not exactly user interface. Besides that I want to know how I can share tools like that in a proper way, how big players are doing this - should I create maybe some installing script, or maybe should I use docker for this (I don't have experience with docker yet)
simpler question would be - do you know any popular tools written in python that uses flask or django, besides apache airflow? because i have hard time explaining what i really mean, and I want to look at some real-world example
might be breaking the rules here, is there a freelancer channel in here?
Which DB are you using/planning to use?
SQLITE3
Are you familiar with any ORMs?
Not sure 🤔
Maybe check simple ORMs like peewee if there is not much data.
I’m just not sure how to use disco-auth and backend code. I have only used python and html before never node.ja
Does not require separate server
So easy for small projects and demos.
Atleast that's what I believe
is it possible to build a Large project, with django + sqlite3
You can
But DB performance would be bottleneck if you gonna get lot of traffic.
Since sqlite is just a single file DB
Is there a way to create an application that clicks and interacts with websites, even if those websites do not have API?
Or even pull data from these websites instead of just a rudimentary click
Look into selenium or beautifulsoup
Thank you
Hey, does anyone know a js library that has "area under the curve" functionality built in? I was looking into NVD3 and it doesnt seem to have it
By that I mean like the user can select and drag an area on a graph and it automatically calculates the area under it
@fallow void Wow it looks like they allow you to use the product commercially as well and grant you all royalties. This is very generous. Thanks again
which db is suitable for high traffic,
It depends on how much traffic you are expecting.
But some dbs are made with specific needs.
Like for logs and textual data you can consider elasticsearch.
For data that is very much structured, you can consider relational ones like postgred or mysql.
What is the modern equiv of bootstrap. Most of my work has been backend forever. I learned some bootstrap + flask many moons ago for quick/ui web stuff
is there a new cool/easy alternative
or I must go for css/javascript and sell my soul?
bootstrap's great, for me it's a staple. but if you want to take your webapps to the next level, js is a must (as well as css, which is what bootstrap helps with). in particular, frameworks like react are great.
So basically im using this Django template engine for html and I need to load static files so i can use them to style the html and images and js stuff. but like them wont load for some reason i have this static folder in the app folder and then i specified it as STATIC_URL='/app_name/static/' and then in the html file, i did
{% load static %}
....
<link href="{% static 'folder/name.css' %}">
....
<h1 class="text-class">Hello</h1>
....
but then it just doesnt work and no errors are given so idk
oh btw i also did put
django.contrib.staticfiles in the INSTALLED_APPS array
I'm not sure but try to set STATIC_URL='/static/' and leave the rest as it is and try if it works
oh yea i tried that too, unfortunately, it didnt work as well, the error just says that 404 cant get blah blah blah from blah blah blah , and since its a 404, it prolly means that its getting the static files through HTTP protocols, maybe i need to set up the storage for the files? but idk how that works
Hmm sorry I don't have a clue what could be wrong, but maybe someone else does
Alr thx for responding tho
Thoughts of Sanic vs FastAPI? I've heard about both and that Sanic is async and FastAPI is not.
Besides those two choices, for startups, I still recommend Django. The ecosystem modules are just too good.
@barren moth
so the way most web frameworks work, they either implement the ASGI (async) protocol or the WSGI (sync) protocol
some frameworks come with their own server, but most allow you to switch out the actual server running the website
the advantage of that is, someone can implement a better more efficient server, and a lot of frameworks can benefit from that. the disadvantage is the small bit of hassle of actually deploying the site.
while you're developing you dont need to worry this at all, most frameworks have a small server built in, just for developing. the built in server should NEVER be used in production tho.
the development servers are usually quite insecure, and also inefficient
Ah
FastAPI is async
Sanic is basically async Flask
FastAPI is its own thing
Why would a synchronus web api ever exist anyways?
why not?
in the case where generating the response is "fast" and doesn't have to wait for external entities "much"
a sync web framework is fine
Django is sync too
although the limitations of WSGI are becoming more and more obvious in today's world, I guess
Yeah
nevertheless
Why would you ever want to build sync now
it's still perfectly possible
because you don't need the complexity + functionality of async
How is async more complex?
Don't you just use async and await keyword
... Should I go back to reading 101 guides lol
it's harder to debug/reason about the performance of your code
quick example
when you await, you don't know what code will execute next
Because you don't know if it'll run that function or a different function?
something like that?
you know how the event loop works, right
what happens after you give up control
depends on what tasks are currently queued
Possibly but I don't have a thing attached to that name
i.e. nondeterministic
it's a common implementation of async
so basically
you have a "backlog" of tasks that are running
when the one with priority awaits
it pauses
and the next one starts running
until it awaits
then the next one, and so on
the machinery that handles all this is called the event loop
So only one thing in async is actually running at a time?
Okay, I get it now
Just switching between what's running a lot
While awaiting something it can do other stuff
Which is why you have to use the async sleep if you want to pause, otherwise it pauses the entire script
yes
good observation
So why does it make this harder?
Learned hard way, just put it together
it becomes harder to understand when that shared mutable state is changing
simple solution: have no shared mutable state
What is a shared state?
say you have a global variable
all coroutines have access to that global variable
they can be said to "share" it
Oh
And they want to edit it
It's not a constant
Then yay! Race conditions or w/e
it's easier to avoid race conditions, in some ways, than in traditional threading
because you choose when to give up control
but, yeah
Okay, I think I get as much as I'll get without messing around
The problem with async = not much adoption yet on Python
If you want rock solid, you go with something like Pyramid.
Like - how much benefit does async really give you at a cost of confusing your juniors?
So paypal payments on notify actually returns the inovice id
gonna Integrate stripe now
uwu
then coinpayments
owo
so kewl i love coding
anyone know how to return a different serializer then the posted serializer with basic integration of viewsets.ModelViewSet? i have to post with id to set the foreign key, but need it to return the username associated in that foreignkey not the id
lets say you have two models, Subscribers and Newsletters linked via a third table SubscriberNewsletters. If you've defined the relationships, you can go [x.newsletter.name for xin subscriber.newsletters.all()]
kind of vibe
Flask beginner here! I assume when I deploy my Flask app, it's gonna exist on a server computer (running Linux?) somewhere out there, and so when it "deploys," we have that computer run flask run to set up the app? Do I have that right?
I need Django help on #help-falafel
Yes, they will be running on a server, in a cloud - paid for by someone else. Heroku is amazing for getting ideas into Production. Just warning, make sure debug_mode = False
Describes Heroku support for Python.
note on that, you can use different environments - if the system recognizes it is on localhost, you set debug_mode on true and use your local database. On prod, you use different variables
is_production = os.getenv("ENVIRONMENT","").lower() == "production"
That's saved me years of my life 🙂
I use this for my settings.py, I have 3 different environments as an automatic github action creates a PostgresSQL to do testing on it:
if os.getenv('DYNO'):
DJANGO_HOST = 'production'
elif os.getenv('GITHUB_WORKFLOW'):
DJANGO_HOST = 'testing'
else:
DJANGO_HOST = 'development'
DYNO?
heroku uses dyno as an environment
I could perhaps also try to use another getenv but the SO-post suggested the use of DYNO and it works for me @barren moth
Yeah, I would always make my own environment variable. How do you know DYNO will always be there. 😛 Don't trust other peoples spec. 😛
Hey I'm having trouble with Flask if anyone can help. I am trying to retrieve database model objects from the flask session for a cart system
I get Object of type Keyboard is not JSON serializable when passing my list of cart dicts to render_template
on ASP.net core MVC with identity framework, I'm getting this thing that says and I can't find the html to remove it anywhere in my project. There are no external authentication services configured. See this article for details on setting up this ASP.NET application to support logging in via external services.
Show me the code? Paste it in a link?
Adding to the cart handled in the item route
and manipulating the cart session is in helper.py
You need to provide a serialization method for Keyboard class or use something like this
for row in resultproxy: row_as_dict = dict(row)
row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns}
So how come that's the case when I can do the following: https://github.com/Muramasa-/KeyboardDatabase/blob/master/keebs/routes.py#L55
It's commented but I remade the same data structure but this time I re-query the item instead of using the one that was stored in the session dict
Passing this seems to work fine, this is where my confusion is
Because entries is a dict already. Keyboard ORM class is not JSON serializable, so if you want to JSON serialize it, you can do something like this.. let me submit a quick PR to show you..
But even doing entries[x] = {"item": session["cart"][x]["item"], "quantity": session["cart"][x]["quantity"]} breaks
My goal was to have a simple system where I could just pass session["cart"].values() to the template rather than re-querying every time cart is viewed
Oh interesting
That code does look very hacky though. I would turn the session into a dataclass.
Oh yeah what I had commented in cart was awful
Because I was trying to understand what I was missing
So like, why in the inventory route, can I pass a query result directly?
Well, you can pass the query to the renderer, but somewhere along the line, you are trying to JSON encode it
Okay I committed a working version
However, on this line: https://github.com/Muramasa-/KeyboardDatabase/blob/master/keebs/helper.py#L35
If I actually put the item obj into the dict in place of the dummy x, it throws the error on trying to add to cart
class PostUpload(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = PostsUploadSerializer
queryset = Posts.objects.all()
queryset = queryset.filter(soft_delete=False)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(PostsSerializer(serializer.data, context=self.get_serializer()).data, status=status.HTTP_201_CREATED, headers=headers)
File "C:\Users\kenda\.virtualenvs\safespace--lAQnTUa\lib\site-packages\rest_framework\relations.py", line 467, in to_representation
return getattr(obj, self.slug_field)
AttributeError: 'int' object has no attribute 'username'
``` anyone know whats wrong?
trying to create with pk for the foreign key, then converting to the response i need for display. 'int' object refers to the pk, and username is the field it should display. for more information
@forest pumice I built you an example on how to use dataclasses for your session here https://github.com/Muramasa-/KeyboardDatabase/compare/master...rodvdka:patch-3
I'm not really sure if this goes under web development but can somebody help me web scrape a number off of a website? I am very confused.
Give us some details
I want a way to extract the number 16. I was told that the number is probably loaded dynamically using javascript. I was told that I should use Selenium to extract it, but is there any kind of way to do it using BeautifulSoup or something else?
There's a python library called "scrapy". I didn't use it but I heard that you can scrap from javascript but I guess it will be more difficult than using selenium. You can check these docs: https://docs.scrapy.org/en/latest/topics/dynamic-content.html
Okay, thanks. I will check it out
why i cant donlowd flask ??
I checked it out and you can use their API. It will be easy, just use requests
In chrome dev tools you can find requests sent by website:
You can get the one you are interested with and then use requests.get(url), in response you will have json with all data that you need
can somebody help me pls ??
@full frigate Oh, that's nice. I know this might be a lot to ask for but could you perhaps show me the code it would require to get the number 16 from the picture I sent. I am a beginner so I doubt that I will be able to figure it out on my own.
import requests
response = requests.get("https://one-versus-one.com/get-stats-data?first_player_id=834&second_player_id=1548&type=statistics")
data = response.json()
now data is a dict with all information that you need, now you can access it
data in response looks like this
and now you need to access that data you need so:
goals_1st_player = data['ranking']['firstPlayer'][0]['bar-value']
Didn't check if it works but it should
To make your work easier - take that "data" and paste it into some online json formatter. Find where is data you need in this structure and then use python to access it
Damn, thank you so much man 🙂
You're welcome 🙂
What exactly is your problem? Can you describe it?
i cant donlowad flask
Looks like you have issues communicating with PyPI. Try this solution:
pip install flask --trusted-host pypi.org --trusted-host files.pythonhosted.org
type this command in terminal
anyone decent in django, i have a really tough question, been searching for an answer, tried a bunch of different things to no avail
i need a different response on post to a foreign key. the response is the pk, but i need the rest of the fields, not the pk to be returned. It has to be posted with the PK to the foreign key or it wont post at all. and yes, ive even swapped it to a separate class, still cant get it to work and passing the serializer.save through the other serializer and its not working either.
another note, its form data thats passed, so my the normal method of swapping of post doesnt work. so im scratching my head at what to do
i found a work around for now, but seem incredibly stupid to have to re query the db for the response data after a post to get the data i need, but it is what it is i guess
@api.route('/users/<int:id>/timeline/')
def get_user_followed_posts(id):
in this view function, I have a line in code which generate a url
prev = url_for('api.get_user_followed_posts', id=id, page=page-1)
, so here comparing with the "route",
users = api.get_user_followed_posts
<int:id> = id
timeline = page=page-1
☝️ is this all correct?
hi, is it possible to make a django api invisible for users in a browser?
and only be accessed by the front-end?
so basically I would be filtering requests from the front end only
is that possible?
Do you have authentication on for endpoints?
no
I was actually about to try to learn about token authentication, but I thought maybe there is a simpler way
One way is CORS Access Control Allow Origin
actually, I had that setup
I needed to implement it, since the frontend coudnt access the api
but I don't know much about it
Hey everyone, how can I do next/previous post on detail_view page? (django). Cant find info about that, *link on some doc. will be fine for me. *
Did you just set it to allow everyone with * wildcard?
You can use same to whitelist your front end
hmm one sec
Check if this helps
from the front-end?
Server sets it in the response headers
actually, I just noticed I have CORS_ORIGIN_ALLOW_ALL = True in the django setttings.py
is that what's causing it?
That's it.
But AFAIK modern browsers honors these headers
But if you have sensitive data, you should also have authentication
I removed the CORS_ORIGIN_ALLOW_ALL = True and added a CORS_ALLOWED_ORIGINS list, but it still allows me to visit the endpoint on my browser
I am no expert on django
But by chance, are you using DRF or some other app?
Does CORS access control allow origin makes those requests made by frontend invisible? Or does it just disable to send request to backend from "other" hosts?
Maybe it has different way to it
I am not very confident
Hello, I am trying to setup my api (made using django rest framework) so that you can authenticate in two different ways: tokens for another program to interface with it and a session auth for other client browsers. Any ideas for the best way to go about that?
Hi, ive got a problem.
im trying to use a list from python in a js script.
python code:
test=["Zonos", "Reaio"]
return render_template("dashboard.html", test=test)
Html Code:
<p id = "test">test</p>
JS code:
<script>
var test = "{{test}}";
document.getElementById("test").textContent=test;
</script>
output:
"Zonos", "ReAio"
Any clue why it has all these weird characters ?
The result you're getting is because Django templates escape the data, because it is vulnerable for XSS. To render the correct content, you'll need to use a filter:
{{ test | safe }}
safe essentially says "I confirm that this data will be safe and does not require escaping". Just know that this is vunerable to XSS so you need to think about how to secure it.
I use token authentication, I save the user's token within a cookie. You can have two separate authentication methods, but the preferred one (which runs first) must be higher within the middleware list within settings.py
No one should be able to use both
Cheers working now
ie every client will either use one or the other
so there isn't really a preferred one
CORS restricts the origin of the requests to your server. E.g. if you had an allowed origin from the host mysite.co.uk, only those requests will reach your server, and others will be blocked by CORS.
I don't know much apart from that, and I have heard from some pros that CORS should never be depended on as a security measure
in that case does it matter which is first
hmm, to my limited knowledge your requests are passed through your first authentication middleware and if it fails to authenticate, it carries on through your other authentication middlewares
so in that case all of your clients will be authenticated at least one way
I see
Would it make much of a difference performance wise if I was to rewrite that or would it not really matter?
e.g. have a custom middleware?
yeah
i wouldn't see it making a big performance change
you could even just modify an existing middleware, such as token auth
that's nice, I was originally planning on making a custom auth class that determined how a client was authenticating.
I have to write a custom token auth anyway
cool, let me know how it goes, i've been wanting to write some sort of custom middleware soon too just to learn about it
also how exactly does session auth work with a seperate frontend, e.g. react? I have never got my head around it
from flask import Flask, render_template
app = Flask(name, template_folder='../templates')
@app.route("/")
@app.route("/home")
def home():
return render_template('home.html')
@app.route("/about")
def about():
return "<h1>About Page</h1>"
if name == 'main':
app.run(debug=True)
getting jinja2except templatenotfound
anyone can help?
are you sure your template_folder path points to the templates folder?
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.
^ btw
yes
app = Flask(__name__)
@app.route("/")
@app.route("/home")
def home():
return render_template('home.html')
@app.route("/about")
def about():
return "<h1>About Page</h1>"
if __name__ == '__main__':
app.run(debug=True)```
I even tried this
alright, can you show us your file structure?
btw you have an empty app route:
@app.route("/")
you should remove that
I think that is not the issue
How can I?
i am getting it anyhow
How is works python post.get_next_by_created.get_absolute_url in django, i'm getting nothing on detail view all time.
that looks right to me, with the templates in the root folder.
strange. I'm not too familiar with flask but what I'd do is remove the empty app route and re-create the templates folder as thats the default that flask looks for. sorry that i cannot help further with that - not too experienced w/ it
I have a problem with spotipy
Is it possible in any way to authenticate using user's login and password?
Yo
Anyone here use Bottle?
Also why the hell is bottle so slow
like absurdly slow
#help-dumpling please, who know httpie
@turbid estuary don't spam for help in every channel dude
where else would I go for web-dev query
you just wait for someone to help you
on was general channel, and one is web-dev
Also just ask your question
😂 usually on weekends, its rare
I made it specific, "who know httpie", only the ones who knows it would click
what's your question?
That's not actually a specific question
If someone does say yes then you'd ask him the question
no problem thanks:)
he did nothing wrong lmfao
have anyone deployed django code to google cloud ever?
can some here help me
Help, I have a problem with submitting the textarea of a Captcha in Python selenium. Thanks for you time. Here is the Stackoverlowlink for more information: https://stackoverflow.com/questions/66188276/cant-submit-captcha-textfield-python-selenium
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('index.html')
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
#return processed_text
return redirect(url_for('returnit'))
@app.route('/saved_text')
def returnit():
return processed_text
if __name__ == '__main__':
app.run(debug=True)
this returns NameError: name 'processed_text' is not defined
can anyone help
Help, I have a problem with submitting the textarea of a Captcha in Python selenium. Thanks for you time. Here is the Stackoverlowlink for more information: https://stackoverflow.com/questions/66188276/cant-submit-captcha-textfield-python-selenium
-_-
Would anyone be able to help me with a flask_pymongo / jinja2 issue I'm having? I'm able to iterate over multiple MongoDB records, but a single record doesn't show in the template
'''
@app.route('/users/<username>')
def user_profile(username):
users = mongo.db.users.find_one_or_404({'username': username})
return render_template("user.html", users=users)
@app.route('/users/')
def get_users():
users = mongo.db.users.find({})
return render_template("user.html", users=users)'''
user.html template
'''{% extends "base.html" %}
{% block body %}
{% for x in users %}
<tr>
<td>{{ x['username'] }}</td>
</tr>
{% endfor %}
{% endblock %}'''
you're trying to access a local variable (in my_form_post) from another function. The scope does not allow that.
I think I figured it out, I'm iterating over an object that's not iterable
https://stackoverflow.com/questions/55944581/python-flask-jinja2-templating-nested-mongodb-data-cursor-object/55944806
It works if I take out the for loop
i think i figured it out i can use session
im pretty sure
what do you mean by that?
like this @native tide
ah I see
hey my css files are not working
Django?
yeah
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{% static 'main.css' %}">
<title>{{ title }}</title>
</head>```
this is the code
Does it load the same old css?
wdym
Did you define it in urls?
oh no it doesnt
urls??
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
@toxic flame here
Ill check in, if on my pc sometime later
@toxic flame which line??
STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ]```
And you have to move your static directory outside of home
Move your static folder to the location where manage.py is located.
Paste this line under STATIC_URL
also the urls
no
The +static thing?
that's usually for media
But if you dont know how to setup static on deployment, then sure.
Should always have em done together
Hi Every body i face to an issue in django project when i pass an argument more than 9 to my url, it's don't working i have an error NoReverse Match Found
is there anyway I can load in an embed iframe without letting it use the current cookies for that site that is current stored?
right now i have an embed on my site that is able to access the login session of that i am already logged in with on the main site
but i dont want it to have access to those cookies
re_path(r'^edit_planification/(?P<pk>\d)$', views.PlanificationUpdate, name='edit_planification'),
when pk is more than 9 it's KO and manually i've the same probleme
so if i POST url http:// ...... /edit_planification/1 (to 9) it's ok
@toxic flame it works thx
and when i POST url http:// ..... /edit_planification/10 (or more) it's KO
someone had and idea ?
Hello, i have this ```py
users = ['d']
@app.route("/")
def home():
with open("index.html", "a") as file:
for a in users:
file.write(f"<h1>{a}</h1>" + "\n")
file.close()
with open("index.html", "r") as f:
x = f.read()
return x
I want it to be displayed as is the squarre in the middle of the site
can anyone help me?
owo
Hi, got a problem.
I have a list that i converted to json but cant get the first value.
<script>
var bot_names = "{{ bot_names_filtered | safe }}";
//^ should equal ["zonos", "reaio"]
document.getElementById("test").textContent=bot_names[0];
</script>
Output = [
Maybe don't put it inside ""
Since it's [ which is hypothetically the first index of a string
even if i did [2] it just does the first character of the string
Have you tried taking it out of the "?
var cars = ["Saab", "Volvo", "BMW"];
This is how an array in js is
No ""
do they not ?
@random lava That is not correct
You should have this:
let bot_names = {{bot_names_filtered}}
Because when you use {{}} inside "" the value gets rendered as a string, its basically the same as str(bot_names_filtered) or bot_names_filtered.toString()
Or another option you have is this:
let bot_names = JSON.parse("{{ bot_names_filtered | safe }}")
This one is what I like more ^^
@toxic flame This is the correct approach
yea i said remove the "
I think this is the best
hey ah i am gonna need to make a db that can be accessed outside my website so should i use ORM
or use a proper db like postgres
hey can anyone help me out. i need to make a custom system for my django website
custom user forms, no ORM and i should be able to access the db from outside of the website
An ORM is just a translation layer, even if you use the ORM in Django (which you should), you can still directly access the database via the Python Postgres or MySQL client depending on your setup. @muted stump
Django < translation layer > ORM < connection > Database < connection > Other Python Programs
Hello. How to do a progress-bar for the client on server-side unzipping of images from uploaded archives? #help-mango
\d+
i see that is good
@muted stump The better pattern is to create a REST API so that the applications that need to modify the database write via the Django models. If you need to just read the data, straight out of databases works.
hey how can i get data from user to my django things
Wot
how come the auth token doesn't change in django?
as I understand, every time a new request has been made, a new token is generated, or have I mistaken something?
how to use sessions in django
