#web-development

2 messages · Page 114 of 1

native tide
#

I run my webpages just using python -m http.server 8080. I guess I could just actually make some server side scripts but it'd be nice if I could have a way to just shove it into the html and just use like eval() since I only will be evaluating my own source code, not user input

frozen python
#

What’s the terminal commands, to run to create a “main.html” file? By the terminal?

obsidian rain
#

can anyone tell me how can i start web development

#

please dm me

jade lark
#

Hello. Tried to use retrieve a product by id but Im getting an error.

@app.route('/product/<id>', methods=['GET'])
def get_product(id):
    if id is None or not id.isdigit():
        return jsonify({'result' : 'Missing ID!'}), 404
    return Product.objects(id=id).first()```

@slow rapids
Try casting it to an int first. As well with mongo you may need a library to help if that's not working either.

#

So I'm trying to learn web development off a book that works with html, js, and php. The problem being php is dated. Is there a way I can use the <?> tags but put python in it instead to run server side?
@native tide
PHP was originally just for templates. You can use something such as Django, or Jinja2 with Python. However, it is good practice to keep your logic separated from your templates. This also includes PHP. If you're wanting to really perform calculations and logic on a page look at using JavaScript.

warm igloo
#

What’s the terminal commands, to run to create a “main.html” file? By the terminal?
@frozen python To just create the file? touch main.html

frozen python
#

@frozen python To just create the file? touch main.html
@warm igloo do I need to CD into anything?

warm igloo
#

I mean .. depends on where you want the file created. touch main.html will create it where you are.

native tide
#

good idea @jade lark I'll probably do django development after I can figure out angular and dbms. Thank you for your input

frozen python
#

@warm igloo thank you, can you also use console to write code? as in a import already and things like that?

warm igloo
#

this is all on *nix btw, I have no idea on windows

frozen python
#

@warm igloo thank you. Well, I’m asking as in I want to have some code automatically added into a page like urls.py, so I can add it from the console on some things

slow rapids
#

@jade lark im using mongo_engine. Thank you for the suggestion

jade lark
#

@jade lark im using mongo_engine. Thank you for the suggestion
@slow rapids Ahh that would make more sense. Well I won't be much help on that.

#

good idea @jade lark I'll probably do django development after I can figure out angular and dbms. Thank you for your input
@native tide
If you're using Django you'll just need to learn the ORM for dbms.

As well if you're doing simple logic just using plain old javascript would work just as well too. Depending on the size and complexity of your application. I would start with Django first and go from there.

native tide
#

^^ Handle the backend stuff first and then implement frontend

#

And React would be good for that 😉

#

@jade lark really I'm just learning to work with different things first don't have a project in mind. I just want different options at my disposal

jade lark
#

@native tide Best way to learn is to pick a project and work on it. Plus finishing something from start to finish is a good way to build a portfolio

haughty turtle
#

request.method == 'POST': how does this work o.o

slow rapids
#

@jade lark may i also ask what is the best way to see if a request response is a json? In my case thr request is done inside the endpoint with requests.get(url)

jade lark
#

@jade lark may i also ask what is the best way to see if a request response is a json? In my case thr request is done inside the endpoint with requests.get(url)
@slow rapids

Check the response headers. Specifically the Content-Type

slow rapids
#

Yeah i also thought of that but thought there would a way to parse the text and understand if it was @jade lark

#

Tried googling but didnt find much so i am asking

jade lark
#

json.loads or json.dumps possibly? You'll need to have exception handling if it tosses a ValueError.

#

Then checking if a certain key exists or all of them. You could make a helper class or function to validate the data.

slow rapids
#

Ok thank you for the suggestion

jade lark
#

You're welcome hopefully it ends up helping.

lunar light
#

for the requests library, .json() does json.loads for you and it's a bit easier esp. since you don't need to import json

#
res = requests.get(url)
try:
    res.json()
except ValueError:
    print("is not json")
else:
    print("is json")
modest scaffold
#

do widgets work for password fields in django

swift sky
#

hey guys im really stuck on this socketio problem

#

im hoping someone can help

#

i was working on a chat feature for my web app, however i had to remove the pytho logic, and i moved the html/jquery file outside of my project directory

#

the issue im having is that socketio is still making continuous polling requests everytime i run the app

#

even though there's no longer any socketio logic in the script!!!

frozen python
#

I created fields with the serializer in DRF, but, only “name” comes up as a field to enter. I also have “description” as a field, but it’s not a choice to enter in anything.

swift heron
#

I have this in my base.html template for referencing my javascript file
<script rel="text/javascript" href="{% static 'base.js' %}"></script>
Would this be the correct way to do so?

#

ahh its different from the css import by using src instead of href makes sense

dawn heath
solemn stream
#

anyone know if you can use pyinstaller with django?

#

to just run a local server

haughty turtle
#

Oh cool so that's what the the request does in Django, it's an await function for GET and POST. O.o

tired axle
#

im creating an app that turns a link from pdf to csv.... im trying to host it on ElasticBeanstalk... is the best way to save it on EBS, then convert, then download it.. Or can the conversion be Realtime, and skip the step where i need to save it somewhere... ?? any ideas?

elder nest
#

here is my code ```from quart import Quart
from discord.ext.ipc import Client

app = Quart(name)
web_ipc = Client("localhost", 8090, "TOKEN")

@app.route("/")
async def show_guilds():
guild_count = await app.ipc_node.request("get_guild_count") # Make a request to get the bot's IPC get_guild_count route.

return str(guild_count) # return the data sent to us.

@app.before_first_request
async def before():
app.ipc_node = await web_ipc.discover() # discover IPC Servers on your network

if name == "main":
app.run('localhost', port=8090, debug=True)
but when I try to run sometimes it says File "web/web.py", line 15, in before
app.ipc_node = await web_ipc.discover() # discover IPC Servers on your network
AttributeError: 'Client' object has no attribute 'discover'and other times it says thisOSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions``` I am trying to attach this to a discord bot using a module called discord.ext.ipc and here is my code from there

#
from discord.ext import commands

# Our bot will be the server we make requests to in order to get data from it.
from discord.ext.ipc import Server

class Bot(commands.Bot):
    """Main bot class"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def on_ipc_ready(self):
        """Event dispatched upon the IPC being ready"""
        print("IPC ready")

    async def on_ready(self):
        """Event dispatched upon our discord bot being ready"""
        print("Bot ready")

bot = Bot(command_prefix="!", case_insensitive=True)
bot_ipc = Server(bot, "localhost", 8090, "TOKEN")

# ipc.server.Server takes four arguments: the bot object, the port to run the IPC on, and a secret key used to authenticate client connections (seen in the web server file).

@bot_ipc.route() # if no name is supplied in ipc.server.Server.route, the function name will become the route name.
async def get_guild_count(data):
    """This route named get_guild_count will return the amount of guilds our bot is in"""
    return len(bot.guilds)

if __name__ == "__main__":
    bot_ipc.start() # ipc.server.Server.start will begin the IPC
    bot.run("TOKEN") # run the bot as usual```
haughty turtle
#

Hmm trying to use PayPal Python SDK and I have a create request and capture request, they both only check if the request method is POST, other than that how does it differentiate if the POST is meant for create or capture

torpid pecan
#

I used "git clone (github address)" to download my files onto my server but what command do I use to update them after making another change? It tells me I cant use "git clone"command again because that file already exists.

tired axle
#

woudnt it be sudo apt update?

#

do a 'sudo find 'file', see if it exists .. Then delete it... if it does and you dont need it.. otherwise, maybe make a new directory and try again

warm igloo
#

You would use git pull to bring down your changes @torpid pecan

torpid pecan
#

Awesome, that worked 👍

limpid cave
#

Hey everyone 👋 .The question I have today is what do you do to minimise risk that may occur due to human error because you are using an unfamiliar language/ new language As software developers? The only answer I can think of testing and reading from the official documents that is it

warm igloo
#

If you're new to a language, but familiar with another, try to make sure to apply similar patterns of development. So, if you know good security habits for one language, try the same patterns. Look up the version of the pattern in that new language and it will help you understand the new lang better because you've tied it together by concept.

I've even taken old code I wrote in one lang, and translated it to another. It gave me that bridge of understanding.

#

And if by risk you mean specifically security risk, you can also minimize risk/errors by using SAST and DAST scanning of your code and running application.

If its a web app, make sure to run it through something like ZAP to test for OWASP top ten.

limpid cave
#

Thanks for the answer that makes total sense, and I've also learned something new do with security testing

dawn kestrel
#

hello, i'm a newbie using django and i have a problem that cannot solve.
In my createview i need to select from the dropdown the object car that has the field is_active = true,
how can i acomplish that?

class Car(models.Model):
brand = models.charfield(...)
is_active= models.BooleanField(default=True)

class Service(models.Model):
car = models.ForeingKey('Car'....)
name = models.Charfield()

class ServiceCreateView(CreateView):
model = Service
form = ServiceForm
...

If i change the field is_active to false in Car model, should not be shown in the dropdown.
can someone put me in the right direction?

jaunty sedge
twilit needle
#

Hello

#

So I use django for my backend

#

and React-js for my frontend

#

this is my react-js component. I want to insert the user's username and some other properties of user into it. How can I get this information from the backend?

#
import React, { Component } from 'react';
import '../../css/app_style.css';


class StatusBar extends Component {
    render() {
        return (
        <div class="status-bar">
            <div class="status-container">
                <div class="label-container">
                    <label class="username">Test Username</label>
                    <label class="personal-name">User's real name</label>
                </div>
                <img src='staticfiles/assets/users/default.jpg' class="user-avatar"></img>
            </div>

            <div class="config-container">
                <button type="button" class="logout-button"><i class="fa fa-sign-out"></i></button>
                <button class="settings-button"><i class="fa fa-gear"></i></button>
            </div>
        </div>
        );
    }
}

export default StatusBar;```
#

pls ping me when help

#

thanks!

native tide
#

@twilit needle develop a RESTful API on backend which is consumed by your frontend

#

then use axios/fetch to hit the endpoint, get results, and show them

torpid pecan
#

How can I "git pull" an old github commit

halcyon lion
#

git checkout [revision].

#

Boys is there any convention on how many fields a django model should have?

stable kite
#

Boys is there any convention on how many fields a django model should have?
@halcyon lion i think no

torpid pecan
#

Should I have my virtual environment inside or outside of my repository?

halcyon lion
#

depends what u are using 😄

#

some libraries can give you problems due to difference based on the OS ppl are suing

#

using*

urban ferry
#

I made a site with python, a very small one for testing from my pc, can I connect from my mobile phone or some other device, why can't I connect?

mint folio
#

@urban ferry Where is this site running?

urban ferry
#

in my pc

native tide
#

with DRF whenever you want to update the information of an object within a database, would you still use a serializer? I am finding myself just doing it manually when I only want to update 1/2 fields of an object. Is this okay?

stable kite
#

with DRF whenever you want to update the information of an object within a database, would you still use a serializer? I am finding myself just doing it manually when I only want to update 1/2 fields of an object. Is this okay?
@native tide yes you can use serializers

native tide
#

And what benefit would that give when you want to just update the fields of an object partially?@stable kite

stable kite
native tide
#

I know... but that doesn't really provide any benefit except for running validation and whatnot (all my request validation is done on the frontend too, so that doesn't matter).

stable kite
#

@native tide wdym i didn't understand your question

native tide
#

Essentially...

Why should you use serializers VS just using request.data and updating an object?

It's probably just a trivial thought which doesn't matter but I just found myself to not be using serializers, e.g. when deleting objects, or updating a field or two. I would just use request.data

stable kite
#

@native tide we use sterilizers because they convert json into Model Objects

#

so that you don't need to do it manually

native tide
#

I don't think you're understanding what I'm asking, it doesn't matter anyways. Thanks

native tide
#

hi

#

is this for django ?

#
class MedarbetarPalListAPIView(generics.ListAPIView):
    queryset = Person.objects.filter(quarantine__isnull=True).exclude(first_name__contains='Doktor').order_by(
        'first_name')
    serializer_class = ListParametricMedarbetarPalSerializer
    authentication_classes = (HSAIDAuthentication, TokenAuthentication,)

    def get(self, request, format=None):

        unit = request.GET.get('unit', None)
        group = request.GET.get('group', None)
        type_ = request.GET.get('type', None)
        work_categories_ = request.GET.get('work_categories', None)
        query_ = request.GET.get('query', None)

        name_query = self.queryset.objects.all()
        print(name_query)

        # Construct query with Q objects
        q_objects = Q()

        # Add the filter if the attribute wasn't specified or it wasn't specified using a star (*)

        if query_:
            q_objects.add(Q(first_name__icontains=query_), Q.AND)

        if type_:
            q_objects.add(Q(type=type_), Q.AND)

        if unit:
            q_objects.add(Q(person_unit__unit=unit), Q.AND)

        if group:
            q_objects.add(Q(group=group), Q.AND)
        
        if work_categories_:
            q_objects.add(Q(person_unit__work_categories=work_categories_), Q.AND)

        # Get all threads according to filter
        # prefetch and select related for increase DB performance
        serializer = self.serializer_class(
            self.queryset.select_related('group', 'type').filter(q_objects).order_by('first_name').distinct(),
            many=True)

        return Response(serializer.data)
#

im trying to add query serch

#

combine first_name and last_name in model taken from query just below class

#

models.py


class Person(models.Model):
    first_name = models.CharField(max_length=127, blank=True, null=True)
    last_name = models.CharField(max_length=127, blank=True, null=True)`
#

i figured how to add query request ... but not sure how to use it with 2 fields from model

#
---
if query_:
            q_objects.add(Q(first_name__icontains=query_), Q.AND)
#

It should search by contains with a combine of first_name and last_name

#

e.x. Lara Croft ... search for "cro" and "la" should show Lara Croft

#

how to combine fields in views ?

#

searchset = Person.objects.all() = all objects

#

filter ?

#

Hello ?

#

like say i have a Person her name is Susanna Lindberg

#

if i search for lindberg susanna it should show up

#

or if i search for lind sus

buoyant leaf
#

I have a question why do you use Python not Javascript

native tide
#

In flask projects do routes go in a different file? Or how is it suppose be structured?

#

Any examples?

#

I understand that routes can return template or a html, but what if a route needs to communicate with an API/DB or do some extra work. Where would logic for this go?

coral raven
#

what does sqlalchemy.func.coalesce() do?

cosmic aspen
#

please , in the official django documentations , there is this code

#

def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output)

#

how does this join method works? it's a bit weird , a for loop in the iterable

worthy lake
#

It is a list comprehension, which is a syntax that produces an iterable. The join method works the same as it does with any iterable.

#

[q.question_text for q in latest_question_list] is a powerful feature that produces a list called a list comp

cosmic aspen
#

ah ok i see

#

thank you

worthy lake
#
l = []
for q in latest_question_list:
    l.append(q.question_text)

@cosmic aspen

#

that is whaat it meaaans

cosmic aspen
#

kinda simple when you understand the purpose

#

thank you

worthy lake
#

its hands down the most useful thing in python imo

cosmic aspen
#

yeah , i literally said to myself "Who's the genius behind this sorcery"

worthy lake
#

theyre even more powerful than that. You can include conditionals in there as well

l = [q.question_text for q in latest_question_list if q.pk % 2 == 0]

#

You can do list comps inside of list comps, if your iterable is also a list comp. There are also dict comps

cosmic aspen
#

i see , holy cow i feel smart

#

i'm a genius now

worthy lake
#

Its kind of a breakthrough in assembling the data you need when you realize its a thing

bronze blaze
#

good afternoon

#

guys, I know html

#

is that good or bad?

limber laurel
#

How could I practice/learn deployment?

bronze blaze
#

you can create web apps and deploy them on Heroku

limber laurel
#

Alright

worthy lake
#

In addition to heroku, you can also spin up VM servers locally if you have a computer that can handle thata. It wont allow you to easily put the sites online, but... it will teach you to configure a production server with all the things needed for it to work.

#

And... you can use it as a local network server more easily at that point.

warm igloo
#

Deployment is a LARGE term

to a VM?
to baremetal?
to kubernetes?
to swarm?

then, dev, staging, or prod?

do you want to do pipelines with ci/cd, do you want to sftp files, do you want to rsync them?

worthy lake
#

yeah thats true. They start to call it DevOps at that level of sophistication.

#

But you got to start with just pushing to a server that either is in production or works the same as one that actually is.

#

I find rsync to be pretty awesome when working with local VMs

#

Thats really the only experience i have with devops other than heroku

warm igloo
#

if you do end up wanting to do local vms, check out proxmox or even just virtualbox

worthy lake
#

yeah virtualbox is what i use

warm igloo
#

should be building a proxmox cluster across 6 thinkcenter mini-pcs soon

worthy lake
#

never used proxmox...

#

not sure what that is.

warm igloo
#

it's a open source competitor to VMWare/ESXi

worthy lake
#

Mine are mostly test servers. Ah okay.

warm igloo
#

so legit vm operating system with all the things you could want

worthy lake
#

is virtualbox not a fully featured hypervisor?

warm igloo
#

monitor all your vms, freeze them, copy them, etc

worthy lake
#

virtualbox is all i know

warm igloo
#

virtualbox has limitations AND it runs ontop of your OS where ESXi or proxmox ARE the OS

#

so closer to the metal

worthy lake
#

I see.

warm igloo
#

check it out sometime if you want to grow your skills in that dept (managing vms) as you get way more control over the vms, the resources they use, their volumes, etc and is closer to what you'd use professionally

worthy lake
#

Cool, Ill check it out. My major issue with VMware was that it was proprietary and not accessible when i tried it.

#

So ill do that next time i need to

warm igloo
#

they do have a free version you can use to learn, but there are some limitations, but in the homelab world most people recommend proxmox as it is open source and you'll learn the same things

Also, if you don't know about the homelab hobby like I didn't earlier this year .. checkout out r/homelab on reddit sometime. And good luck to your wallet/free time. Haha. 😉

#

thankfully I got free hardware from work to do some stuff like those 6 thinkcenter pcs, but I've also created a kubernetes 5 node cluster on raspberry pi 4s using a laser cut blade-server chassis.

And now we're not talking about web development so I'll stop

worthy lake
#

yeah, unfortunately, I dont have the money to run a home server room haha. I like the idea but it seems unrealistic for me.

worthy lake
#

Is there a way to change path('accounts/', include('django.contrib.auth.urls')), to a different end point when using those generic auth views? For example, I can change that to path('users/', .... but, this doesnt change the fact thaat all the other views loaded in by that include still use 'accounts/'

#

For now im just going to leave it. I can learn more by not changing things constantly, but I still would like to know.

#

ah, the way you do it is right there. You just explicity call all of the views insteada of using include

somber aurora
#

There are tons of Anime API 's but not all them have good documentation

#

Who can give me a good one

swift heron
#

@somber aurora you could probably use something like imdb or some 3rd party api and sort out the database with tags that only have animation

#

so for ajax how would I make a post request that would fire off a function in my views.py (django) here is what I have so far

$(document).ready(function () {
    $(".btn").click(function (event) {
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:8000/computer/test",
        });
    });
});

views.py

def computerView(request):
    context = {'title': 'Computer Stream', 'applications': computerStream.applications}

    def test():
        print("Hello!")

    return render(request, 'pages/computer_view.html', context)

I know this probably isnt near correct since I dont have a url that is localhost/computer/test it is only localhost/computer and I have never seen a function inside of a function before but that is what it looked like in the various stackoverflow posts I have been viewing. so what do I need to change to get that jquery post run the test function? @swift heron if you reply thanks!

granite loom
#

css:

.container{
    width: 80%;
    margin:auto;
    border: 5px red solid;
    padding:0px;
}

html:

    <div class="container">
        <div class="box-1">
        <h1>Hello There</h1> 
        <p>
            Lorem ipsum dolor sit amet consectetur,
            adipisicing elit. Nisi enim nemo
            doloremque placeat excepturi quasi natus
            maiores inventore nostrum totam.
            Saepe nemo ullam iure illo, minus quasi enim
            atque porro!
        </p>
        </div>
    </div>

hey this is making it like this.
what I want is make the top and bottom look the same as the left and right side.
how can I do that?
please happen to ping me for an anser

#

I want it to look like this

outer apex
#

@granite loom Check out the padding CSS property

outer apex
#

If you set the padding for .box-1 as 1px, it fills the space within container.

granite loom
#

@granite loom Check out the padding CSS property
@outer apex but I why was the thing that I was doring not working?

outer apex
#

Also certain tags have default margins. H1 and p tags for example.

native tide
#

@swift heron in your AJAX request you could add a header (such as test:1) and then in your function, check for this header, and if it is there, run test()

granite loom
#

This is the structure of my folder, home.html is inside the html folder, and I am trying to link style1.css to it.
this is how I am currently doing it

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
        integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
        crossorigin="anonymous" />
    <link rel="stylesheet" href="style/style1.css"> 

but it isn't linking it, does anybody know how I can fix that?

#

please happen to ping me for an answer

viscid gulch
#

You have to remove the font linking it is incorrect @granite loom

granite loom
#

ohh, np i got it

viscid gulch
#

What is it

#

The fix?

#

Hey

#

@granite loom

granite loom
#

ohh i just did ../style/style1.css

viscid gulch
#

👍

#

K bye

granite loom
#

cya

granite loom
#
.button {
  transition-duration: 0.4s;
}

could someone explain to me what this is doing?
Cause i don't understand
please happen to ping me for an answer

native tide
#

@granite loom that the transition will have a duration of 0.4s

granite loom
#

oh thx

vale orbit
#

anyone know any good tutorials for gRPC in python?

#

I wish to experiment with APIs using gRPC, but I want to make sure I have a solid foundation first. All of the tutorials I could find were for Go or Java.

#

Unless the gRPC functionality is identical to one of the above.

cold zephyr
#

What are some nice css frameworks for a personal website?

#

Static site

#

Are there alternatives (not necessarily latex theme but just sort of a minimal css lib

native tide
#

Does the popup suit?

swift sky
#

has anyone worked with flask socketio

#

anyone have any experience with that? I'm abit confused about how eventlet fits into all this, and how the flask server handles sockets

swift sky
#

idk but it sounds like you might need to disable mime checking

toxic flame
#

Is there a way where i can display live database modifications on django without reloading the wrbsite?

swift heron
#

@native tide so is a header what is used to specify the function you want to run?

halcyon lion
#

anyone knowledgeable on django/html wanna hop on a voice call. I need some help on how to setup a search funcion 😦

hybrid patio
#

Hello

#

I have problem with Flask ...

#

and jinja templates

#

gyus??

native tide
#

@swift heron no... why do you have a function inside a function anyway? Can't you just seperate the endpoints?

#

Headers are just part of the request

#

But in your request you can send JSON

swift heron
#

yeah I was just going by an example on stackoverflow I didnt understand it either but this is all new territory

native tide
#

Are you using React?

#

JS, i mean

swift heron
#

yeah Jquery

native tide
#

So in your request, you can include JSON. Such as {test: true} then in your function, you can see whether test is true (therefore running the 2nd function) or if it's false not running the 2nd function.

#

It would probably be easier if both of the functions were part of a class, too

#

@hybrid patio What's the issue?

#

@halcyon lion Best to do that with JS, I'd recommend React and having some backend APIs

halcyon lion
#

@native tide i am dumb

#

just had the form name wrong in my view

#

and it works fine now :d

#

it says results in bulgarian 😄

swift heron
#

okay I think I have an idea of what is happening let me try this one second

native tide
#

Also, what is the point of the view in the first place? You're making a POST request to a regular view, not an API endpoint. Am I missing something?

swift heron
#

so here is what I am thinking

        $.ajax({
            url: '127.0.0.1:8000/computer',
            type: 'POST',
            json: {test: true}
        });

Which when somebody goes to 127.0.0.1:8000/computer
A requrest will be sent to my views function to load that page

def computerView(request):
    context = {'title': 'Computer Stream', 'applications': computerStream.applications}

    if request['true']:
        print("Fired!")


    return render(request, 'pages/computer_view.html', context)

But I am checking the request json if the value is true and that is how I communicate from the frontend to the backend?

This example dosent work but is this the general idea?

#

I am trying to run a function is all

native tide
#

Yes that's the general idea. But it will have to be within an API endpoint, not a regular view.

Also it would be if request.data["test"] == true: in Django

swift heron
#

can you show an example of an API endpoint?

native tide
#

Do you know of DRF?

swift heron
#

nope havent seen this yet

native tide
#

That'll be essential for you to learn if you want to start implementing communication between a seperate frontend and your Django backend

swift heron
#

Alright great ill get started on it then

native tide
#

An example API endpoint is similar to a view, they vary, this is a function based view:

@api_view(["POST]) # means this function only handles POST requests
def example_view(request):
   if request.data["true"] == 1:
      print("fired!")
swift heron
#

okay thanks im going to research this more and ill give it a shot you have been a great help thanks!

lavish canopy
#

Hello everyone!

#

I've been needing some help with a few things and don't really know where else to turn

#

I've just got a new machine, installed VS Code, Installed Node JS, messed with the settings since the bloody thing couldn't find the python .exe file, got that to work and finally got to the point where I can install django

#

Problem is, when I activate pipenv (pipenv shell) I don't see that the environment is activated like (environment_name)User@USER in my terminal

#

I'm attempting to take all the jQuery off of the django install and use VUE instead, in order to do that I needed to do some bollocks npm install vue or whatever

prisma jackal
#

I have models.TextField() in my model but I want that only few characters to be seen in my browser, how can I achieve that? Django

swift heron
#

@native tide so reading through this documentation and watching videos it seems we are taking the data and putting it into a model (fancy class) and from there we serialize that data to a database? from this point our frontend can get/post data to that database and our backend can work with the database? is that the basic idea or am I spitting out nonsense?

stone basin
#

I’m trying to make a server that serves a static html file using django.
Is there any way I can just send that file without dealing with templates and stuff?

dapper tusk
#

you could host it as a static file, similar to an image, and send it from the view using whitenoise.

#

don't think the builtin staticfiles can serve in deployment

prisma jackal
#

@prisma jackal {{ value|truncatechars:7 }}

errant spear
#

I am working with flask jwt extended and have a login route that looks like this:

@app.route('/Login', methods=['POST'])
def login():
    try:
        user = get_user_from_db(request.json['email'])
        password_correct = check_password_match(request.json['password'], user.password)
        if password_correct:
            access_token = create_access_token(identity=request.json['email'])
            refresh_token = create_refresh_token(identity=request.json['email'])

            resp = jsonify({'login': True})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp, 200

and a refresh route that looks like this:

#
@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    return jsonify(access_token_cookie=create_access_token(identity=current_user)), 200
#

But, I get a Missing CSRF token message

#
app.config['SECRET_KEY'] = os.getenv('JWT_KEY')
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
app.config['JWT_CSRF_IN_COOKIES'] = True
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(seconds=10)
#

I set my CSRF in cookies true

#

I checked my cookies to make sure they exist

toxic flame
#

cloritexcalcium

native tide
#

Anyone know a library for working with microsoft's oauth2

native tide
#

@swift heron that's correct!

Serializers translate the request data (from JSON to Python), which can then be saved to represent an object in the database.

A ModelSerializer serializer tries to replicate the model that it is linked to. I'd recommend using that.

swift heron
#

okay great, just working on having jquery grab that data now but I havent looked to much into it yet

night atlas
#

hi

#

im newbie in python

#

im learning GUI now can someone teach me

shell heath
#

@night atlas There are good resources online. Just follow the tutorials for a couple of projects and you will be good to go. I actually prefer books, but the content can be daunting. So tutorials is a good way to go about it. Deciding on which library you want to learn is a harder task. I started from tkinter and moved on to pygame. There's pyqt5, wxpython and many more. Also, try out your own projects once you finish the tutorials. This will be the fun part!

sonic cedar
#

@shell heath Do you know about python turtle ?

shell heath
#

I haven't used it explicitly, but I know it.

#

@sonic cedar But haven't touched turtle since I learnt pygame.

sonic cedar
#

@shell heathCan I speak with you in private?

shell heath
#

@sonic cedar Sure

sonic cedar
#

ok

#

@shell heath accept friend ._.

night atlas
#

@shell heath so what should i mastering first? the GUI one or the basic one first

shy finch
#

any python web developer here? I need to ask some question...

#

not about coding, pls dm me if there is a Python web dev

hybrid patio
#

Good morning

#

It is anyone there?

shy finch
#

Good Evening..

#

anyone?

jovial fractal
shell heath
#

@night atlas If you know basics of coding, you can jump to gui to solidify your fundamentals. If not go over the begginer tutorials and try to master the basics first. Python Crash Course is an excellent book to start with basics and small scale projects

shy finch
#

can anyone help me with a question?

night atlas
#

@mellow shaleytyn

#

@shell heath Can u acc my friend req

#

nah ty

shy finch
#

Q: I want to learn pyhton web develeopement, so do i need to learn HTML, CSS, JAVA for web design?

shell heath
#

I'm not a web developer by any means, but I learnt a bit of html and css before jumping into django. So yea, knowledge is never harmful

shy finch
#

Yeah i know html css

#

but do i need to learn it advanced?

#

or when i work someone will do that for me?

placid vale
#

Q: I want to learn pyhton web develeopement, so do i need to learn HTML, CSS, JAVA for web design?
@shy finch yeah if u want to work in frontend

#

but do i need to learn it advanced?
@shy finch or if u dont want learn advance u can learn there frameworks like bootstrap

primal kernel
native tide
#

@swift heron Idk how it is with Jquery, but making requests from JS is really simple with axios and it's promise-based.

#

@primal kernel It looks like you're going to need to connect your models, right? Possibly set up a one-to-many relationship between "Courses" and your other models so you can access them directly.

primal kernel
#

They are connected, every consumption is related with a client and a course

native tide
#

@prisma jackal you can set a max-length to the textfield

#

Oh I see

#

So your course only has one field, its name, what attribute determines the number of courses sold?

primal kernel
#

Every consumption has a course associated, what I want is get the best selling courses, like: Course 1 1020 sold, Course 2 992 sold and so on

#

Like 1020 consumptions has that course associated

#

I think I could do it in 2 steps but I dont think that's the most elegant way to do it

native tide
#

Is "Consumptions" the orders of the course?

primal kernel
#

yeah

native tide
#

Could you do: (just paraphrasing)

courses = Consumption.objects.filter(course) # This gets you the list of courses
# Loop through the courses and sort by 10 most occuring.```
hybrid patio
#

FLASK ?? someone to help me ??

native tide
#

You could setup a "amount_sold" or similar in the course model

#

and that would make it much easier

#

@hybrid patio Ask the question instead of asking to ask

hybrid patio
#

ok but I have problem with templates

primal kernel
#

Yeah I could do that, i could get what I want in 2 steps

#

But thats not the best way

hybrid patio
#

I dont understand I have everthing good

primal kernel
#

Anyway @native tide thank you so much for helping me, I think that I will do it in 2 stems till I get the knowledge to do it in a different way

hybrid patio
#

{% extends "_main.html" %}

{% block title %} Article {{ id }} {% endblock %}

 {% block body %}

     <h2>{{ value.title }}</h2>
     <p>{{ value.content }}</p>



{% endblock %}


#

article file

native tide
#

Yeah looping through the queryset isn't a good option, but ideally you would add a new column to the 'Course' model such as orders , and you can use decorators such as @post_save to increase the orders every time a Consumption is added. Then you can simply and quickly sort it.@primal kernel

Or add the order_numer to the Consumptions model and do the same.

#

@hybrid patio Show us the view

hybrid patio
#

view? what do you mean?

native tide
#

The function which is rendering that page

#

{{ value.title }}

#

value is undefined

hybrid patio
#

wait

native tide
#

and that is being passed from the view (or the function if you will)

shy finch
#

@shy finch or if u dont want learn advance u can learn there frameworks like bootstrap
@placid vale Bro I am trying to learn DJANGO so do i need to learn HTML, CSS, JS, etc?

hybrid patio
#

{% extends "_main.html" %}

{% block title %} articles {% endblock %}

{% block body %} This page uses for something ...  {% endblock %}

{% block foot %}
    {% if articles %}
        <ul>
            {% for id, value in articles %}
                <li>
                    <h2>{{ value.title }}</h2>
                    <p>{{ value.content }}</p>
                </li>
            {% endfor %}
        </ul>
    {% else %}
            <p>No articles</p>
    {% endif %}
{% endblock %}

#

vaule is define in loop

#

this is another file

#




from flask import render_template
from flask import Flask
from .data_base import articless

app = Flask(__name__)

@app.route("/")
def welcome_page():
    return render_template("index.html")

@app.route("/admin/")
def admin():
    return render_template("admin.html")


@app.route("/about/")
def about():
    return render_template("about.html")

@app.route("/articles/")
def articles():
    return render_template("articles.html", articles=articless.items())


@app.route("/articles/<int:art_id>")
def article(art_id):
    article = articless[art_id]
    return render_template("article.html", article=article)


native tide
#
{% extends "_main.html" %}

{% block title %} Article {{ id }} {% endblock %}

 {% block body %}

     <h2>{{ value.title }}</h2>
     <p>{{ value.content }}</p>



{% endblock %}
#

But here it isn't

hybrid patio
#

Yes I take from articles.html

native tide
#

@shy finch For a simple project all you need is HTML

hybrid patio
#

what?

#

ah sorry 😄

shy finch
#

@native tide Thanks bro but what about advanced project?

native tide
#

@hybrid patio Which function is linked to this code snippet, which one is rendering this:

{% extends "_main.html" %}

{% block title %} Article {{ id }} {% endblock %}

 {% block body %}

     <h2>{{ value.title }}</h2>
     <p>{{ value.content }}</p>



{% endblock %}```
hybrid patio
#

@app.route("/articles/<int:art_id>")
def article(art_id):
    article = articless[art_id]
    return render_template("article.html", article=article)

#

this one

native tide
#

And that HTML code block is your whole page?

#

You're not specifying value

hybrid patio
#

nono

#

this is articles

#

and template

#

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href={{url_for("static", filename="css/main.css")}}>
    <title>{% block title %} {% endblock %}</title>
</head>
<body>

    <header>
        <h1><a href="{{ url_for("welcome_page") }}">Tomas Balbinder</a></h1>
    </header>
    <nav>
        <ul class="nav">
            <li><a href="{{ url_for("admin") }}">Admin</a></li>
            <li><a href="{{ url_for("about") }}">About me</a></li>
            <li><a href="{{ url_for("articles") }}">Articles</a></li>


        </ul>
    </nav>

    {% block body %} {% endblock %}

    <foot>
        {% block foot%} {% endblock %}


    </foot>
</body>
</html>


#

articless = {

    1: {
        "title": "HELLO WORLD!",
        "content" : "This is a article about..."
    },

    2: {
        "title": "HELLO WORLD!",
        "content": "This is a article about..."
    },

    3: {
        "title": "HELLO WORLD!",
        "content" : "This is a article about..."
    },
}
#

and articless in articles

#

and I would like to show one article when i write url /1

native tide
#

so it would be

{% extends "_main.html" %}

{% block title %} Article {{ id }} {% endblock %}

 {% block body %}

     <h2>{{ article.title }}</h2>
     <p>{{ article.content }}</p>



{% endblock %}

and you'd pass ID too

#

@shy finch For an advanced project sure, but if you have never used Django or JS or HTML why think about an advanced project

hybrid patio
#

id is wrong right?

#

article no value ?

native tide
#

Idk what you're saying

shy finch
#

@native tide just wanted to know

hybrid patio
#

WOW

#

works

#

how it is possible?

#

{% extends "_main.html" %}

{% block title %} Article {{ article.title }} {% endblock %}

 {% block body %}

     <h2>{{ article.title }}</h2>
     <p>{{ article.content }}</p>



{% endblock %}


shy finch
#

@native tide i am learning Django so it popped in my mind

hybrid patio
#

why article?

native tide
#

Because if you looked at your error... it literally says value is undefined

#

You are not passing a value to your HTML page, you are passing article

hybrid patio
#

I know

native tide
#
def article(art_id):
    article = articless[art_id]
    return render_template("article.html", article=article)```
#

Look at the render_template, you are passing article=article to the HTML page

hybrid patio
#

ah 😄

native tide
#

and article is in the form {"title": x, "content":y}

hybrid patio
#

ok than you so much

native tide
#

👍

hybrid patio
#

you are boss

#

😄

native tide
#

@shy finch If you want to learn a JS framework I'd recommend React

#

But save that for when you get to grips with Django

hybrid patio
#

@native tide look

shy finch
#

@shy finch If you want to learn a JS framework I'd recommend React
@native tide Thanks bro for letting me know.. pithink

hybrid patio
#

@app.route("/articles/<int:art_id>")
def article(art_id):
    article = articless[art_id]
    return render_template("article.html", fuck=article)

#

yes work

#

s

native tide
#

why ping me for that...

hybrid patio
#

I wanted to convice my self it works

static harbor
#

How can I serializers (using django rest api) two models like

class A(models.Model):
    name=Textfiled()

class B(models.Model):
    book=Textfield()
    name=Foreignkey(A)
    startDate=Datetime()
    endDate=Datetime()

this, so that I can create an api which gives json response like

{ 
"name":"tet",
"books":[
{
"book":"test",
"startDate":"2020-12-6",
"endDate":null
}
]
}
#

I want to understand how can I write serializers for these two models?

solar urchin
#

Guys, sorry if I'm wrong category in case you notify me and change.
I need to be able to assign this underlined value to a variable. However, this "content" text changes with each link, so the program must be able to fetch it every time

#

Can anyone help me?

native tide
#

@static harbor You can use DRF's modelSerializer

#

I'd recommend looking at the docs for that module

#

Then ask any questions if you don't understand something

hybrid patio
#

Hello again >D

#

I have problem with alight center in CSS

#

so how can I get this to html tag?

#

<.nav> ??

quick cargo
#

Remove the .

hybrid patio
#

nono

#

look

#

body {
    padding: 0 20%;
}

header {
    text-align: center;
}

.nav {
    padding: 0;
    list-style: none;
    overflow: hidden;
    text-align: center;
}

.nav li {
    display: inline;
}

.nav a {
    display: inline-block;
    padding: 10px;
    text-decoration: none;
}


footer {
    text-align: center;
}
#

I need use something for this

#

but what is .nav??

native tide
#

using . represents a class name

hybrid patio
#

becouse I have other text ... can I create another css tag?

#

ah ok

native tide
#

If in the HTML I had a div with class example, in the CSS doing .example would target that div

hybrid patio
#

I need center other text but i dont have enought css tags

native tide
#

Try justify-content: center

hybrid patio
#

look

#

becouse I dont have enought css tags

#

Can I create own?

round wave
#

can session variables be changed from the client? So when i save a email or something to save the account a user logged in, can i be sure he can't change that?

native tide
#

hello?

#

i have a question

round wave
#

then just ask the question and dont just say that you have one?

hybrid patio
#

ok without answer

native tide
#

I want to know that I can watch the web as much as I want through Python

#

just..not seing

#

@hybrid patio Yes you can. Go on W3 to get a rundown of how CSS works

hybrid patio
#

ok ok

#

nut thank you

#

I found it

native tide
#

@round wave If the session ID is stored in the cookie, yes. They can change it.

#

umm..

round wave
#

so whats the best way to save in what account a player is logged in?

#

maybe save a hash of the password too?

native tide
#

save a list?

#

@round wave save a hash of the password where? as a cookie?

#

Session auth will work fine. If the user changes the session token to one that does not match with the account, they should be logged out.

round wave
#

im new with web developement, so can i just save the email now?

native tide
#

wdym by save the email?

#

if you're using Django and don't have a seperate frontend use session auth, it'll do it all for you

round wave
#

im using flask

native tide
#

Well flask should have a library which solves that for you

round wave
#

do you know the name?

native tide
#

A simple google search would get it for you. I haven't used Flask in some time

#

If you follow a signup/login tutorial for flask they'll probably cover it too

slender moat
#

if anyone here ever used flask_restful/flask_restplus/flask_restx, what's the proper way to implement pagination and filtering on API resources?

native tide
#

Make API endpoints w/ Flask or Django

torpid pecan
#

When I try to start gunicorn with "sudo systemctl start gunicorn" I get the error: "A dependency job for gunicorn.service failed. See 'journalctl -xe' for details."

gusty hedge
#

did you check the details?

torpid pecan
#

When I use that command for details it tells me: No journal files were found

last quest
#

hi .. I m new to Django framework and i m trying to make a Data table which should having fowling function , like filtering data with group by using Django Query set ....so if you having any resource regarding this Django query set please let me no thankyou

vapid acorn
#

In django, how would you make dynamically added links

#

like with hastebin, where you get a link for every new document

#

I dont know what I should google for

native tide
#

@vapid acorn In your URLs you can have path('site/example/<id_of_something>/)

vapid acorn
#

oh ok

limber laurel
#

Hey I am trying to setup Django REST Serialization, but for some reason the page is not found

#

Like a url that starts with api is is not recognized

#
    path('login/', views.LoginView.as_view(), name='login'),
    path('profile/', views.ProfileView.as_view(), name='profile-view', ),
    path('plan/<int:pk>/', views.PlanView.as_view(), name='plan-view'),
    path('create-plan/', views.CreatePlanView.as_view(), name='create-plan-view'),
    path('logout/', views.LogoutView.as_view(), name='logout'),
    path('auto_setup/', views.AutoPlanView.as_view(), name='auto-plan'),
    path('edit_user/', views.EditProfileView.as_view(), name='edit-user'),
    path('register/', views.RegisterView.as_view(), name='register'),


    # REST Framework URLS
    path('api/plan/', include('users.api.urls', 'plans_api'))
]

users/urls.py

#
app_name = 'users'

urlpatterns = [
    path('<slug>', api_detail_plan_view, name='detail')
]

users.api.urls.py

#

I have found my mistake, I needed to use users prefix as in my main app the prefix for users is users

#

In what case would I use serialization?

#

and api views

hard sonnet
#

please any recommendations? I have problem recieving socket on server side created in flask-socketio

  1. I have client side in react native mobile app https://imgur.com/a/gpvxrox
  2. server running on raspberry pi trough flask-socketio
  3. I succesfully connect to server
  4. than after clicking on buttons I try to send socket socketio.emit 'data'
  5. in flask I have socketio.on 'data' print socket was connected but for some reason Im not getting that message
    any recommendations?
    my connectionscreen:https://pastebin.com/2W0cVrkc
    main screen where I click buttons and send sockets: https://pastebin.com/WhQv1VbQ
    simple flask-socketio server: https://pastebin.com/Uc50hxCz
#

Im trying to confirm recieving socket with print socket was connected on server side but it doesnt work, any recommendations please?

open owl
#

Please help, i need to obtain two values from a single checkbox. In a case below, i need to get food_name and price when a user check the box. Here's my code:

models.py

class Food(models.Model):
    food_name = models.CharField(max_length=50)
    food_image = models.ImageField(blank=True, null=True)
    price = models.IntegerField()
    description = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField()

**views.py**


def menu(request):
    Product = request.POST.getlist('food')
# here's where i need to get the values
   food_list = Food.objects.all()
    args = {
        'food_list':food_list
    }

    return render(request, template_name='menu.html', context=args)


menu.html
{% for food in food_list %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<tr>
<td>{{ food.food_name }}</td>
<td>{{ food.price }}</td>
<td><input type="checkbox" name="food" value="{{ food.price && food.food_name }}"></td>

#Here's my checkbox with the two values i need

{% endfor %}
<button type="submit">Order Now</button>
</form>

Pardon my poor code-arrangement here on the discord

sturdy parrot
#

hello, i was looking to make a website. i don't wanna say too much of what it is exactly but it's gonna basically be a voice chat like chatroulette or similar

#

i had my eye on flask or cherrypy

#

but i honestly don't know anything on either

#

or python web frameworks in general

#

if anyone had any suggestions or tips, it would be much appreciated

native tide
#

what is the recommended fastest way to get the output of a python script displayed on a webpage? i am building an app that will only ever be run locally but i would like some qol UX features and figured a webpage would be the most convenient way. django seems like overkill and im unable to find a flask tutorial that simply outlines how to achieve my goal?

#

like, i just want to turn a python dict into some text on a webpage

grizzled meteor
#

well, you prob def want to use Flask

#

and Django is 100% overkill

#

what are you using for your Front-End @native tide

native tide
#

im fine using basic html/css for now

#

it's just a series of scripts that im running locally for myself

#

any framework seems like overkill tbh. i feel like im better off just exporting to csv or something else if i don't want to stare at the cli all day

#

also ty for the response

grizzled meteor
#

i mean; tahts True lol

#

but at least with Flask, you could just configure a simple end-point and have your Front-end smack that endpoint for the data

native tide
#

yeah

grizzled meteor
#

up to you; can be tackled all kinds of diff ways and you prob don't need a web-framework to do it

native tide
#

im functionally new to python so i feel like it's just too much to learn at once. i'd rather just focus on getting my scripts to do what i want rather than take on a web framework

#

yeah

#

thank you

#

helps to talk through it

chrome onyx
#

Check out Tech With Tim's Flask Tutorial on YouTube

#

It explains how to use Flask

#

But I will include an example to do just what you want to do:

topaz widget
#

Hey has anyone ever had problems with css media queries not updating a web page when the mobile device orientation changes?

#

I'm having some problems with this, and I haven't found a solution after searching for some time on Google.

chrome onyx
#

main.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
    dict = {"What is this?": "A dictionary", "Why is this here?": "It's an example"}
    return render_template("index.html", dict=dict)

app.run()

index.html

<html>
<!-- Add some boilerplate here to get all the <head> tags -->
<body>
    <p>{{dict}}</p>
</body>
</html>
#

@native tide ^

#

@topaz widget I've had that problem too, but I sadly don't know a solution

native tide
#

thanks, @chrome onyx

#

that's really helpful

chrome onyx
#

You could do some complex styling to the dictionary to get it in a table and etc., just remember that anything inside {{here}} is a reference to Python, so you can use Python code in there.
For example: {{dict["What is this?"]}} will just display A dictionary

native tide
#

that's perfect

chrome onyx
#

More complex templating syntax (such as for loops and if statements - within your HTML code) are available... check out jinja2 if you want to learn more

topaz widget
#

I've had that problem too, but I sadly don't know a solution
@chrome onyx Well, thanks for the response. It's really strange. So much for the page being responsive.

swift heron
#

Okay I am just learning on how to do post/get requests to the django database and when I run my page I am getting Forbidden (CSRF token missing or incorrect.)

Is there a way I can disable CSRF tokens for the moment until I can actually get Post/Get requests working? if anyone has a reply please @swift heron Thanks!

hybrid patio
#

Good evening guy

#

guys

#

Someone help me with little issue?

#

Flask

slender moat
#

just say what's the issue dude

pulsar hinge
#

Is there any possible way to remove this info from djangos signup form? coz it's destroying my layout.

hybrid patio
#

OK I try to use include

#

but my page doesnt works

#
<!DOCTYPE html>
<html lang="en">
    <head>

        <title>{% block title %} {% endblock %}</title>
        {% include "_head.html"}
    </head>
    <body>
        <header>
            <h1><a href="{{ url_for("welcome_page") }}">Tomas Balbinder</a></h1>
        </header>
        <nav>
            <ul class="nav">
                <li><a href="{{ url_for("admin") }}">Admin</a></li>
                <li><a href="{{ url_for("about") }}">About me</a></li>
                <li><a href="{{ url_for("articles") }}">Articles</a></li>
            </ul>
        </nav>

        <main>

            {% block main %} {% endblock %}

        </main>

        {% block body %} {% endblock %}
        <footer>

            <p> (c) 2020 Tomas Balbinder</p>

        </footer>


    </body>
</html>
#

in head ... look

#

this is _head page


<meta charset="UTF-8">
 <link rel="stylesheet" type="text/css" href={{url_for("static", filename="css/main.css")}}>

#

error

pulsar hinge
#

@hybrid patio {% include "_head.html"} it is supposed to be {% include "_head.html"%} u just forgot the % sign at the end

swift heron
#

I figured it out for testing when working with a class you need to use the following
@method_decorator(csrf_exempt, name='dispatch')

keen night
#

Hey, I'd like to create a basic online form to feed variables for my python program, what would be the fastest way to do so ? (Idc about fancy graphics) - I cannot use Streamlit as its work related and streamlit doesnt work with IE

gusty hedge
#

oh sorry, you said online form

hybrid patio
#

{% extends "_main.html" %}

{% block title %} Welcome Tomas pages {% endblock %}




{% block body %} Tohle je zkušební stránka Tomáše Balbindera.{% endblock %}  

#

Oh tank you I am ... idiot >D

verbal snow
#

For some reason if statements in django work half the time
{% if owner.userid == user.id or user.staff == True %}
This is what im doing and the current user is not the owner but is staff, but what its supposed to do when staff is true, is not happening

pulsar hinge
#

Why don't u just put {% if user.staff %}, i suppose owner is staff as well.

#

@verbal snow

verbal snow
#

Owner is not staff

#

It's the owner of a specific entity, not the site

pulsar hinge
#

than instead doing {% if owner.userid == user.id or ... %} do {% if user.id == owner.userid or ... %}

verbal snow
#

Didn't change anything

#

It's like django can't parse anything

#

It'll parse half the statement in some cases

pulsar hinge
#

are u properly refering to an object?

verbal snow
#

I am indeed

pulsar hinge
#

no idea then

lavish canopy
#

I dunno if my question ever got answered or not

#

But I've been having issues getting NodeJS and NPM to work well with my django project

#

I literally just want to use NPM to install stupid VueJS

#

I installed NodeJS and it literally broke VS Code

hard sonnet
#

Any recommendations what am I doing wrong? I connect to server and try to send socket with socket.emit
BUT for some reason my server doesnt recieve socket, or it seems it doesnt because it wont print socket was connected
this is my client:https://pastebin.com/WhQv1VbQ
this is my server: https://pastebin.com/Uc50hxCz

lavish canopy
#

I'm down for DMs/Side convos for someone who can just help me get setup so I don't have to fiddle for another 4 hours with trying to make sure everything works

sturdy sapphire
#

In Django, why should I make a custom user model inheriting from AbstractUser? why cant i just get it from the AUTH_USER_MODEL thing? (im not 100% sure about the names here)

#

There should be one obvious way to do things, and inheriting from abstractuser to make your own custom one does not make a lot of sense to me.

#

I would love some insight into this?

#

for the record, I am using AbstractUser in my custom user model, but I wonder why.

native tide
#

@sturdy sapphire Iirc AUTH_USER_MODEL (by default is django.contrib.auth.models.User) has it's own attributes and methods such as is_authenticated, which other parts of Django will leverage. So, if you create your own model overriding this, some parts of Django won't work with your model (such as authentication).
https://docs.djangoproject.com/en/3.1/ref/contrib/auth/

So by inheriting from AbstractUser you keep all of the attributes / methods of Django's User model, and you essentially just add some custom data fields.

sturdy sapphire
#

right, that makes sense. thanks @native tide

native tide
#

@verbal snow You said that the user is staff? So this will always run as it's truthy
{% if owner.userid == user.id or user.staff == True %}
right?

verbal snow
#

Yea but it wasn't showing what it should've. I got it tho

indigo kettle
#

the staff attribute is user.is_staff I'm pretty sure

#

not just staff

swift heron
#

@native tide Hello just a quick question I did get post request to work so I can send data from the frontend to the backend how would I go about sending data from the backend to the frontend without reloading the page? say an additional model is loaded into the database after the page is loaded how can I get that info to javascript and then added to the frontend?

native tide
#

@swift heron your endpoint can return a Response, you'll have to import it, can't remember off the top off my head

#

And that will return JS which your frontend can handle

swift heron
#

alright awesome will look into it, thanks again!

native tide
#

Also import status (which returns the status of the request back to the frontend, such as 200 (OK) or 404 (not found)

#

An example would be this for your API endpoint

# import Response, status
def example_endpoint(request):
  # do something with the request
  data = {"success": "request was successful"} # the data you want to return to your frontend
  return Response(data=data, status=status.200_OK) # specify data=<data you want to return> and status=<status you want to return>
#

Then in your frontend you can access the returned data

verbal snow
#

I'm using the erorr page example on the django site

def response_error_handler(request, exception=None):
    return HttpResponse('Error handler content', status=404)


def permission_denied_view(request):
    raise PermissionDenied

handler404 = response_error_handler
``` but it still renders the regular one
native tide
#

I'd recommend axios for the requests

swift heron
#

Alright thanks Ill be trying that out after a short break 👍

plucky tapir
#

Currently at the moment on django I am using generic class based views to CRUD my tables from the database. If I want to view them all on a homepage, should I still use class based views for that?

#

Currently using list view to view info

#

Maybe switch to FBV for what I’m trying to do

dapper tusk
#

!pban @acoustic zealot spamming insults

lavish prismBOT
#

failmail :ok_hand: applied ban to @acoustic zealot permanently.

visual lake
#
soup = BeautifulSoup(page.content, 'html.parser')
tree = soup.find('span', {'class': 'indexName'})
print(tree.next_sibling)
#  None
#

is class=indexName not a sibling to class=indexValue or am I missing something?

half vale
#

Hi, I'm a total newb. I have a server that I'm renting. I'm looking for a tutorial on how to use python on my server to do things like respond to a POST request

#

The simpler the better. I'm only trying to do the most basic things.

topaz widget
#

@half vale Use a framework like Flask.

#

Django works, too, but is typically for more complicated stuff.

#

Flask is easier to get started with from what I understand.

indigo kettle
#

@visual lake it is a sibling, are you sure that the class indexName is used only once on that page though? You might be getting a different element on accident

visual lake
#

yea you're right the first one on the page actually doesn't have a sibling @indigo kettle

indigo kettle
#

so you'll have to find a different way to access that element, maybe first finding a parent and then finding that class name afterwards

visual lake
#

I can get to "DJ Italy" which is a child of indexName which inturn is a sibling of indexValue

#

would that work?

#

nevermind, thanks for the help @indigo kettle

indigo kettle
#

oop, sorry. Np!

half vale
#

@topaz widget I don't really understand how to use Flask on a remote server. Do you know a good place for me to learn?

topaz widget
#

Learn on your local computer. I think Flask probably has a built-in local server. When you feel comfortable with your app, then transfer it over to your remote server and configure the server to run your Flask app. @half vale

half vale
#

I already understand how to program from my local computer. I'm looking for resources on how to do it remotely.

topaz widget
#

Corey Schafer has some tutorials on YouTube for Django. He might have some on deployment for Flask, too. I know he has Flask tutorials, just not sure if they cover deployment.

#

Do you have some server software like Apache or NGINX installed? You'll probably need that too unless you're using some pre-configured solution.

half vale
#

I have a server up and running. There's a terminal I can get to from cpanel. That's pretty much all I know.

#

I published a sample site and then replaced it with my own html and js files. But I don't know how to code actual server side code.

#

I will check out Corey Schafer.

topaz widget
#

Yeah, getting a server set up properly can be somewhat involved, but for simple stuff, there are ways to make it easier like Heroku. I'd recommend looking at Corey Schafer first. He's pretty good at explaining things that can be somewhat complicated.

half vale
#

I like the host that I have I just don't understand how to set up a server honestly. Or how to change one that's already been set up.

topaz widget
half vale
#

Thank you.

indigo kettle
#

I haven't used sqlalchemy but have used django often

#

I can try to help. Is it important to have referred_by and referred_to fields?

#

is the referred_to, not somehow related to referred_by

#

I think I understand

#

I think the issue is that you have multiple backrefs with the same name to the same model

    dest_address = db.relationship('Address', backref='orders', lazy='select')
    from_address = db.relationship('Address', backref='orders', lazy='select')
    status = db.Column(db.String(MaxLengths.order_status), nullable=False, default="Pending")
    products = db.relationship('Product', backref='orders', lazy='select')
    subtotal = db.Column(db.Float(), nullable=False)
    shipping_fee = db.Column(db.Float(), nullable=False)
    tax_cost = db.Column(db.Float(), nullable=False)
    total = db.Column(db.Float(), nullable=False)
    discount_code = db.relationship('DiscountCode', backref='orders', uselist=False, lazy='select')
#

here you have 3 backref='orders'

#

I think these will have to be unique or else there will be no way to access them

#

actually, the discountcode should be fine

#

but the other two are both coming from Address

#

so those will have to be unique

#

you also have 2 reviews fields on the Product model

#

I'm not sure exactly how this works but for the referred_by thing I was asking about, I think this is the right time to use backref because referred_to, and referred_by should be kinds of mirrors of eachother

#
    referred_by = db.relationship('User', backref='referred_to')

idk exactly how it should be written

#

just a thought

#

did you run a migration?

#

one of my first large web apps I wrote was an ecommerce app so this all looks very familiar

#

fun stuff!

#

another thing, here on Product

    ordered_by = db.relationship('User', backref='product', lazy='select')
    orders = db.relationship('Orders', backref='product', lazy='select')

you have ordered_by as a field, but users has a relation on the order, so you can access users through the order model

#

hm, I feel like it should be accessible without writing it again like this. But I don't know exactly what sqlalchemy is doing so I'm probably wrong

#

haha

#

yeah, you'll bang your head against a wall for a while before it all makes sense

native tide
#

I am trying to create a Flask application, however, my extend title isn't working. It was working in a different IDE, but I cannot use that one anymore.
My layout.html:

<head>
    <title>{% block title %}{% endblock %} - My Webpage</title>
...

My index page (only one):

{% extends "layout.html" %}

{% block title %} Index {% endblock %}

{% block main %}
    test
{% endblock %}

Any help would be appreciated. Thanks in advance!

#

^^ what it looks like now

native tide
#

It also appears that all other blocks do not work too

indigo kettle
#

changing ide's shouldn't change anything

#

what does your view look like

topaz widget
#

@native tide It's not obvious from what you posted what the problem is, and as bri said, changing your IDE shouldn't make any difference unless it's a tabs vs. spaces issue in your Python code. This does not seem like a Python issue, though.

native tide
#

wtf

buoyant dawn
#

Hey guys...I can't seem to get rid of this problem in django
I've installed Django in both the venv and on the system
But this problem still persists
I tried to delete the workspace and create a new one but still can't seem to get rid of this

unborn mural
#

Hey guys after deploying my django website how is it possible to access my django admin ui?

topaz widget
#

Hey guys after deploying my django website how is it possible to access my django admin ui?
@unborn mural Go to the /admin url and enter your superuser credentials. If you have not created a superuser, the command to create one should be python3 manage.py createsuperuser from the root directory of your Django site (the directory with your manage.py file in it).

unborn mural
#

no nooo

#

tht one is okayy

#

but like let's say i create a simple blog application

#

and then deploy it

topaz widget
#

Same deal

unborn mural
#

if i need tp create , edit or delete my db

#

then how do i access my admin of already deployed website

topaz widget
#

There are a number of commands to interact with your db.

#

I'm not exactly sure what you're trying to do.

unborn mural
#

I'm not exactly sure what you're trying to do.
@topaz widget bro there's this django admin ui ryt

#

how do i access tht after i deploy my website

topaz widget
#

are you talking about the admin page?

unborn mural
#

yes

topaz widget
#

Should be the same url

#

(not localhost, though, obviously)

unborn mural
#

Should be the same url
@topaz widget then anyone would be able to access it ryt

topaz widget
#

If they can guess your credentials, yes.

#

Django recommends changing the admin login page url to something only you know.

#

You can do that in your root url conf if you think you need the security.

unborn mural
#

got itt

#

thanksss 🙂

topaz widget
#

The default url is admin/

#

@unborn mural Make sure you register all your models in your admin page, too. Should be done in something like an admin.py file in each app.

unborn mural
#

yess okay

tranquil idol
#

Quick question: free places to learn JS for WebDevs?

rapid bramble
#

Any ideas why this error?

django.db.utils.OperationalError: (-1, 'MySQL Connection not available.', None)

I'm using mysql-connector-python and a remote DB

#

Oh btw, this happens when I try to create a super user only

gaunt marlin
#

@rapid bramble you said you have remote DB right? can you connect to the database? the error probably from timeout timer exceed when connect to the DB

#

try running in shell with python manage.py shell
and

import django
print(django.db.connection.ensure_connection())

if it return None then the connection is ok, else it will print out the error

rapid bramble
#

I'm able to connect to the database remotely yes, and that is pretty obvious considering that error occurs only during super user creation and rest of the connections - login signup and other stuff involving dB is fine.
But I'll try the second portion of it when I'm back on the PC.

#

Also, it occurs randomly, like if I set CONN_MAX_AGE to 36000 sometimes it works and sometimes it doesn't

#

Pretty weird

sly echo
#

Hello

#

Can somebody assist me?

pulsar hinge
#

Just put your problem here

sly echo
#

Sure

#

I was practicing recursion
I wrote this code and the output should return "Babe Hi" but it is returning "ebaB iH"

#
def reverse(string):
    if len(string) == 0:
        return string
    else:
        return reverse(string[1:]) + string[0]
a = "Hi Babe"
print(reverse(a))
#

@pulsar hinge

pulsar hinge
#

I don't think it's a problem for web dev, use channel for it but python is going thru a single letter not words

sly echo
#

um, okay

pulsar hinge
sly echo
#

I have tried this code of geeks. They are reversing the characters. I want to reverse the order of the words

pulsar hinge
#

No, they are putting last words at the beginning.
Input : str = "geeks quiz practice code"
Output : str = "code practice quiz geeks"

sly echo
#

I see, thanks.

native tide
#

hello, this is a pre-development question, to clarify if my idea could workout - when i choose heroku as host for my little webapp i need to store the code that drives the app in a git(hub) repository and the data in a postgresql database, is that correct so far?

swift crystal
#

🚫

native tide
#

thats all you gonna give?

gaunt marlin
#

@native tide your code will be stored in both github and the heroku server in order to run, you would also need to set up your database on the server though

limber laurel
#

What woild be the use case if serialization?

native tide
#

@limber laurel Can you elaborate

limber laurel
#

Like when would I serialize a view and return it in a json format?

native tide
#

When you want to return data to your frontend

limber laurel
#

But like why would I want to do it that way?

native tide
#

Let's say that you make a request to your API endpoint with JSON and want to save it to your model... You can serialize it and then save the serialized data. That has advantages because you can add custom serializer validation (which is different to your model).

But if you want to just return some data, serializers just validate that the input is what is expected. For such views I usually don't use serializers (as all of my input validation is on the frontend anyway).

limber laurel
#

Hi

#

@native tide Thanks, I guess I will need to do some more reading on my own

green snow
#

does anyone know how to make css work in django
i mean its working but when i save the page changes arent reflected after refresh
it only works when i restart the server

#

it worked initially but now it doesnt

#

sometimes it works sometimes doesnt

rapid bramble
#

@green snow Ctrl + F5

#

If you check Django development server logs you'll see a 304 on the CSS file, which basically means that the CSS file has been cached by the browser and the latest copy isn't being fetched.

green snow
#

ctrl+f5 works thx @rapid bramble

rapid bramble
#

👍

native monolith
#
@app.route("/picture", methods=["GET", "POST"])
def picture():
    if request.method == "GET":
        return "Getting image\n"
    else:
        return "None\n"

how request knows what methos it was called?

#

is there some globals under mask ?

quick cargo
#

It's just the current request's method from the HTTP request

upbeat umbra
#

Was that module created from libcurl?

willow iron
#

possibly

quick cargo
#

@upbeat umbra what module?

upbeat umbra
#

requests

native monolith
#

requests or request ?

#

;P

native monolith
empty pivot
#

@native monolith rendering is what the computer does when it decides what to display to the user and then displays that. super refers to the class which a certain class inherits or extends.

So if I have an Animal class then a Dog class which inherits properties and functions from Animal class, then I can use super in the Dog class to refer to properties or functions from the Animal class.

I think I got that right :)

native monolith
#

in know python super, but is this the same in flask and html?

slender moat
#

yes, but that's not html, it's a jinja2 template

native monolith
#

ok, but written in html 😄

slender moat
#

render in this context pretty much means that it will copy and paste some content

#

in the place where you called super()

native monolith
#

hmmm

#

so it copies block head from parent and extend it ?

#

I see

#

thanks @slender moat

slender moat
#

yeah

#

np

native monolith
#

could you also give me short desc what is the difference? {% %} {{ }}

#

what I understand is that {% %} refers to conetxt, and {{ }} is code

#

or {%%} is escape for jina, and the other i do not know 😄

slender moat
#

{{ }} are expressions and have some kind of output

#

{%..%} are statements and have no output

native monolith
#

im reading line by line but did not saw such thing yet

#

thanks

slender moat
#

np

echo river
#

Hi i need some help regarding libxml12-python, when I tried to install django-dinggo into my project . It keep return the same error. ERROR: No matching distribution found for libxml2-python>=2.6.9 (from django-dingos>=0.1.0->django-mantis-core). When I check in PyPI, the only version is 2.6.9.

keen night
#

Hello, I would like to get User inputs through a very basic online form. What's the best way to do it ? (Streamlit felt amazing but wont work on internet explorer)

blazing sinew
#

anyone with experience getting a pandas dataframe into postgresl?

stark plank
#

Ok i am not the best at asking coding questions to be honest but I am trying to show a static file which is an image in my template. I have read a lot of things and i dont know what i am doing wrong. Here is my template code ```

<h1>Portfolio</h1>

{% load static %}

<img href="{% static 'portfolioapp/Placeholder.png' %}">

{% for project in projects %}

<h2>{{ project.title }}</h2>
<img src="{{ project.image.url }}">
<p>{{ project.description }}</p>
<br>
{% if project.url %}
<a href="{{ project.url }}">Link </a>
{% endif %}

{% endfor %}

let me know if there is anything else i need to copy and paste
#

its django btw

snow sierra
#

STATIC_URL = '/static/'
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/')

#

also in urls

stark plank
#

@stark plank do you have changes in settings.py ?
@snow sierra yes

snow sierra
#

@stark plank using browser inspect?

stark plank
#

I assume you are asking if the file appears in the network tab and the only thing that appears is my other placeholder image which is from the database and my web page

snow sierra
#

Ok i am not the best at asking coding questions to be honest but I am trying to show a static file which is an image in my template. I have read a lot of things and i dont know what i am doing wrong. Here is my template code ```

<h1>Portfolio</h1>

{% load static %}

<img href="{% static 'portfolioapp/Placeholder.png' %}">

{% for project in projects %}

<h2>{{ project.title }}</h2>
<img src="{{ project.image.url }}">
<p>{{ project.description }}</p>
<br>
{% if project.url %}
<a href="{{ project.url }}">Link </a>
{% endif %}

{% endfor %}

let me know if there is anything else i need to copy and paste

@stark plank it is not enough :x

stark plank
#

what should i also show

snow sierra
stark plank
#

ok

snow sierra
#

and folders hierarchy

stark plank
#
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from portfolioapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('blog/', include('blog.urls'))
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)```
snow sierra
#

did you restart server after changes>?

stark plank
#

yes

snow sierra
#

mine works fine .. :/

stark plank
#

thats really odd

snow sierra
#

can you paste HTML source code? where your img is..

stark plank
#

i'm not too sure what you mean

snow sierra
stark plank
#

like what i pasted earlier? This? ```
{% load static %}
<h1>John's Portfolio</h1>

<img href="{% static 'portfolioapp/Placeholder.png' %}">

{% for project in projects %}

<h2>{{ project.title }}</h2>
<img src="{{ project.image.url }}">
<p>{{ project.description }}</p>
<br>
{% if project.url %}
<a href="{{ project.url }}">Link </a>
{% endif %}

{% endfor %}

snow sierra
#

open web page > right click on image place > inspect

stark plank
#

this?

snow sierra
#

yes, and when you click on link /Placeholder.png what is happening?

stark plank
#

nothing

#

i put it in the url

#

and the image shows

#

huh

#

this is confusing 😅

#

i fixed it

snow sierra
#

🙂

stark plank
#

i changed href to src

snow sierra
#

lol yes :d d

stark plank
#

thanks for your patience haha

native monolith
#
    <div class="topnav" id="myTopnav">
      <a href="#home" class="active">Home</a>
      <a href="#news">News</a>
      <a href="#contact">Contact</a>
      <a href="#about">About</a>
    </div>

hey, so where can I find common or most functional classes to use like this topnav? 😄

opal vale
#

How can I host static files in my fastapi?

#

I mean I have folder
pics and I want people to be able to see them

halcyon lion
#

@stark plank isnt it convention to name ur media files "media" and add as sub directories whatever u want

slender whale
#

Is there a way to force the execution of a parent block before my block?

#

I inherit a template and jinja keeps putting my block after the parents despite calling super after my block

#

And idk how to fix it

native monolith
#

yes

#

{{ super() }}

slender whale
#

I do that

#

But it's not working

#

I made a long so post about it

native monolith
#

you should call it before i think, not sure

slender whale
#

I want my block executed first

#

So that it's overwritten should someone pass an option to the parent

native monolith
#

which block u want to call?

#

you call now table

slender whale
#

I want to call table_styles block from the parent before my default_table_styles block

native monolith
#

then call it in this block

slender whale
#

How do I call a block from the parent without calling the entire thing?

native monolith
#

?

#
{% block default_table_styles %}
         #T_{{uuid}} th {
          font-size: 100%;
          text-align: center;
          background-color: blue;
          color: white;
          border: black solid thin;
    }    #T_{{uuid}} td {
          font-size: 100%;
          text-align: center;
          background-color: white;
          color: black;
          border: black solid thin;
    }    #T_{{uuid}} th:empty {
          border-width: 0;
    }
    {{ super() }}
{% endblock %}

<!-- {{ super() }} />
#

you also try using css

#

instead of formating every row and col

#

@slender whale did it worked?

slender whale
#

Not exactly but you lead me enough to the correct solution

#

Thank you very much

#

Pandas has an empty block called before_style and I just shoved my css in that

#

Outside of table block

#

I didn't know I could do that

#

So thank you again @native monolith

native monolith
#

does css style link must be in head ?

slender whale
#

Yeah

native monolith
#

also why css keeps upadting so long?

#

sometimes i reload page, or even start private brower mode it still remebers old css

prisma jackal
#

What is the best django vote API

native monolith
trim star
#

I have a django question

#

I am looking at a model

#

and i see an attribute (member associated with it) but i cannot find where that attribute is being initiated

#

It is being referred to as self.attribute

#

but attribute was never initialized in the class definition of the model. Where else can attributes be defined?

naive oar
#

Hi All, I'm in need of django regroup tag template.

#

I'm trying to group an image into a specific attributes

native tide
#

@naive oar wdym by that

trail vapor
#

who use brython ? dm me pls !!

naive oar
#

@native tide Here's what I have so far '<div class="row">
<div class="uni-popular-cars-item">
{% regroup detailwheels by wheel_image.wheel as wheel_list %}
{% for wheel in wheel_list %}
<div class="col-md-3 col-sm-6 col-xs-6 col-unisp-12 item new">
<div class="item-img">
<img src="{{ wheel.grouper }}" alt="" class="img-responsive">
<div class="item-img-caption">
</div>
</div>
{% for detwheel in wheel.list %}
<div class="item-info">
<h3><a href="">{{ detwheel.name }}</a></h3>
<div class="uni-divider"></div>
<h4>Model: {{ detwheel.model }}</h4>
<h4>Available Sizes: {{ detwheel.sizes }}</h4>
<h5>Finish: {{ detwheel.finish }}</h5>
</div>
{% endfor %}
</div>
{% endfor %}`

#

I'm trying to get the image to display here but I'm not seeing anything? ' <img src="{{ wheel.grouper }}" alt="" class="img-responsive">'

lavish canopy
#

Aren't you supposed to do {% url 'static/img' %}?

naive oar
#

@lavish canopy Yes that is at the top of the page

lavish canopy
#

Wait

#

I usually do {% load static %} before everything else

#

So like:

{% load static %} <link rel="stylesheet" type...

#

Then I put all my HTML underneath it

naive oar
#

Here's what I'm trying to do, I want to group the images and only display the model number and sizes and only return 1 image.

lavish canopy
#

I might be missing something

naive oar
#

maybe there is something easier that regroup, I'm still new to Django

lavish canopy
#

Same here

#

Almost seems like it would be easier if you could load the image as a variable and then just call the variable

#

Or you know.... go the old route and just copy/pasta the same img code

naive oar
#

I'm trying to make this dynamic from a csv file, this csv file can have the same image to multiple model numbers

#

I know how to do it in SQL but I'm trying to do it with Django tags

safe oasis
#

so I clicked a button and I checked the Network Tab but it shows values like this in the Request Payload.

choices: ["5c52b1f391a06c64660050f8"],
question_id: "5dd34bf75f0ed65e8b31195f",
session_key: "5dd34bf75f0ed65e8b31176RT",
stuff like that so I was wondering how would I get these values because I know whend I send a Post Request in Python then the session key would be different and I wouldnt know the question_id because there would be different questions.

I tried viewing the source of the page to look for the value of one of the keys above but I couldnt find any because if I did then I would just use Web Scraping to find the IDs for the question and choices.

cunning hull
#

Anyone know how I could format text to the colors of lets say python?

naive oar
#

@safe oasis what are you trying to get the question_id?

#

Is that an html element?

rustic pebble
#

Does anyone know how I can fix this error when trying to connect with a foreign redis server?
[2020-11-19 01:51:54,727: CRITICAL/MainProcess] Unrecoverable error: ModuleNotFoundError("No module named 'redistest-ro'")

#

I have literally 0 idea on how to fix it

#

And I cannot find anything related to redistest-ro

inland stirrup
#

same here but i'll try to help u

rustic pebble
#

Same with me? @inland stirrup

inland stirrup
#

i mean i have no idea too

rustic pebble
#

ah alright

#

I think I figured it out

#

I had forgot to add redis:// before the server url

inland stirrup
#

ok lol good to hear

#

for flask when i render webpage with images which one is good practice

use the usual img tag
or
use the url_for to create a field for the image

safe oasis
#

@naive oar I just found out how to get the question_id it was stored in an HTML element, now my question is how do I get the session_key? I tried checking my cookies

naive oar
#

@safe oasis nice, that you can usually find in the network tab, I dont believe that's stored in the html.

safe oasis
#

@naive oar how? would it be a get request? can you show an example screenshot of what it may look like

naive oar
#

@safe oasis this can be done with selenium I believe, its been a while since I've done web scrapping.

native tide
#

I am trying to create a Flask application, however, my extend blocks aren't working
My layout.html:

<head>
    <title>{% block title %}{% endblock %} - My Webpage</title>
...

My index page (only one):

{% extends "layout.html" %}

{% block title %} Index {% endblock %}

{% block main %}
    test
{% endblock %}

Any help would be appreciated. Thanks in advance!

I said this yesterday and someone replied with "this shouldn't be a python issue" Any idea what is messing up? Maybe like a Flask setting or something? It seems as if Jinja is just reading the first line and not reading the rest

rustic pebble
glass badger
#

Hey, I want to preload some data on one of my webpages, I dont want to use a dataframe however because that slows down the server a lot if their is traffic.

#

I was wondering, if a dictionary of dataframes solves the above?

#

instead of one giant DF, allow for a dictionary of an estimated 900 Dataframes?

rustic pebble
#

If one dataframe slows down your server how would 900 dataframes make it faster? @glass badger

glass badger
#

The differences is the dataframe would be parsed, and if a user wanted to look for an item located in my dataframe, they wouldnt have to look through 100,000 rows

#

Instead they would locate the key index

#

making it much faster

inland stirrup
#

I said this yesterday and someone replied with "this shouldn't be a python issue" Any idea what is messing up? Maybe like a Flask setting or something? It seems as if Jinja is just reading the first line and not reading the rest
@native tide technically this should work ...is your file structure proper

native tide
#

What do you mean by that?

rustic pebble
#

The differences is the dataframe would be parsed, and if a user wanted to look for an item located in my dataframe, they wouldnt have to look through 100,000 rows
@glass badger I am not sure what you mean

#

If that's the case why not have a local db with all the dataframes and then just a route that the user can make requests to

#

That would be the fastest

inland stirrup
#

i mean all the html files should be in templates folder and all other python files should be in a level above the template directory @native tide

glass badger
#

@rustic pebble to my understanding, doing a "look-up" on multiple rows is always much more extensive then not having to look through rows if they dont have too

#

Play with a dictionary of dataframes and you will see what i mean in terms of speed. However I don't know about the RAM issues with a dictionary

#

which is why I ask 🙂

native tide
#

I think that is what you mean

inland stirrup
#

looks good ...whats written ur app.py file

native tide
glass badger
#

@rustic pebble I have a dB that I write queries too, not sure if thats what you meant.

rustic pebble
#

You can load the dict you are talking about in the server memory, assign a unique id to each one of them or something to identify them and then you can create a route like this:

@app.route('/get-df/<df_id>', methods=['GET'])
def get_df(df_id):
  return {'data': dataframe_dict[df_id]}
inland stirrup
#

@native tide dm me like the whole file ....

native tide
#

That is the whole file

#

Not including imports

inland stirrup
#

are u in a venv?

native tide
#

I just started on this and it just stopped working

#

Yes, I am

inland stirrup
#

wait that shouldnt matter

glass badger
#

You can load the dict you are talking about in the server memory, assign a unique id to each one of them or something to identify them and then you can create a route like this:

@app.route('/get-df/<df_id>', methods=['GET'])
def get_df(df_id):
  return {'data': dataframe_dict[df_id]}

@rustic pebble interesting

rustic pebble
#

Did you understand what I am saying?

glass badger
#

Yes I do, thank you for the example. So would the server calls be made client side?

#

@rustic pebble

rustic pebble
#

Yup, a really simple fetch api

#

This method would really make your load times faster since all you would need to do is get the keys

glass badger
#

I have a question, would this be a similar networking to a rest api?

rustic pebble
#

So you would have something like this:

@app.route('/')
def home():
  return render_template('index.html', dataframe_keys=dataframe_dict.keys())

Now you would have to iterate through the dataframe_keys list to fill the frontend using Jinja2 server-side rendering. Now if you want to make a client-side request you can do the following:

async function get_dataframe_data(dataframe_id){
  let url = "/get-df" + dataframe_id;
  const resp = await fetch(url, {method: 'GET'});
  const dataframe = await resp.json().data //or await resp.json()['data'] JSON can be accessed either as an object or as a dict
  return dataframe
#

@glass badger

#

I have a question, would this be a similar networking to a rest api?
@glass badger Yes

glass badger
#

@rustic pebble ohhh okay I see now, thank you so much!

rustic pebble
#

No problem!

twilit needle
#

Hello

#

So I have a django rest api

#

and a reactjs app which consumes it

#

so I want to access the authenticated user's info from the reactjs frontend

#

whats the best way to do this?

#

Right now I have an api view like this to access it is this right?

#
class CurrentUserView(APIView):
    """
    An APIView to get the current user
    [authenticated user]
    """
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        user = request.user
        serializer = CurrentUserSerializer(user)
        return Response(data=serializer.data)
indigo kettle
#

seems fine to me

twilit needle
#

is this how its generally done

native tide
#

how do i read static files

twilit needle
#

okay if theres any other better practice
someone pls tell me I have no idea

#

thanks @indigo kettle

indigo kettle
#

yeah if someone else is more familiar hopefully they can answer, seems perfectly good to me though!

twilit needle
#

thanks

#

its funny this channel has support for JavaScript

safe oasis
#

@naive oar Is there any way I can do this with requests? Because there is a thing called

requests.Session()

But no idea on how to get its id

naive oar
#

@safe oasis I'm sorry not sure about getting the session id?

native tide
#

h

peak locust
#

hello

#

is any one available to make django websites

#

giving 10-100 usd on work

wet heath
#

guys what should i start to learn, flask or django?

twilit needle
#

this is not a hiring place sorry

#

@peak locust

#

guys what should i start to learn, flask or django?
@wet heath Django

#

I have a doubt with Django.
So my media files are saved in a directory called media

here's my settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

I want to display my files on the website, like
If theres a file with the path /media/images/default.jpg
then when I go to my_url/media/images/default.jpg The image should be displayed on the browser

how can I do this?
discord does the same thing, but how?

#

see?

wet heath
#

@twilit needle yes thx 😊

plucky tapir
#

I'm trying to do an if statement inside of an html file for django, would someone be able to look at my code and see whatsup?

#

Its just outputting the lines rather than performing them

merry kelp
#

hlo

native tide
#

hi

#

anyone there?

#

i like some help with Django , deleting multiple models at once

merry kelp
#

hlo i need help regarding Flask

#

i have doubt in flask it is i am making a web development using flask and html so my doubt is i want my web app users to navigate between pages and in particular order . Example i have A,B,c pages i want users to go to c when they have visited A.B

#

this is my doubt

#

i hope i find answer soon

native tide
#

me too

#

🙂 )

native monolith
#

<div class="navbar" id="TopNavBar"> is this bootstrap? or its js element

stone wren
#

I added some enum types in flask, but when I update the object, it says this enum type was not found

#

is editing enums not possible in flask sqlalchemy?

native tide
#

@twilit needle What authentication method are you using

#

You shouldn't be serializing request.user. You should be serializing request.data which contains an Authorization header with your user token.

#

Which (on sign up / login) you should be sending a token to your frontend which then saves it as a cookie.

#

@merry kelp on page A have a link to page B. On page B have a link to page C.

prisma jackal
#

I want to implement reddit upvote/downvote blog post but I don't want to reinvent the wheel. I need a help, I use django.

plucky tapir
#

Really quick question. Is there a way to define a column in a models thatll take in a number and make it negative?

native tide
#

@prisma jackal just add an 'upvote' field to your model and handle the rest on the frontend.

#

@plucky tapir wdym by that

stone wren
#

@prisma jackal just add an 'upvote' field to your model and handle the rest on the frontend.
@native tide that and I would recommend running your view asynchronously

native tide
#

how could you do that? make it AJAX?

twilit needle
#

@twilit needle What authentication method are you using
@native tide hello

#

How can I make this possible

#

any ideas

native tide
#

Make what possible again?

twilit needle
#

sending the data and saving it as a cookie

stone wren
#

how could you do that? make it AJAX?
@native tide both platforms

frontend and backend

native tide
#

@stone wren Oh yea I gotchu. Frequent API requests from the frontend to update the counter async

#

@twilit needle So... do you have a separate frontend, or are you just using Django templates?

#

Wait that doesn't matter

twilit needle
#
import SideBar from './components/anchored/sideBar';
import './staticFiles/css/app.css';
import React from 'react';
import axios from 'axios';
import api_url from './configuration.js';
import RegistrationForm from './components/forms/authenticationForms';

class App extends React.Component {
    constructor(){
        super();
        this.state = {
            loggedIn: false,
            user: {}
        };
        this.handleLogin = this.handleLogin.bind(this)
    }

    checkLoginStatus() {
        axios.get({api_url}+'users/current-user/', {withCredentials: true})
            .then(response =>{
                if (this.state.loggedIn === false) {
                    this.setState({
                    loggedIn: true,
                    user: response.data.user
                })
                }
            })
            .catch(error => {
                if (error.response.status === (403 || 401) && this.state.loggedIn === true) {
                    this.setState({
                    loggedIn: false
                    /*the api raises an 403 NotAuthenticated error when trying to
                     fetch current-user data as an anonymous user */
                        });
                    } else {
                    console.log(error);
                        }
            })
    }

    handleLogin(data) {
        this.setState(
            {loggedIn: true,
            user: data.user}
        );
    }

    componentDidMount() {
        this.checkLoginStatus();
    }

    render() {
        if (this.state.loggedIn === true) {
            return (
                <div className="app-container">
                    <div className="app-mount">
                    </div>
                    <SideBar />
                </div>
            );
        } else {
            return <RegistrationForm />
            // bring up authentication container
        }
    }
}

export default App;
#

So this is what I am doing right now for the app.
I make a api get request for the current-user data and then if the api responds with an error [which means user isnt authenticated] then I bring up a login container

native tide
#

Nice, React, I like it

twilit needle
#

I am using reactjs for frontend

native tide
#

Okay, so what authentication method are you using?

twilit needle
#

idk sorry whats that

native tide
#

For example, session authentication or token authentication

#

In Django you have to specify your authentication method, and isAuthenticated checks against that.

twilit needle
#

So this is what I am doing right now for the app.
I make a api get request for the current-user data and then if the api responds with an error [which means user isnt authenticated] then I bring up a login container
@twilit needle is this best practice? like checking all those stuff, bringing up a login container and then after login deleting the container and finally bringing the app cointainer?

#

Ohh

native tide
#

Yeah, it's covered in Django authentication docs.

twilit needle
#

okay

native tide
#

For a React frontend I'd recommend token auth

twilit needle
#
class CurrentUserView(APIView):
    """
    An APIView to get the current user
    [authenticated user]
    """
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        serializer = CurrentUserSerializer(request.data)
        return Response(data=serializer.data)```
native tide
#

So setup that authentication, and whenever a user is added to your database, give them a token.

twilit needle
#

is this what I should do?

#

earlier I had this ```py
class CurrentUserView(APIView):
"""
An APIView to get the current user
[authenticated user]
"""
permission_classes = [permissions.IsAuthenticated]

def get(self, request):
    user = request.user
    serializer = CurrentUserSerializer(user)
    return Response(data=serializer.data)```
native tide
#

Yep

twilit needle
#

okay
is this best practice

#

do you recommend doing this

#

something seems wrong to me thats why I am not used to this type of coding

#

how do I setup authentication? can u pls link the docs

#

and @native tide should I implement the auth for the whole project or only specific api views

native tide
#

When you set the authentication method in settings.py, it is the default auth for every view which has the isAuthenticated permission (which can also be set as a default).

#

So you're setting it for the whole entire project

#

And if you want views without any auth, you can use a different decorator (forgot what it is, it's in the docs)

twilit needle
#

yeah I get it now thanks

#

omg my project will be so insecure if u didnt tell me this thanks

#

one sec il finish auth then what should I do

native tide
#

Have a look through Django auth docs. (or maybe it's DRF, can't remember) then ask any questions if you have any

#

I'll be back later and I can help you with the React stuff

#

but I got a lesson to go to

twilit needle
#

okay thanks

#

one last thing

#

so the token you told me, thats where Ill store my user object right

native tide
#

I don't understand the question

#

Each user in the database will have a token field associated with it

twilit needle
#

okay

#
class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })```
like this custom one what should my token have
native tide
#

so when you make a request to the API, it will have the token in the header, so the backend can know which user it is (from request.user which it handles)

twilit needle
#

the user?

#

ohh

#

I got it thanks

#

so I dont need a custom token?

vivid canopy
#

hey guys i did homework from flask from pirple but they rejected it third time and not answering me ....can u look at it what should be bad or where should be mistake bcs i think it's right ...maybe i didnt understand something right
note(i did change home with about...want to have about things in home page so bcs taht i change that)

this is what they want(picture)
this is what i send them -->https://drive.google.com/drive/u/0/folders/1V8nWd549asD79QprRmxvMbxhcY4-IUax

twilit needle
#

also this