#web-development

2 messages · Page 93 of 1

native tide
#

yes, I'm talking about the /register route which aaccepts both GET and POST

uncut spire
#

using something like flask_accepts

#

the flask.request object also has a method attribute, which will contain the relevant verb for a given request

native tide
#

Oh sorry maybe I expressed myself wrong

#

I meant, when I recieve a post request

#

I want to validate that there are no extra fields

#

and no wrong input on each form input

#

While having a React template

uncut spire
#

mmm why do you need to validate that there's nothing extra? just curious, like if i post you {'data': 'info', 'extra': 'foo'} is it that bad that i included extra?

#

you should validate the correct input using marshmallow and flask_accepts in my view, they are very easy to get started with

#

introduce a models.py specifying input and output let's say

native tide
#

Because (bad practice) curreently I just store the whole request on my db

#

first time working on web

uncut spire
#

ah

native tide
#

So when using postman, I realized how bad that is

uncut spire
#

yes not a great way to keep your sanity, but let's cover what you need

#

if you want to move on to using flask_accepts and swagger and api documentation/things of that ilk, post again and i'll help if i can

native tide
#

I'm checking out marshmallow right now

#

will note the others ones down

#

Thank you 🙂

uncut spire
#

np

native tide
#

so for marshmallow and flask_accepts (the plural one, not flas_accept, right?) it's a case of either, or?

#

Or are they used together?

uncut spire
#

they can be used together, or individually

#

typically, people use flask_accepts alongside flask_restx for autodocumenting APIs (though fastapi is looking better and better)

example:

# myproj/models.py
from marshmallow import fields, Schema

class RequestBody(Schema):
  my_field = fields.String(required=True)
  another_field = fields.String()

class ResponseBody(Schema):
  some_string = fields.String(required=True)
# myproj/app.py
from flask import Flask
from flask_accepts import accepts, responds
from flask_restx import Resource

from myproj.models import RequestBody, ResponseBody

app = Flask(__name__)

@app.route('/foo', methods=['GET', 'POST'])
class Foo(Resource):
  @accepts(schema=RequestBody, api=app)
  @responds(schema=ResponseBody, api=app)
  def get(self):
    pass  # your logic here

  def post(self):
    pass  # your logic here
#

and yes it's flask_accept_s_

#

but note the article i sent earlier, it outlines a way to do very vanilla flask with marshmallow doing the validation against a request.form or request.json

hallow jacinth
#

I am using regex to check passwords users input, I am not sure what Is wrong with this syntax

if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password):

anyone have an idea why I get the error
expected string or bytes-like object

topaz widget
#

@hallow jacinth Why are you checking users' password inputs? Frameworks should have this covered.

#

Also, which web framework are you using?

hallow jacinth
#

flask, and framework doesn't cover it, I can enter passwords like "test" and it accepts it

topaz widget
#

Well, first of all, you can combine all those regexes into a single one.

#

'[A-Za-z0-9]' will cover all those.

#

That doesn't really solve your problem, but it will make your code way more compact and readable.

hallow jacinth
#

oh cool, didn't kno I could compact it like that

topaz widget
#

yeah

#

I think the problem is with your password variable. For some reason it isn't the right data type.

hallow jacinth
#

yeah I just thought of that

topaz widget
#

It's not really possible to see what's wrong from what you posted.

hallow jacinth
#

it is PasswordField type

#

so I just have to figure out how to make it into string

topaz widget
#

It's probably an attribute of the PasswordField object.

#

maybe .value

#

That's what it would be in JavaScript.

hallow jacinth
#

yeah I am going to look at documentation to see if it is a specific value

topaz widget
#

If the PasswordField is an object, it's probably an attribute of that.

#

Make sure it escapes the characters, though, because someone might be able to run code if you don't escape the user input.

#

Flask might do that automatically, but it's good to make sure. Django escapes automatically.

native tide
#
class registerform(forms.Form):
    username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={"class": "form-control"}),
                               validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',
                                                          message='Username must be Alphanumeric',
                                                          code='invalid_username')])
    email = forms.EmailField(label="Email Address", widget=forms.TextInput(attrs={"class": "form-control"}))
    password = forms.CharField(label="Password", widget=forms.PasswordInput(attrs={"class": "form-control"}))
    confirm_password = forms.CharField(label="Confirm Password",
                                       widget=forms.PasswordInput(attrs={"class": "form-control"}))
#

Does anybody have an idea to how I can check that password and confirm_password are equal?

#

Within the class, not the view...

topaz widget
#

Is this Django? @native tide

native tide
#

Yes @topaz widget

topaz widget
#

The default process should check that automatically

native tide
#

Which process?

topaz widget
#

The built-in registration view

native tide
#

Yeah but I'm building my own form from scratch.

topaz widget
#

I'm sorry, the default UserCreationForm should check that.

#

Just extend the default UserCreationForm, don't start from scratch.

#
from django.contrib.auth.forms import UserCreationForm

class MyUserCreationForm(UserCreationForm):
...

@native tide

vestal hound
#

Yeah but I'm building my own form from scratch.
@native tide why?

native tide
#

Just thought it would help me understand it better. I can't remember stuff just off documentation

vestal hound
#

how about you look at how Django did it then

native tide
#

I am 😄

#

And I just implemented it, thanks for leading me in the right direction! :D@topaz widget I now understand how to do it.

topaz widget
#

np

weak chasm
#

if I'm trying to authenticate and authorize api's. what library/service do you recommend?
[i'm using django, but solution doesn't have to be a django specific solution ]

ebon beacon
#

I am writing a Rest API in Flask and noticed the request and response payload for some of the endpointsappearing in swagger do not tally with the namespace and resources in the controller

#

my user_account controller

details = CustomerDetailsResponse.api
cust = NewCustomerDto.api

_user = NewCustomerDto.user_account
_userdetails = CustomerDetailsResponse.userdetails
@cust.route('/')
class UserList(Resource):
    @details.doc('list_of_registered_users')
    @details.marshal_with(_userdetails, as_list=True, envelope='data')
    def get(self):
        """List all registered users"""
        return get_all_users()

    #@cust.response(201, 'User successfully created.')
    @cust.doc('create a new user')
    @cust.expect(_user, validate=True)
    def post(self):
        """Creates a new User """
        data = request.json
        return save_new_user(data=data)
#

my data transfer object

class CustomerDetailsResponse:
    api = Namespace('userdetails', description='Response object when fetching customer details')
    userdetails = api.model('user', {
        'first_name': fields.String(description='user first name'),
        'last_name': fields.String(description='user last name'),
        'membership_id': fields.String(description='membership id of the user'),
        'occupation': fields.String(description = 'occupation of user'),
        'mobile_number': fields.String(description = 'phone number of custmer'),
        'email': fields.String(description='user email address'),
        'enabled': fields.Boolean()
    })

class NewCustomerDto:
    api = Namespace('user', description='Registers new customer')
    user_account = api.model('user', {
        'first_name': fields.String(required=True, description='user first name'),
        'last_name': fields.String(required=True, description='user last name'),
        'username': fields.String(required=True, description='username'),
        'occupation': fields.String(description = 'occupation of user'),
        'mobile_number': fields.String(required = True, description = 'phone number of custmer'),
        'email': fields.String(required=True, description='user email address'),
        'password': fields.String(required=True, description='user password'),
    })
#

when I run in terminal I get this in swagger documentation -

#

Also my namespace -

from flask_restplus import Api
from flask import Blueprint

from .main.controller.user_controller import cust as customer
from .main.controller.user_controller import dea as deactivate
from .main.controller.lease_controller import emp as employee
from .main.controller.auth_controller import api as auth_ns

blueprint = Blueprint('cust', __name__)
cust = Api(blueprint,
          title='REST API AUTH WITH JWT',
          version='1.0',
          description='An API for a Rent Management System'
          )

register = Blueprint('dea', __name__)
dea = Api(register)

lease = Blueprint('emp', __name__)
emp = Api(lease)

validate = Blueprint('auth', __name__)
api = Api(validate)

cust.add_namespace(customer, path='/user')
cust.add_namespace(deactivate, path='/user')
cust.add_namespace(employee, path='/employee')
cust.add_namespace(auth_ns, path='/auth')
#

I am coming from a C# background, so I have limited experience writing APIs in Python (Flask). How can I resolve this?

plucky tapir
#

To make sure my form submission works, should I get the information and display it in an html form, should I just display the inputs on another page?

vestal hound
#

if I'm trying to authenticate and authorize api's. what library/service do you recommend?
[i'm using django, but solution doesn't have to be a django specific solution ]
@weak chasm DRF?

weak chasm
#

@vestal hound vanilla

vestal hound
#

doesn't Django already have support for that

#

using...decorators, I think?

native tide
#

Hello

#

I'm new to Django and I'm wondering why this

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
       {% for posts in posts %}
            <h1>{{ posts.title }}</h1>
            <p>By {{ posts.author }} on {{ posted.date }}</p>
            <p>{{ posted.content }}</p>
       {% endfor %}
    </body>
</html>
```Isn't loading
#

When it's supposed to show

posts = [
    {
        'author':"Fairy King Lucifer",
        'title':"Becoming the Fairy King",
        'content':"This is how I became one of the few Fairy Kings to ever live.",
        'date':"August 22, 2020",
    },
    {
        'author':"Demon King Lucifer",
        'title':"Becoming the Demon King",
        'content':"This is how I became one of the few demon Kings to ever live.",
        'date':"August 21, 2020",
    }
]
vestal hound
#

...

#

for posts in posts?

#

how about for post in posts

#

also, you have posts and posted

#

posted doesn't exist

#

the latter is the ultimate cause of your problem

native tide
#

Ohh thanks

#

Sorry that I wasted your time

vestal hound
#

Sorry that I wasted your time
@native tide you didn't

#

but I would really suggest you use better names

#

for posts in posts is doubly confusing because you use a plural term "posts" for a single post, and because the element and the collection are called the same thing

native tide
#

I have changed it

#

Thank you for the help

vestal hound
#

yw!

#

🙂

native tide
#

Ahh I may need more help

#

Now it's not showing any thing

stable kite
#

tell what help

native tide
#
<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
       {% for posts in post %}
            <h1>{{ post.title }}</h1>
            <p>By {{ post.author }} on {{ post.date }}</p>
            <p>{{ post.content }}</p>
       {% endfor %}
    </body>
</html>
```Thats the html code

from django.shortcuts import render

post = [
{
'author':"Fairy King Lucifer",
'title':"Becoming the Fairy King",
'content':"This is how I became one of the few Fairy Kings to ever live.",
'date':"August 22, 2020",
},
{
'author':"Demon King Lucifer",
'title':"Becoming the Demon King",
'content':"This is how I became one of the few demon Kings to ever live.",
'date':"August 21, 2020",
}
]

stable kite
#

open developer tools check if get your html code there

native tide
#

Nothing

stable kite
#

try to rerun the server

native tide
stable kite
#

check your url & views

native tide
#

Urls

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='blog-home'),
    path('about/', views.about, name='blog-about'),
]
```Views
```Python
from django.shortcuts import render

post = [
    {
        'author':"Fairy King Lucifer",
        'title':"Becoming the Fairy King",
        'content':"This is how I became one of the few Fairy Kings to ever live.",
        'date':"August 22, 2020",
    },
    {
        'author':"Demon King Lucifer",
        'title':"Becoming the Demon King",
        'content':"This is how I became one of the few demon Kings to ever live.",
        'date':"August 21, 2020",
    }
]

def home(request):
    context = {
        'posts': post
    }
    return render(request, 'blog/home.html', context)

def about(request):
    return render(request, 'blog/about.html')
stable kite
#
<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
       {% for posts in post %}
            <h1>{{ posts.title }}</h1>
            <p>By {{ posts.author }} on {{ posts.date }}</p>
            <p>{{ posts.content }}</p>
       {% endfor %}
    </body>
</html>```
#

@native tide you spelled it wrong it should be posts.author but you wrote post.author

native tide
#

I just changed it

stable kite
#

ok

native tide
#
<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
       {% for posts in post %}
            <h1>{{ posts.title }}</h1>
            <p>By {{ posts.author }} on {{ posts.date }}</p>
            <p>{{ posts.content }}</p>
       {% endfor %}
    </body>
</html>
stable kite
#

ya it should work now

native tide
#

Still nothing

stable kite
#

ok just a second

#

@native tide <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date }}</p> <p>{{ post.content }}</p> {% endfor %} </body> </html>

native tide
#

I will try that

stable kite
#

ok

native tide
#

Okay it worked

#

Thanks

#

Just the title didn't show up

stable kite
#

ya you mis spelled the context variable in you template

#

check it out again i fixed it

native tide
#

Okay

#

Thanks so much for the help

stable kite
#

No problem

native tide
#

IIT WORKED

onyx crane
#

Django:
What do i have to do to be able to use .scss files instead of .css ?

stable kite
#

@onyx crane check it's documentation it will help you to solve our problem

native tide
#

me having no idea what a .scss file is

onyx crane
#

so i assume, this is the propper way of implementing it ?
Install the package under installed apps ?

plucky tapir
#

Is this ‘u’ thing me? Or python converting from html form?

#

Is it just from print, and doesn’t actually have a u in its submission?

versed python
vestal hound
#

I just changed it
@native tide the other way round...

#

which makes more sense to you in English?

#

“for post in posts” or “for posts in post”?

native tide
#

Yea your right but English isn't my main. My main is like Latin

plucky tapir
#

Thanks

#

Out of curiosity which db language do you guys prefer with flask? I've read you shouldn't get into too much of sql lite if you're more serious about db in the future

marble carbon
#

if you're using SQLAlchemy with Flask, which you should be

#

then you can pick any db

plucky tapir
#

You guys recommend flask over django for first time web development? as a middleman between databases and front end. Plan to have an admin page eventually

versed python
#

both have their places, django puts some rules in place so you have a consistent project structure that just works. Flask is generally easy to learn. At the end of the day, go with what suits you, not what people think you should use.

plucky tapir
#

I spent a good amount of today doing things in flask, but maybe I should give the other a shot as well. django seems to have a lot of features I'd probably have to really dive into to learn for flask, idk how much more time consuming it'd be to implement database/security/admin features

marsh canyon
#

django takes time to pickup tho, learning all the stuff that is built in and using them.

fallen mango
#

Can anyone suggest me some project idea to learn Django rest framework?

versed python
#

todo app lol

marsh canyon
#

any app but just use drf

#

or convert ur existing projects to use drf

#

i had a social media site built with pure django first, then I changed it to use drf and vanilla JS

onyx crane
#

whats drf ? I though it was django rest framework => django

vestal hound
#

You guys recommend flask over django for first time web development? as a middleman between databases and front end. Plan to have an admin page eventually
@plucky tapir if you have experience with Python but not with web dev, I would reco Django

#

it makes many decisions for you

onyx crane
#

can anyone make any sense out of that error msg ? (@me)
I've used it just like they describe in the documentation... + im using the endcompress tag in the next line

native tide
#

Can anyone tell me what is wrong

onyx crane
#

do a propper screenshot and then maybe

vestal hound
#

@native tide post errors as text.

stable kite
#

It's indentation error I think so

plucky tapir
#

First impression I thought django had a lot code written beforehand but it looks like a lot of it is imported, mainly settings having the most preset code?

versed python
#

Tbh most of the code written before-hand are just comments

zealous cloud
#

Hello, I am having an issue with my testing db. Using postgres and when i run this test file the test data is overriding my db data and saving the test data! I have no idea what I'm doing wrong. My app database is called informed_voter_db and my test db is called voter-test. Can someone help me out? Below is the file setup and teardown. The users in this file are being saved to my app db and all other data being deleted.

os.environ['DATABASE_URL'] = "postgresql:///voter-test"

# Create tables and delete data in each test

db.create_all()


class UserModelTestCase(TestCase):
    """Test views for users"""

    def setUp(self):
        """Create test clien and sample data"""
        db.drop_all()
        db.create_all()

        test_user1 = User.signup('tester@test.com', 'tester987', 'password1')
        test_user1id = 99999
        test_user1.id = test_user1id

        test_user2 = User.signup('mcnair@test.com', 'McNair', 'qwerty')
        test_user2id = 1001
        test_user2.id = test_user2id

        db.session.commit()

        test_user1 = User.query.get(test_user1id)
        test_user2 = User.query.get(test_user2id)

        self.test_user1 = test_user1
        self.test_user1id = test_user1id

        self.test_user2 = test_user2
        self.test_user2id = test_user2id

        self.client = app.test_client()

    def tearDown(self):
        res = super().tearDown()
        db.session.rollback()
        return res
zealous cloud
#

Never mind. Figured it out. Used URL instead of URI. The eyes get tired at night. Also forgot app.config["SQLALCHEMY_ECHO"] = False

void patrol
#

Hey guys. I just want to know how can I use the flask app context in a thread?

#

My code here raises a RuntimeError:

from flask import current_app as app
from threading import Thread
from flask_mail import Message
from .. import mail


def thread_send_mail(msg: Message) -> bool:
    with app.app_context():
        try:
            mail.send(msg)
            return True
        except ConnectionRefusedError as e:
            print(e)
            return False


def send_mail(to: str, subject: str, text: str, html: str, from_: str = "info@simplymeet.gq"):
    print(app.config)
    msg = Message(subject, to, text, html, from_)
    Thread(target=thread_send_mail, args=[msg]).start()
#

And this is my folder structure. The current python file is mail_helper.py

| src
|-- __init__.py
|-- routes.py
|-- util
|---- __init__.py
|---- mail_helper.py
| ...
#

Please mention me while providing an answer. Thanks

void patrol
#

nevermind, i just didnt use threading and it worke

low blade
#

is it a better idea to containerize everything if im intending to add more things (like another web api or web app) on the same host as my bot?

snow moss
nova storm
#

@native tide

native tide
#

Hello guys i need help i want to know how to create a route that a admin can access in which i can create posts for my blog i dont know how this work

#

and how am going to get the that route after deploying

versed python
#

@native tide if you're using django, then look into "view level permissions"

native tide
#
[{"quote":"I can't even say the word 'titmouse' without gigggling like a schoolgirl.","character":"Homer Simpson","image":"https://cdn.glitch.com/3c3ffadc-3406-4440-bb95-d40ec8fcde72%2FHomerSimpson.png?1497567511939","characterDirection":"Right"}]```
#

If this is my API response, how can I select "quote" if the braces are in the way?

#

In JavaScript

versed python
#

response[0].quote @native tide

native tide
#

Thank you! 😄

twilit dagger
#

There is margin-bottom:0 on navbar and margin-top: 0 on content

native tide
#

@twilit dagger are you using bootstrap?

twilit dagger
#

Yes

#

@native tide

native tide
#

What class is the content div? Have you tried container-fluid?

twilit dagger
#

container-fluid increases the margins lol

#

there was container on the content div but the gap remains even after I removed it

#
        <img class = "top-image" src = "../../media/arling>
        <div class = "text-overlay" id = "top-image-text">
            <h1>Nimbus Communications</h1>
        </div>
    </div>

#content-section{
    margin-top: none;
}```
plucky tapir
#

With django if I wanted to share a few web pages I made through github with someone else, would you upload all the files even if you didn’t use them all yet? That django created by default

swift sky
#

if anyones used wtforms before, do you guys know if the checkbox logic goes in the form class?

#

like do the options in my check boxes need to be variables in my form class

#

im trying to set this up such that if a person selects one of the check boxes, a different set of options appear as a subsection

versed python
#

@plucky tapir ofc, why leave something you'd have to do later anyway

native tide
#
<script>
    $(document).ready(function(){window.setTimeout(function(){
        $(".alert").fadeTo(500, 0).slideUp(500, function(){
            $(this).remove();
        });
    }, 5000);})
</script>```
#

i have this script tag in my template

#

and it doesn't work

#

This script tag is for when an alert message pops op

#

I want it to fade away after a couple of seconds

#

{% if messages %}
    {%for message in messages%}
    <div class="alert alert-success" role="alert">
       {{message}}
      </div>
    {%endfor%}
{% endif %}```
#

but when I click inspect and go to the console

#

I see this error

#
?user_login=/all-users/:10 GET http://localhost:8000/login/jquery-3.5.1.min.js net::ERR_ABORTED 404 (Not Found)
?user_login=/all-users/:43 Uncaught ReferenceError: $ is not defined
    at ?user_login=/all-users/:43
(anonymous) @ ?user_login=/all-users/:43```
#

The jquery cdn is in the head tag

#

like so <script src="jquery-3.5.1.min.js"></script>

#

I have no idea why it doesn't work

plucky tapir
#

It’s looking like the django way is to categorize everything in their own apps within the project. I’m trying to figure out the purpose, This would help with more features later on and organization?

a register and login page considered under the main app?

twilit dagger
#

Yes in a users app @plucky tapir

plucky tapir
#

Ah yes thanks

It seems like there’s be main, users, then one for like info on your site.
Like articles if you had a blog site

A few like that, seems right? Or does it get broken down into a lot more apps

twilit dagger
#

Usually I've seen a home/whatever is the main on your site, and stuff like about and contact goes in there too, then a Users app and then stuff like shop, forums, etc.

#

So actually I've mostly seen only 2 apps for most websites

plucky tapir
#

👍
One option to go from userinput to db, I could create an html form, post the input to a model and migrate it to a database?

twilit dagger
#

Django provides you a default CreateView for making models @plucky tapir

#

You don't have to make a form

#

Django gives you a lot of things from the get-go

swift sky
#

any experience with ListWidget from wtforms

plucky tapir
#

@twilit dagger CreateView would still need a template right? Would it sortof be a substitute for the html? Would it much more convenient in the long run to use modelform rather than html?

twilit dagger
#

All you need to put in a CreateView template is {{ form.as_p }} @plucky tapir

#

Or better is to use Crispy Forms, then it's just {{ form|crispy }} and it looks much better

#

That's it

#

It makes the form and creates the model for you, you just have to make a submit button

#

It's far far more convenient to use the Views Django gives you, though in certain cases you still have to use ModelForms, no point in using base html forms.

#

Django gives you CreateView, DeleteView, ListView, DetailView, UpdateView etc. It also gives you LoginView and LogoutView

plucky tapir
#

Using the views from django, push/pulling info to/from the database will be significantly more convenient?

#

feels like django has the ability to make it mainly a python project

twilit dagger
#

yeah it does

#

no point in doing stuff the hard way if its all given to you

topaz widget
#

Hey does anyone know the best way to keep text on a page at the same location when the page / element it's inside of resizes?
I have a slide-out navigation panel on my web page, and I need wherever the top of the page is to stay the same when I expand/collapse the panel.

plucky tapir
#

My issue is I have a partner who doesn’t know python but is doing the css/html and dB side of things. Django feels like it removes their contributions from the project

Although thinking of finished product in a short time it seems like django is the way to go.

topaz widget
#

@plucky tapir They need to learn Django's templating language, and you should be handling database stuff since most of that is taken care of by Django's ORM.

#

They should probably also "git gud" with JavaScript if they're going to be taking on the front-end part of it.

#

Django's templating language is not that hard to learn if that's all you need to learn.

#

@plucky tapir Your division of labor doesn't make a lot of sense. Usually isn't front-end and back-end. Having someone doing HTML/CSS AND database while you work with the back-end framework is not a great division of labor.

#

You should be handling the database.

mortal shale
#

How can I capture whenever a POST request is sent to my rest api in django
Because I want to do something whenever that happens so how do I detect it as soon as it does happen

plucky tapir
#

@topaz widget Thank you got it. So if I continue with django, there are still a lot of areas that html/css could still give a good amount of labor? If so what type of stuff would that be, I had the idea that using views almost removed html use.

topaz widget
#

You can't really remove the HTML use. Views in Django use HTML templates to render the pages. Your partner would just design the pages, and they could either learn Django's templating syntax, or you could just modify the HTML pages to add the templating syntax. It's probably better if they learn the syntax, though, since you will have parent and child templates, and someone will be doing a lot of extra work if the Django templating language isn't just used from the start.

#

@mortal shale Every request will have a method. If the request's method is POST, then do something in the view that handles that.

mortal shale
#
class HeroViewSet(viewsets.ModelViewSet):
    queryset = Hero.objects.all().order_by('name')
    serializer_class = HeroSerializer
#

is there a request type arg?

#

@topaz widget

topaz widget
#

There is a request object that would be handled by a view. This request object will have the HTTP request method (POST in this case) as an attribute.

#

Yes, it would be an argument to a view, as well, to answer your question further.

mortal shale
#

so I can put it in my HeroViewSet class as an argument or?

topaz widget
#

I'm not sure. I don't really know what the ModelViewSet class does.

#

I've never really worked with DRF

oak stratus
#

Hi, I'm trying to generate a database with MySQL and MAMP. I installed sqlAlchemy to generate a data table but it didn't work. I am having this problem and already installed the libraries mysql flask-sqlalchemy, etc with terminal and python libraries.

Don't know what else I can do.

Love

plucky tapir
#

@topaz widget I'm going to try to convert an html template to a django template to see the difference. Django would remove the need of creating/modifying databases because views handles it directly correct?

topaz widget
#

I'm not sure I follow what you're saying in either of those sentences.

#

@plucky tapir Not sure what you're saying. It's hard to render web pages with Django without making it a "Django template".
As for the database, Django models handle all the database stuff. You need to configure your database in settings.py, if you don't want to use the default sqlite database, but that's pretty much it.

marsh swan
#

Yo - I'm using flask and having a weird issue where a route creates a form which immediately procs "submit"

native tide
#

@swift sky yeah I have some experience with wtforms, whats up?

marsh swan
#

This has the rest of the code too

#

the issue is i want to dynamically be able to add scores on a page - so i have two forms

#

one is the base, which contains just scores and a submit button, and the other specifies the scores through a fieldlist of formfields

#
class PowerGridScore(FlaskForm):
    scores = FieldList(FormField(PowerGridForm), max_entries=6)
    submit = SubmitField('Submit')
#

Therefore for the route I have to do something like

#
scoreformname = game.gname.replace(' ','')+'Score'
baseformname = game.gname.replace(' ','')+'Form'
current_mod = sys.modules[__name__]
score_form = getattr(current_mod, scoreformname)
base_form = getattr(current_mod, baseformname)
class LocalForm(score_form):pass
LocalForm.scores = FieldList(FormField(base_form), min_entries=int(entries), max_entries=6)
form = LocalForm()
#

if i check submission of the form with form.validate_on_submit(), it IMMEDIATELY procs

#

the only workaround I've seen is just if request.method == 'POST': instead of if form.submit(): or even if form.validate_on_submit():

#

if i use validate, even though the field list is called with proper validators (datarequired() ) it will never actually validate

#

if I use submit, it never displays the page to begin with and just immediately redirects me

#

why does that newly created form immediately get submitted?

#

is there a better way to do this instead of checking if POST? i feel like that exposes me to just malicious code that could be interpreted but idk if wtforms handles that

#
class PowerGridForm(FlaskForm):
    player = StringField('Player', validators=[DataRequired()])
    plants = StringField('Plants', validators=[DataRequired()])
    money = StringField('Money', validators=[DataRequired()])
#

that's the other form getting fieldlist'ed

plucky tapir
#

@topaz widget I already have html files that would submit input, I would send that to a database using flask. Today I was going to try to convert the html into django templates to see what it is like. but I don't really see any examples online (to see a side by side comparison.)

topaz widget
#

It's probably somewhat similar to Flask. I think Flask uses Jinja, which is not that different from Django.

#

@plucky tapir If you have a bunch of HTML templates that are written in Jinja and it will be a lot of work to change them, you can also specify in your project's settings.py file that you want to use a different templating engine than the Django default. I have not done this, so I do not know the details. It is possible, though.

marble carbon
#

well you can use jinja as templating engine in Django as well

#

but Django template language is not much different from Jinja anyway so won't be much of a hassle converting them

fallen peak
#

It's probably somewhat similar to Flask. I think Flask uses Jinja, which is not that different from Django.
@topaz widget fun fact, jinja2 was created based on django templating engine and the same creator made a fork of it for php

swift sky
#

@native tide I am trying to build a "survey form" which has multiple choice, open ended, and questions need to appear depending on responses

#

how would you approach htis

zealous cloud
#

Im trying to deploy my Flask app to heroku, but it's not working. Im trying to figure out the issue, but cant quite figure it out. First time deploying to heroku. I think it might be an issue with bootstrap? Can anyone take a look at my logs and tell me what im not seeing please?
https://pastebin.com/3wdWCicA

vestal hound
#

@zealous cloud 2020-09-26T00:00:33.084755+00:00 app[web.1]: ModuleNotFoundError: No module named 'keys'

zealous cloud
#

@vestal hound Oh shoot thats my api key. I put it into a separate file and put that into my git ignore. Is there a way to include it into the project without hard coding it in obviously?

vestal hound
#

why is it in your .gitignore

#

your server needs it

zealous cloud
#
venv/
__pycache__/
.DS_store
keys.py
.vscode
vestal hound
#

huh

#

why is it in your .gitignore

#

that's what I'm asking

#

like

#

your server files won't be visible

#

to outsiders

#

it's fine to put it there

zealous cloud
#

oh because its my api key. It was my understanding that you dont want that in your project files?

vestal hound
#

hm

#

not if your code is public

#

but if you're only pushing to Heroku

#

(i.e. not hosting on a public GitHub repo or something)

#

it's fine

#

because ultimately

#

you need to have some sort of credentials in your server code, right?

#

otherwise how will you authenticate

zealous cloud
#

so push to heroku master with the api key but not to github correct?

#

correct. hadnt considered that. thank you. I didnt include it because I also have a github repo for it and thought somehow id be publishing the api key in my code'

vestal hound
#

so push to heroku master with the api key but not to github correct?
@zealous cloud yup!

#

correct. hadnt considered that. thank you. I didnt include it because I also have a github repo for it and thought somehow id be publishing the api key in my code'
@zealous cloud yeah, that's a good thought

#

it's great that you're considering the security implications

#

another way to do it is with an environment variable

#

I would suggest not using a .py file

#

some data file might be better?

#

like a JSON

#

or .env

#

even a .txt is fine

zealous cloud
#

that makes more sense now that you mention it. Thank you again. I'll look into a way to do that after I get it up and running.

vestal hound
#

yw!

urban wyvern
#

I'd put it as an environment variable and then load it in with os.getenv("NAME_OF_VAR")

#

Rather than keeping the code in a file at all

vestal hound
#

Rather than keeping the code in a file at all
@urban wyvern why?

urban wyvern
#

Avoid the potential of accidentally publishing it anywhere

vestal hound
#

they can leak (depending on the deployment environment)

marble carbon
#

there's a package called python decouple for that

#

heroku has config vars in project settings, which are equivalent to environment variables

zealous cloud
#

I used environment variables for my database and secret key. Not sure why I didn't think of doing it with my api keys also. BTW my project opened successfully

native tide
#

I'm using flask with my first try of blueprints, here is my tree:

├── app.py
├── LICENSE
├── PaktMonitor
│   ├── appliance
│   │   ├── __init__.py
│   │   ├── models.py
│   │   └── routes.py
│   ├── __init__.py
│   ├── user
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── routes.py
│   │   ├── static
│   │   │   └── main.css
│   │   └── templates
│   │       ├── base.html
│   │       └── login.html
│   └── views.py
├── README.md
├── requirements.txt
└── run.sh

Whenever I go to any of the urls, such as /user/login, this is the result:

$ curl localhost:5000/user/login
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>

No matter what I do, there is a 404 on every page.

plucky tapir
#

Is the django templates have a quick learning curve? I can just read basic html tbh

versed python
#

if uk python, django template language doesn't require much learning

#

just go over the docs and you'll be fine

solemn igloo
#

i loaded my style.css in static folder but the images dont show up on my site

#

can anyone help me?

cosmic nebula
#

@rotund token I'm here

rotund token
#

does anyone know a bit of html as i need help with making this contact form stack on top of eachother and need it on the right. TAG ME

#

ok @cosmic nebula

cosmic nebula
#

Use FlexBox API

rotund token
#

i loaded my style.css in static folder but the images dont show up on my site
@solemn igloo make sure you link them properly and have the right names and tags

#

how

cosmic nebula
#
/* style.css */
.container {
  float: right;
  display: flex;
  flex-direction: column;
}
rotund token
#

did u see my github

cosmic nebula
#

Or you can remove float and make the position: absolute; and then adjust/set the right to some viewport width

#

did u see my github
@rotund token no where is the link

rotund token
#

@cosmic nebula

cosmic nebula
#

Can you tell me where your code is? I'm on mobile rn and it's kinda hard to go through your code

#

Like the file and the line number

rotund token
#

wdym

cosmic nebula
#

Or your can tell me the class'name

#

In CSS

#

Like .container or whatever you named it

rotund token
#

ok let me find it

cosmic nebula
#

You can share a line by clicking on the line number and then clicking on the three dots and share

rotund token
#

ill just grab the class

#

the class is contact

cosmic nebula
#

And it's children?

rotund token
#

.contact

cosmic nebula
#

Ok found it

rotund token
#

ok so it worked and its on the right

#

now i want it to stack on top of eachother

cosmic nebula
#

Wdym

#

Does it have any children?

rotund token
#

wdym

cosmic nebula
#

Like contacts

rotund token
#

ur confusing me

cosmic nebula
#

Or does it have a parent?

#

A parent container?

#

Which should hold all the contacts as a stack

rotund token
#

there is a .container

#

over everything

cosmic nebula
#

Ohkay

#

That's a bad use tho

rotund token
#

i want it to look like this

cosmic nebula
#

Because you what this container to be different don't you?

#

Yea

#

Use labels too

rotund token
#

yeh there is 2 lables

cosmic nebula
#

The Email is s label

#

Yes

rotund token
#

lable for = 'email'

#

label for ='message'

cosmic nebula
#

Make a different container class for contacts

rotund token
#

yeh there is a div

#

and the class = contact

cosmic nebula
#

Cause of you change the main container class, all elements having that parent class will behave like a stack

#

No no

rotund token
#
  <div class="contact">
        <form action="#">
          <label for="email">
            Email: <input type="email" id="email" placeholder="Enter your email">
          </label>
          <label for="messages">
            Message: <textarea id="message">Message</textarea>
          </label>
          <input type="submit" valid="Send Message" id="submit-button">
        </form>
      </div>```
cosmic nebula
#

Ohkay

#

Then just add ```css
display: flex;
flex-direction: column;

#

And lemme know if it works

rotund token
#

hold on

cosmic nebula
#

Also I think this is how you use a label

<label for="email">Email: </label>
<input type="email" id="email" />
rotund token
#

ok it worked but now its too low

#

@cosmic nebula

cosmic nebula
#

Use divs to cover all the label+inputs

rotund token
#

i have ill commit and push so u can see

cosmic nebula
#

Yea

#

Also I don't think it's too low

rotund token
#

re fresh

#

it should update code

cosmic nebula
#

You just have to postion the submit button a bit below

#

Yea

#

Add a .submit class for the submit button and style it

#

And then change its top value to a larger value

#

Or you can change the bottom value too

rotund token
#

confused me

#

yeh there is a div

cosmic nebula
#

<input type="submit" class="submit" />

rotund token
#

div class='submit-button-wrapper'

cosmic nebula
#
.submit {
  /* Style it, like color or background-color, etc. */
  bottom: /* some value */%; /* or even vw works instead of % */
}
rotund token
#

like margin

cosmic nebula
#

Yea that works too

rotund token
#

so

cosmic nebula
#

margin-bottom

rotund token
#
.submit-button-wrapper{
  margin-bottom :
/* STYLE BUTTON */
}```
#

how would i get the links to go lower as i did margin-top N it didn't go lower

#

@cosmic nebula

cosmic nebula
#

What links?

#

Also I meant styling the button itself, not it's wrapper

rotund token
cosmic nebula
#

Try postion: absolute; top: 95vh;

#

You can change the value 95 until it looks good

#

Remember it shouldn't be greater than 100 cause that will put the elements below the viewport

rotund token
#

wdym

#

ok thanks tho

#

appriciate it

brittle basin
#

Hello, for some reason when I deploy my simple flask app to Heroku it says it can't find flask

cosmic nebula
#

ok thanks tho
@rotund token did it work?

brittle basin
#

Any idea what's wrong?

lapis spear
#

yo how can i pass variables to my base template is it possible?

trail axle
#

Are there any Python things I can use for front-end alongside HTML and CSS? No browser supports Python, yes, but are there are any things I can compile from Python to JS, either manually or not? Brython compiled it very incorrectly.
From what I’ve searched, Flask and Django are for backend.

near bison
#

Can postcss with plugins completly replace SASS

strange briar
#

And this is my dockerfile
@brittle basin do you need Ubuntu or just python ? Usually good practice is to separate front end, back end, and db with docker and link them with docker compose, so if i was you i'd directly take an image of python instead of ubuntu:latest

brittle basin
#

Thanks I'll check that

formal haven
#

anyone have experience with scrapy-splash? I'm trying to get the variables inside my return function, but the response object only has the body, without the variables i want to pass

stable kite
#

How to upload images from webpage to Django & through Django to firebase without using forms?

mortal shale
#

how do i allow pypi packages in my django site

mortal shale
#

for example urllib3

#

because im trying to use the requests module

#

https://pypi.org/project/urllib3/

strange briar
#

does anyone know about fastapi ? i'd like to build a fastapi project, and i'd like to put my users models and endpoints inside a subfolder just like this

backend
├── main.py
├── ...
│   ├── users 
│       ├── models.py
│       └── users.py
│       └── ...

so like a django project with multiple apps, can anyone tell me how to do this with fastapi ? i see mount and router, but i don't understand the difference between both

bronze notch
#

Is there anyone here who knows about flaske and can speak German.

#

I need some help

#

🥬

rotund token
#

does anyone have any front end web development courses as i’m trying to learn

#

tag me

native tide
#

What are the key differences between Sanic and Aiohttp server?

#

PING ME on answer!

wicked lodge
#

Can someone explain to me in simple terms. The purpose and use case of the SECRET_KEY inside config file in Flask
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

warm igloo
#

Read up on 12 factor apps and managing config through environment for each deployment target @wicked lodge

wicked lodge
warm igloo
wicked lodge
#

👍

crude heath
#

Guys how can I make an image cut out extra spaces instead of squeezing?? in html and css

warm igloo
#

Is the extra space IN the image, or in the HTML around the image?

crude heath
#

in the image, like say if I want the image to be square, but it's a rectangle, I'd want to cut off parts of the side to make it square rather than squeeze it into one

acoustic oyster
#

in the image, like say if I want the image to be square, but it's a rectangle, I'd want to cut off parts of the side to make it square rather than squeeze it into one
@crude heath PIL (pillow) has builtins for that I am sure

topaz finch
#

Is it not possible to use the default sqlite module in a flask application?
@ me when answering, please.

native tide
#

@crude heath wrap the image in a div with a max width; say 100px, with overflow-x: hidden?

quick cargo
#

or...

#

use the actual object css properties

#

object-fit: contain;
object-fit: cover;
object-fit: fill;
object-fit: none;
object-fit: scale-down;```
wanton turtle
#

That's my search engine!

#

Here's my other sites which I have a doubt. https://austrix.itf.repl.co I want it to be the RALEWAY font not the horrible default heading on iOS!

topaz finch
#

Does trying to use both SQLAlchemy and the default sqlite module screw up Flask apps?

@ me when answering.

native tide
#

When I launch the localhost:8000 server on my computer, is it possible to access it via my phone?

native tide
#

Is it possible?

stone schooner
#

If you are on the same network you can probably set up some proxy, but not out of the box no.

Android can do forwarding afaik, not sure about Ios devices

lavish plover
#

Hello:) I've got a question for you ppl.
What's better / when to use Django template vs sending JSON to JavaScript?

#

When I launch the localhost:8000 server on my computer, is it possible to access it via my phone?
@native tide I think it's possible

#

ATM I don't remember in which list you need to append it

#

ALLOWED_HOSTS = ['*']

native tide
#

🤔

lavish plover
#

And in your terminal

#

$ python manage.py runserver 0.0.0.0:port

#

In port you put any port you want I think

#

try with 8000

#

Oh, and in your phone

#

You go to http://your-ip-address:port

native tide
#

O kay

lavish plover
cursive violet
#

Would Django be a good tool to create a website for image archiving?

#

I'm working on a family archive project, and would like a place for people to see the photos (and potentially upload their own)

lavish plover
#

Yeah I think so

#

Would Django be a good tool to create a website for image archiving?
@cursive violet You could use something like AWS' S3 to save those photos

#

Or you could set your own NAS:)

cursive violet
#

well yeah, but i just mean for getting all of the tools and stuff

#

like i want to implement face tagging and other shit

warm igloo
#

yeah, there are python libraries for that you can use

#

doubt they're django specific

#

django would be good cause you'd get an admin piece right out of the gate to help you manage what you build

sly canyon
#

In computer science, session hijacking, sometimes also known as cookie hijacking is the exploitation of a valid computer session—sometimes also called a session key—to gain unauthorized access to information or services in a computer system. In particular, it is used to refer ...

stable kite
#

How to upload files to Django through Ajax ?

bronze notch
#

that's flask

#

if you can solve this problem you will get lemon pepper wings

heady field
#

Hi here, how to make vscode check the site-packages of my virtualenv?

limber laurel
#

How in django can I use cache_control with a class based view?

limber laurel
#

It doesnt expalin how I can use that function specificvally

#

as it is a decorator but I am not sure how I can use3 decorators in class based viewws

#

Oh it expalins that, ty, but Im not sure how I could use multiple decorators

vestal hound
#

just stack them

#

@limber laurel

limber laurel
#

How?

#

cache_control(private=True)cache_page(60 * 2)(views.ProfileView.as_view())

#

If I do it like this it gets underlined red

vestal hound
#

no

#

like one per line

limber laurel
#

?

#

Wdym?

#

if I use it above the class definition I get this error:

#

path('profile/', cache_page(60 * 2)(views.ProfileView.as_view()), name='profile-view', ),
AttributeError: 'function' object has no attribute 'as_view'

quasi wigeon
#

how can i build this one and make it work using Django

marble carbon
#

it isn't Django specific

#

put Javascript and css for this in the template

sleek trout
#

it isn't Django specific
@marble carbon

Yup thunder is right

#

Theres nothing to with django.... It will fine with javascript

swift sky
#

im using wtforms to build a survey

#

idk how to make it so that depending on the answer to question, a new set of questions appear

#

any ideas?

errant creek
#

Are there any beautiful soup experts in the house?

#

For example

#
<h2>Main Title</h2>

<p>Here is a subtitle text</p>

<p>
    <strong>Bold title 1</strong>
</p>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>

<p>
    <strong>Bold title 2</strong>
</p>

<ul>
    <li>Stuff</li>
    <li>I</li>
    <li>don't</li>
    <li>want</li>
    <li>to</li>
    <li>capture</li>
</ul>

<p>
    <strong>Bold title 3</strong>
</p>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
</ul>
#

Is there a way I can just grab the Bold title 1 and it's items, skip bold title 2 and it's items, then capture bold title 3 and it's items? Is that possible?

swift sky
#

not sure if this is the right subchannel for that, but good luck

errant creek
#

Or would I be able to achieve this with another utility like scrapy or selenium?

#

Ugh, I started in advanced discussion, they told me to come here 🤦‍♂️

#

Where should I go to find the answers since google isn't helping?

marsh canyon
#

so u mean alternate items @errant creek ?

#

or just ignore Bold title 2?

errant creek
#

Thanks @marsh canyon. Ignore bold title 2 and it's items

marsh canyon
#

alright

errant creek
#

So capture bold title 1 and 3 and their items (for clarification)

marsh canyon
#

so firstly u will want to get all the p tags and ul tags, delete the first p tag as its not needed

#

right

errant creek
#

Sounds like it would be a long argument

#

Is beautiful soup the best utility for something like this, in your opinion?

marsh canyon
#

not sure, i have only used bs4

#

give me a min, lemme try

errant creek
#

Cool. Appreciate the help

marsh canyon
#
soup = BeautifulSoup(x, "lxml")

paragraphs = soup.find_all("p")

del paragraphs[0]

uls = soup.find_all("ul")

for p, ul in zip(paragraphs, uls):
    if p.text.strip().endswith("2"):
        continue
    # you got your title 1 and 3 
    print(p.text.strip())
    print(ul.text.strip())```
#

@errant creek

#

x is the html string which u sent above

errant creek
#

Got it. I'm assuming I use requests to pull the html from the website first?

marsh canyon
#

sure, that can work

errant creek
#

I'll give it a try. Thanks @marsh canyon

rotund token
#

Morning boy/girls.

#

does anyone have any courses for CSS?

opal fulcrum
#

can someone please explain to me what is a post request ? and why do we have to make sure it's a post request when making a form ?

marsh fog
#

@opal fulcrum , the POST requests hold the data to be sent to the server in the body of the request. From what I understand, and I could be wrong, the POST is better as the GET request with lots of data would be a massive URL. Check this out as it seemed to help me https://www.w3schools.com/tags/ref_httpmethods.asp

opal fulcrum
#

thanks man that was useful

topaz finch
#

I am using a flask app, and am trying to use the sqlite3 module in it. I got this error when revisiting a page:

cur = self.conn.cursor() sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 140453609432832 and this is thread id 140453567469312.

what exactly does this mean, and what actions would you recommend I take?

Please @ me when answering.

fickle fox
#

does anyone knows how to save image to database using flask??

valid sandal
#

hello

#

I'm using django and django-filters

#

And I had my filters working and then randomly stopped working, no changes made

#

but I think my filtered queryset

#

( .qs )

#

is not working in the template

#

if someone can help me plsssss

#

No errors displayed, the filter form generated correctly

#

but when I press the search button it doesn't bring me any objects to the template

#

and that stopped working from one time to another

#

also, I tried the {% for ... % } inside the form?????

spark rover
#

So django 3.1 added models.JSONField and I've migrated my project to use that from the old postgres specific one, is there a way to have migrations not fail on sqlite but also not break current deployments by squashing migrations

vestal hound
#

@opal fulcrum , the POST requests hold the data to be sent to the server in the body of the request. From what I understand, and I could be wrong, the POST is better as the GET request with lots of data would be a massive URL. Check this out as it seemed to help me https://www.w3schools.com/tags/ref_httpmethods.asp
@marsh fog yes but also

#

GET requests should be idempotent i.e. if you submit them multiple times it shouldn’t be a problem

#

which is usually not the case for POST requests

#

e.g. imagine you use a GET to place an order

#

if you send it multiple times, you get multiple orders

#

which is not right

#

so usually GET requests are used for read-only stuff

desert parrot
#

Is this where i ask about web scraping?

native tide
#

Maybe I can helpya if it's bs4

#

Is it ok to post my Django project to GitHub?

#

You know... With all the sensitive info in my settings.py

#

Like tokens and my email with password.

versed python
#

nope

#

search for django deployment

native tide
#

Usually I use environment variables to hide my sensitive info, but when I want to deploy it do a live server I have to replace the path to the environment variable with the actual value.

#

Which is redundant

versed python
#

wdym path to environment variables?

#

environment variables are available globally

native tide
#

O yes, I mean.. os.environ['var']

#

By path

versed python
#

that is indeed the correct way to manage secrets

#

what makes you think it is redundant?

native tide
#

Hi! I'm trying to use django and when I do: django-admin startproject mysite, I just get this error:

operable program or batch file.```

Someone help please!
quartz pewter
#

@native tide Check whether you have installed Django correctly or not. It is not installed yet.

valid sandal
#

are u working with a virtual enviroment

#

?

surreal whale
#

Could anyone help we with this bootstrap problem?

#

I have a navbar

#

but Idk how to make your current location highlight

#

it should be highlighting home

rain wren
#

Guys I have a problem in updating data in Django

#

I cant update and also delete a data

#

there is no error when I click the Update button and Delete Button

#

it's just redirect me to the Dashboard and nothing will change

#

in the database there is also no change

#

I have inputted also form tags

#

in my html

versed python
#

@rain wren you haven't done any database stuff in your view, why would it save anything?

rain wren
#

I have the database

#

my only problem now is that it cant update and also delete

#

and when I click the buttons, it has no error and only redirects to the dashboard

native tide
solar ridge
#

Has any had trouble getting Django Debug Toolbar to work? I have followed the instructions, although I get a javascript blocked error due to the MIME type.

#

<script type="module" src="/static/debug_toolbar/js/toolbar.js" async></script>

#

I can view the debug panel when in the inspector view. This confirms that the template is loading, and injecting into my webpage. But none of the buttons work due to this error

#

I'm getting a 200 status when django is serving the js file as well.

#

Adding the javascript import directly in my own template fixes the issue:

#

but this isn't a resolution to the original problem.

#

Any idea what may be going on here?

#

The bug must have appeared 4 months ago due to this commit where 'type="module"' was changed.

past cipher
#

I am creating a booking system. Seller signs up and they choose what days they want to work. i will then create a calendar and then only show the days the seller wants to work. So lets say I sign up, and I say I want to work Days: Monday, Wednesday, Sunday. I need to then add these days to the DB and then on the front-end only show them days in the calendar. How would you setup the DB table? I am thinking something like this:

class WorkerAvailability(db.Model):
  __tablename__ = 'worker_availability'
  id = db.Column(db.Integer, primary_key=True)
  monday = db.Column(db.Boolean, nullable=True)
  tuesday = db.Column(db.Boolean, nullable=True)
  wednesday = db.Column(db.Boolean, nullable=True)
  thursday = db.Column(db.Boolean, nullable=True)
  friday = db.Column(db.Boolean, nullable=True)
  saturday = db.Column(db.Boolean, nullable=True)
  sunday = db.Column(db.Boolean, nullable=True)

Seems a bit long though, any other way I am setup the table ?

lethal orbit
#

Which is redundant
@native tide There are different ways to go about it. I am using gitlab-runner and storing my secrets in my repo, so gitlab-ci gets them automatically when building my project. There's also Hashicorp vault, and you can use .env files with https://pypi.org/project/python-dotenv/

#

Just be sure to .gitignore your .env file, and use scp to copy it onto your server.

#

I am creating a booking system. Seller signs up and they choose what days they want to work. i will then create a calendar and then only show the days the seller wants to work. So lets say I sign up, and I say I want to work Days: Monday, Wednesday, Sunday. I need to then add these days to the DB and then on the front-end only show them days in the calendar. How would you setup the DB table? I am thinking something like this:
@past cipher That works. You can also store it as a single int using bitwise operations, which would keep your database smaller.... but it would make your code slightly more cryptic 😄

hidden gulch
#

Hello, are there efficient ways of hosting web services , something like lazily loading the service only when needed , like for now im hosting my php service with docker and nginx , so is there some way I can lazily load it only when a request comes in?

lethal orbit
#

Hello, are there efficient ways of hosting web services , something like lazily loading the service only when needed , like for now im hosting my php service with docker and nginx , so is there some way I can lazily load it only when a request comes in?
@hidden gulch you're thinking of https://en.wikipedia.org/wiki/Serverless_computing

hidden gulch
#

@lethal orbit seems that this utility is not provided by all cloud platforms, we're planning to deploy everything on hetzner server

#

is there some tool which can be used to achieve this?

#

like for my other services which dont require nginx , Im using something called ynetd , https://github.com/rwstauner/ynetd , for lazily loading up containers only when a request is made

#

so I was wondering if I could do the same with my web services too

lethal orbit
#

Yeah, if you are running on a VPS, you can use systemd socket-based-activation.

hidden gulch
#

yah Ive read on that

#

is it fast enough?

lethal orbit
#

Depends on how fast your services start.

#

I don't actually use it; my projects are usually small enough they can be always on...

hidden gulch
#

once an image has been built , I think docker cache can handle stuff right

lethal orbit
#

Sometimes, you can spend thousands of dollars on engineering to save a few hundred on deployment costs, and end up with a more complex system, so make sure you calculate the costs properly first lol

hidden gulch
#

I don't actually use it; my projects are usually small enough they can be always on...
@lethal orbit true , but since there are lot of services running parallely on my side, I prefer to free up ram whenever possible

#

Sometimes, you can spend thousands of dollars on engineering to save a few hundred on deployment costs, and end up with a more complex system, so make sure you calculate the costs properly first lol
@lethal orbit yes that is so true , thank u so much , Ill surely look up everything properly

cyan violet
#

is it possible to insert html into iframe from flask variables

twilit dagger
#

CSS - ```.parent-element{
margin-top: 80px;
display:flex;
justify-content: space-between;
}

.block{
display: flex;
flex-direction: column;
margin-left: 30px;
padding-top: 10px;
}```

tepid stirrup
#

Is there any way I can use javascript to change a timezone in django?

I use this in base.html
`{% load tz %}
{% timezone "GB" %}

{% block content %}
{% endblock %}

{% endtimezone %}`

But I found that this javascript code Intl.DateTimeFormat().resolvedOptions().timeZone
Gave the timezone.

Is there a way to get the results of that code and change the timezone?

past cipher
#

@twilit dagger maybe width 33% ?

#

or flex-basis actually since you're using flex

native tide
#

I've a package installed using poetry, but if I try to execute it I got 'ModuleNotFoundError: No module named 'packagename'" is possible to include self or how can I fix it?

nimble epoch
#

Hey there wanted to ask a question its about a game not programming its name is Ag Drive is it still available on app store or any country or region to download it from app store?

low blade
#

how do you guys feel about sanic for building a frontend? i was comparing it to django, and it seems better because it has async functionality built-in from the get-go

swift crystal
south linden
#

run .text on all the found elements

#

@swift crystal

#

it'll return the inner text

swift crystal
#

let me try

#

resultset has no attribute text

#

i am using findall...

#

hmm

#

should i iterate through them?

south linden
#

yea

swift crystal
#

what even is it idk how to make it into a list or iterate it

#

is it a list or a string idk

#

more details:

low blade
#

why do you keep screenshotting an impossible to read image at this point instead of just copying the text itself?

#

copying the text would probably make it easier for people to read, and therefore help you

swift crystal
#

ok

#

so originally I needed to extract the text from some html code i scraped

#

I got how to do that but I cant do it to a resultset

#

I need to iterate over it to do it to each one

#

but i have no idea how.

#

ok

night wharf
#

Hey i have a question about Django + Bootstrap can anyone help?

distant trout
#

flask-restful vs fastAPI, someone know which one is better overall?

low blade
#

this is a summary @terse viper provided in #career-advice

my quick summary of benefits are:

  • it's an API framework, so specialized for API work. Flask is a bit more general-purpose. An obvious example of where specialized for API is good is the error messages re json by default
  • unified query, path, and body inputs as arguments. Flask uses the request singleton for stuff, and it's inconsistent. Having arguments is neater (functions more pure)
  • built-in run-time schema validation and static checking with pydantic. Flask has no such thing. This also uses python type hinting
  • built-in automatic documentation generation. you will literally get a /doc page with swagger UI generated for you automatically if you define your input/output models with pydantic
  • async support
  • websockets
  • graphql
slender bloom
#

Hey, Im trying to run my Flask app in apache2 using wsgi and Im facing some issues, someone help?

marble carbon
#

Post your problem

honest dock
#

Can anyone explain why my static and media files are not working on deployment server?

#urls.py
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

#settings.py
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    os.path.join(BASE_DIR, "media"),
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')
twilit dagger
#

Include a path for staticfiles @honest dock

honest dock
#

@twilit dagger can you tell me how?

twilit dagger
#
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'staticfiles'),
]```
#

@honest dock

honest dock
#

@twilit dagger how does that make sense

twilit dagger
#

Try adding it into your staticfiles_dirs

#

os.path.join(BASE_DIR, 'staticfiles'),

old reef
#

@twilit dagger can u pls help me correct this script.

#

if (command == 'kick'){
const userKick = message.mentions.users.first();

if (userKick) {
    var member = message.guild.member(userKick);

    if (member) {
        member.kick('you have been kicked for brekaing the rules.').then(() =>{
            message.reply(kicked zuser ${userKick.tag}!);
        })



    } else {
        message.reply('that user is not in the server.')
    }
} else {
    message.reply('you need to state a user to kick')
}

}

if (command === 'ban') }
const userBan = message.mentions.users.first();

if (userBan) {
    var member = message.guild.member(userBan);

    if(member){
        member.ban({
            reason: 'you broke the rules.'
        }).then(() => {
            message.reply(${userBan.tag} was banned from the server.
        })
    } else {
        message.reply('that user is not in the server.'
    }} else }
        message.reply('you need to state a user to ban.')
#

it sais theres 9 erros

#

but i fixed it all

#

and it still doesnt work, im not sure if its the start

#

o

#

k

marsh canyon
#

huh

#

its javascript

#

Also first line there are three ===
@twilit dagger u always have 3 equals in javascript to ensure type checks

twilit dagger
#

Yeah I didn't even realize

#

I was wondering why this was looking so strange

marsh canyon
#

@old reef this question is related to discordjs i believe, this might not be the right server for that

#

you can ask in a javascript server

twilit dagger
#

I can't believe I didn't see all the {}

marsh canyon
old reef
#

@marsh canyon ty ur the BEST

teal glacier
#

hey everyone, need some help with something. i had this flask program that was running fine before, but now it keeps giving me a flask.cli.noappexception

devout coral
#

Anyone know what the best practice for having something done on a schedule or a regular basis in Django is? For example I want to go through all my records in a model and if they are certain days old I want to delete them.

cerulean vapor
#

@devout coral that kind of thing is best done with a script that you run by way of the operating system's task scheduler.

devout coral
#

Well my initial thought was to run a cron job to directly interface with my SQL database but then I thought implementing it into the Django site might be best.

cerulean vapor
#

you can run a cron job to launch a script that uses Django's ORM

#

that's the way I'd do it myself

teal glacier
#

theres a library called schedule that is very easy to use. im not sure its a 'best practice' though

cerulean vapor
#

for something that only happens once a day or something like that, use cron.

devout coral
#

Yeah, which is what I thought of doing but lets say I deploy this at a different location and now i'd have to set that up and add seperate documentation for it. I thought adding it to the app would be best. Guess not.

cerulean vapor
#

cross that bridge when you come to it :D

#

use what works now to get it working now.

devout coral
#

Haha ok.

cerulean vapor
#

just make a note that it has to be ported.

devout coral
#

Yep, I can add that to the doc no big deal. Just thought it might piss some people off that there is also this separate thing that needs to be used.

cerulean vapor
#

As long as it's documented, it should be fine

devout coral
#

Then from cron I should be able to use the Django ORM if anyone is using different SQLs?

cerulean vapor
#

ideally. I believe Django ORM is pretty abstract

devout coral
#

Ok, I also saw some people mentioning celery but I have never used it. Any thoughts on that?

cerulean vapor
#

I haven't used it myself

brave gyro
#

I dont know if this is the write chat sorry but I want to make an app using react native that basically allows me to take a picture of something at store it in a map like google maps would i have to use the google cloud api?

devout coral
#

So you normally just set up a management command and then run it through cron?

cerulean vapor
#

@devout coral or a script that imports the needed components to be Django-aware

#

@brave gyro you'd have to use Google's APIs to interact with anything Google.

devout coral
#

Ok, I think I am going to go for a management command so I do not have too many outside dependancies

#

and this way if something happens I could also easily run it manually

cerulean vapor
#

that makes sense

devout coral
#

Cool, I appreciate your help.

cerulean vapor
#

YW!

visual lake
#

Is there someone from Sweden here?

proven orchid
dapper tusk
#

you have no path at /

proven orchid
#

how to configure this for windows then?

faint ivy
#

im trying to do author/ books example from django. in my books class im adding author with foreignkey relation

#

i dont want to add books in author class too

lethal orbit
#

Is there someone from Sweden here?
Yes

faint ivy
#

is there anyway to do without adding books via hand

#

i checked docs, manytomany relation maybe can help me

lethal orbit
#

may ik wot has gone wrong here?
@proven orchid you need to register a view at / in urls.py

faint ivy
#

but example for manytomany relation is not good

native tide
#

can anyone help me make my socket io site less laggy

proven orchid
#

@proven orchid you need to register a view at / in urls.py
thanks

last patio
#

I keep getting django.core.exceptions.ImproperlyConfigured: The included URLconf 'project.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

#
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', include('QuickQuiz.urls')),
]```
#

my main urls file

#
from django.urls import path
from . import views

urlpatterns = [
    path('', views.Register.as_view(), name='register'),
]```
#

is the QuickQuiz urls

#

how do i fix it?

#

??

native tide
#

Can you deploy a Django project on Netlify?

last patio
#

I keep getting django.core.exceptions.ImproperlyConfigured: The included URLconf 'project.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
@last patio pls help

native tide
#

okay...

last patio
#

anyone?

native tide
#
from django.urls import path
from . import views

urlpatterns = [
    path('', views.Register.as_view(), name='register'),
]```

@last patio Is this in the QuickQuiz app?

last patio
#

yes it is

#

I've changed it sine but its the same error. ```py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('register/', include('QuickQuiz.urls')),
]

#
from django.urls import path

from . import views

urlpatterns = [
    path('', views.register, name='register'),
]``` this is the one it includes
#

When i google it literally all the answers are "check how you spell urlpatterns"

native tide
#

I've never seen this error before, but try to check this part now the issue is probably caused by a circular import.

last patio
#

Im not quite sure what would cause that

native tide
#

Is the register view a function based or a class based view?

last patio
#
from django.shortcuts import render
from .forms import *
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm

def register(request):
    if request.method == 'POST':
        context = {}
        registration_form = RegisterForm(request.POST)
        context['form'] = registration_form
        if registration_form.is_valid():
            registration_form.save()
    else:
        context = {}
        registration_form = RegisterForm()
        context['form'] = registration_form

    return render(request, 'QuickQuiz/register.html', context)```
#

@native tide

devout coral
#

@cerulean vapor I have implemented the command and it worked great but I had a question. Do you know of a package similar to bootstrap_daterangepicker which will allow me to have users select multiple days. In that specific package I can have them choose a range but I would also like for users to select separate days. Any ideas?

native tide
#

how did you make the text green in discord tho

#

did it do that because its code block?

#

@last patio

last patio
#

put py right behind the `

#

@native tide

native tide
#

oh thats cool

#
print ("I see now")
#

ah

#

ik thats not proper print format btw lmao

#

actually ill just change it

willow iron
#

hey, can anyone here help just a bit w django?

#
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(null=True, blank=True,
                              default='default.jpg', upload_to='profile_pics/',
                              validators=[validate_image_file_extension])
    about = models.CharField(null=True, blank=True, max_length=200)
    githubusername = models.CharField(null=True, blank=True, max_length=80)
    domes = models.IntegerField(default=0)
    followers = models.ManyToManyField(
        User, default=None, blank=True, related_name="profile_followers")
    slug = models.SlugField(null=True, unique=True, max_length=256)

    def __str__(self):
        return f'{self.user.username} Profile'

    def get_absolute_url(self):
        return reverse_lazy('users:profilepage', kwargs={'slug': self.slug})

    def followers_as_flat_user_id_list(self):
        return self.followers.values_list('id', flat=True)

    def save(self, *args, **kwargs):
        username = self.user.username
        self.slug = slugify(username)
        super().save(*args, **kwargs)

#

This is my model

#

Was wondering how do I list all the followers of a profile in an APIView?

#
class FollowerModelSerializer(ModelSerializer):
    user = CharField(source='slug')

    class Meta:
        model = Profile
        fields = ['user', 'followers']

This is the serializer.

class FollowerModelViewSet(ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = FollowerModelSerializer
    allowed_methods = ('GET', 'HEAD', 'OPTIONS')

    def list(self, request, *args, **kwargs):
        self.queryset = self.queryset.filter(id=request.user.id)
        return super(FollowerModelViewSet, self).list(request, *args, **kwargs)

And this is the API

#

All it returns to me is the id of followers in the API View instead of all the followers.

#
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "user": "pop",
        "followers": [
            1,
            4
        ]
    }
]```
This is the response I get.
#

Basically, I want to get the username in there instead of the user id.

nimble epoch
#

Hi wanted to ask a question its about a game not programming its name is Ag Drive is it still available on app store or any country or region to download it from app store?

#

Missed it bad just wanted to know if you can help

versed python
#

@willow iron look into nested serializers

willow iron
#

nvm lol

#

it was an easy problem, was just missing a concept. solved it a while later. thanks a lot either way!

#

just had to use slugrelatedfield

weak chasm
#

anyone here able to help me with django-allauth?

willow iron
#

sure

#

what's the issue?

#

I personally prefer django social auth but allauth works too ig :))

weak chasm
#

@willow iron omg thank you.

#

okay

#

i guess ill just ask you on the other thread

willow iron
#

sure

sage thistle
#

can someone help me with Flask ?

vestal hound
#

can someone help me with Flask ?
@sage thistle don't ask to ask, just ask.

sage thistle
#

👀 ^ [**flask **] i am trying to do a site where users can type in some stuff ,which they want us to deliver like , example : if u want grocery u need sugar 5kg , salt 1kg .... u just type it in and the things which they type will be saved in db and sent to the delivery guys ,,,

problem : when they type the item which they want and click on the add more button i want that previously written item to be displayed bellow the Sugar ^ in the pic if they click add more again the same should happen

how can i do it?

analog reef
#

can anyone help me a little bit
im making a webpage
i want it to be like when a person fills a form, the data is sent and shown in my terminal
i don't flask so i asked

vestal hound
#

👀 ^ [**flask **] i am trying to do a site where users can type in some stuff ,which they want us to deliver like , example : if u want grocery u need sugar 5kg , salt 1kg .... u just type it in and the things which they type will be saved in db and sent to the delivery guys ,,,

problem : when they type the item which they want and click on the add more button i want that previously written item to be displayed bellow the Sugar ^ in the pic if they click add more again the same should happen

how can i do it?
@sage thistle JS would be useful here

sage thistle
#

oooh! okay ? i havent tried it yet but can u tell me a bit more about it? @vestal hound

vestal hound
#

JavaScript

#

you basically want a dynamic webpage

#

you could do this with Flask but it’d be inefficient and complex IMO

mortal geyser
#

You will basically have an empty array and a js function that each time you call it, it will push that required ingredient to the array

#

so when u use "add more" button you will call that js function instead of performing a server call

sage thistle
#

ooooh! okayy ig i have a idea , i will try it out ty

opal basalt
#

is there any good tutorials on this subject?

versed python
#

What subject?

marble carbon
#

maths

opal basalt
#

Web development with python

#

I'm very new to it, where would be a good place to start. I know js, HTML, css, php already.

marble carbon
#

Try cs50 web

opal basalt
#

Thanks !

proven orchid
#

any help for react here?

marble carbon
#

or this

proven orchid
#

no i mean with my error

#

lmao

marble carbon
#

lol

#

idk react

proven orchid
#

F

marble carbon
#

post ur error tho

#

someone else might look at it and help u out

proven orchid
#

nvm got it

#

lmao

versed python
marble carbon
#

jekyll theme

#

made by the same guy

#

lol

proven orchid
#

lmao

versed python
#

jekyll theme
@marble carbon where can I get it?

marble carbon
#

oh nvm

#

idk

versed python
native tide
#
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User'
#

how to fix this.... I am getting this after i made a custom user model using AbstractUser class

#

any suggestion

versed python
#

@native tide AUTH_USER_MODEL='youapp.CustomUser' in settings.py

native tide
#

I did this already....my custom user model is working fine but when i register a new user ...it raise this exception

versed python
#

the django docs say that swapping out the default model mid way through a project introduces a lot of problems

#

maybe delete your db and try again?

native tide
#

It was starting....i deleted the database three times making every thing again 😂

#

I'll have to dig deeper in docs i guess

versed python
#

i tried doing it midway once, it didn't work

#

good luck though

hollow root
#

Hey guys Im using django , I have a Model that i added a custom function to, when i get a queryset i need to sum all of monthly_totals

class CustomerTransaction(models.Model):
    customer_transaction_id = models.CharField(unique=True, max_length=255, blank=True, null=True)
    customer_agreement_id = models.ForeignKey('CustomerAgreement', on_delete=models.CASCADE, null=True, blank=True)
    meter_id = models.ForeignKey('Meter', on_delete=models.CASCADE, null=True, blank=True)
    amount_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, 
    transaction_date = models.DateTimeField(blank=True, null=True)
    amount_including_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True)
    meter_number = models.CharField(max_length=255, blank=True, null=True)

    def monthly_total_kw(self):
        today = datetime.date.today()
        total = 0
        if self.transaction_date.month == today.month and self.transaction_date.year == today.year:
            items = self.customertransactionitem_set.filter(units__isnull=False)
            for item in items:
                total = total + Decimal(item.units)
        return total

i would like to be something like this,but it wouldn't work because its not a column in the table but rather a function...is there another way i could do this without having to loop through each item and add them together?

    transactions = CustomerTransactions.objects.all()
    total_kwh = transactions.aggregate(total_kwh=Sum('monthly_total_kw'))
vestal estuary
#

does anyone have experience serving a django page as an actual url instead of localhost?

#

I tried using hosts file to redirect an example url to localhost with the port, but it doesn't direct from that url to the stuff I am serving on the localhost

flint breach
#

Hey guys Im using django , I have a Model that i added a custom function to, when i get a queryset i need to sum all of monthly_totals

class CustomerTransaction(models.Model):
    customer_transaction_id = models.CharField(unique=True, max_length=255, blank=True, null=True)
    customer_agreement_id = models.ForeignKey('CustomerAgreement', on_delete=models.CASCADE, null=True, blank=True)
    meter_id = models.ForeignKey('Meter', on_delete=models.CASCADE, null=True, blank=True)
    amount_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, 
    transaction_date = models.DateTimeField(blank=True, null=True)
    amount_including_tax = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True)
    meter_number = models.CharField(max_length=255, blank=True, null=True)

    def monthly_total_kw(self):
        today = datetime.date.today()
        total = 0
        if self.transaction_date.month == today.month and self.transaction_date.year == today.year:
            items = self.customertransactionitem_set.filter(units__isnull=False)
            for item in items:
                total = total + Decimal(item.units)
        return total

i would like to be something like this,but it wouldn't work because its not a column in the table but rather a function...is there another way i could do this without having to loop through each item and add them together?

    transactions = CustomerTransactions.objects.all()
    total_kwh = transactions.aggregate(total_kwh=Sum('monthly_total_kw'))

@hollow root if it's a function, you most likely can't directly query it, as it is pure python

#

an option is adding computed fields and store in the db, and then you can directly query it

#

does anyone have experience serving a django page as an actual url instead of localhost?
@vestal estuary as a url, just means hosting it somewhere else, pointing your dns at it, and wiola (of course, not the whole story)

#

ngrok is a nice alternative

#

or geting an aws ec2 instance for example and just hosting it there

#

look up computer networking basics and you'll begin to understand the process

#

but what you're basically looking for is, "deploying the app"

#

google deploying a django app, and im sure you'll find some great sources on how to do it

#

@hollow root actually now that i think of it, you don't really have complex logic in that function, look into query expressions more specifically, F queries - a django thing

#

and rewrite it as a pure query

twilit dagger
#

Has anyone here worked with Crispy Forms?

flint breach
#

you'll have more luck actually asking your question

hollow root
#

@flint breach thanks ill have a look at f queries

twilit dagger
#

I have this Crispy Form in Django, I want there to be some space between the fields and for the last 2 fields to take up the entire row

#

In the template I just have ```
<fieldset>
<legend><h1>Get a Quote From Us:</h1></legend>
{% crispy form %}
</fieldset>

#

Forms.py - ```
class ContactForm(forms.Form):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
phone_number = forms.CharField()
company_name = forms.CharField()
additional_comments = forms.CharField()

helper = FormHelper()
helper.layout = Layout(
    Row('first_name', 'last_name'),
    Row('contact_email', 'phone_number'),
    Row('company_name'),
    Row('additional_comments'),
    )
helper.form_tag = False
honest dock
#
field = forms.CharField(
        widget = forms.Textarea(attrs={
            'padding-right': '10px'
        })
    )

I think you can do something like this @twilit dagger

#

else, you need to split the form and use columns and rows (that is if you use a css framework)

native tide
#

I hosted my Django project on PythonAnywhere. Now i want to update some stuff in my css file but the changes do not show up.

#

Before I put it on the server I did add a STATIC_ROOT and ran collectstatic

#

But should I run collectstatic again when I make changes to the static files?

lean rapids
#

Notsure if this is the right place for my questions, if not, im sorry.
but anyone here with experience with flask?

Trying to make a "bank"-app as a project, and I was thinking that every user that makes an account would get a "randomized encrypted URL", so that i can prevent people from just typing in other users in the URL and getting there bank account up.

Im new btw. So little experience 😦

native tide
#

you should probably look into flask_login @lean rapids

#

because a url can be brute forced, but flask_login uses sessions to allow you to restrict acess to urls based on the users status

lean rapids
#

@native tide willdo, thanks! 😄

native tide
#

np xd

sly cargo
#

Anyone here have experience with flask-socketio and/or vue-socket.io

#

Having some issues with the two combined, not sure if its related to either of them or to Traefik

#

Flask is logging the requests so they are reaching the server which is inclining me to believe it is an issue with flask and vue, not traefik

waxen badger
#

Hello everyone! I am trying to learn how to host a little chat on the web as an exercise, but I don't know where to start.
I would like to create everything, from the server hosting the chat to the actual code 🙂 Does anybody know where I should start?

sly cargo
#

Hilariously enough there are tons of screencasts of implementing a chat app using flask-socketio

#

Following along to them is a good start

#

Deployment stuff is another ballgame with tons of options

gaunt quiver
#

Im not sure if web development is the right spot, But im trying to go through the django tutorial and I cant even create the project, Ive been trying for over and hour and am totally lost

#

I have django and pip and python installed but it wont let me create the project

quick cargo
#

do python -m django-admin instead

#

just means its not in path @gaunt quiver

gaunt quiver
#

@quick cargo Thanks for the help, It dosent error but now just does nothing

#

no file or folder is created either

quick cargo
#

try "dango-admin"

gaunt quiver
quick cargo
#

you sure its not installed on a virtual enviroment or the sort

gaunt quiver
#

I dont know what that is

quick cargo
#

if you do py -m pip install Django

#

does it say already satisfied

gaunt quiver
#

Yes

quick cargo
#

okay

#

if you do python -m django does it come up with anything?

gaunt quiver
#

When i do with py instead of python yes

quick cargo
#

okay so somehow you have two diffrent aliases for that but alright

#

you should be able todo:

#

py -m django startproject name_here instead of django admin

gaunt quiver
#

yea when i do anything with python instead of py it just does nothing

#

OMG I LOVE YOU

twilit dagger
#

How do you host a Django project on something like Wordpress?

quick cargo
#

you dont

#

🙃

twilit dagger
#

Can you integrate it?

gaunt quiver
#

thank you @quick cargo

quick cargo
#

@gaunt quiver np

#

@twilit dagger wordpress is PHP

gaunt quiver
#

I feel like something is wrong with my computer, It now isnt working for the very next thing.

It created the folder with everything in it but

py manage.py runserver
Does nothing

#

im in the project directory so that isnt it

#

i tried with Python instead of py just for kicks and same thing, nothing

twilit dagger
#

dont do py

quick cargo
#

what no

#

thats just wrong lol

twilit dagger
#

no why would you need to do 'py'?

quick cargo
#

because thats how you run python files...

gaunt quiver
#

also

quick cargo
#

whats you current working directory and file layout

twilit dagger
#

It goes "RootFolder/Project/manage.py runserver" that's all

gaunt quiver
quick cargo
#

although i doubt it

#

try py "./manage.py"

marble carbon
#

manage.py is in the directory
@twilit dagger doesn't work like this on windows, only linux man

gaunt quiver
#

same thing nothing

quick cargo
#

you have possibly the most unlucky python setup ive seen

#

🤔

marble carbon
#

uninstall python

quick cargo
#

yeah pretty much

marble carbon
#

reinstall it

quick cargo
#

uninstall it all and reinstall it entirely

gaunt quiver
#

I did that this morning because I thought something went wrong, do it again?

quick cargo
#

uninstall it all

#

get a new distribution

#

preferably 64 bit not 32 this time though

#

i cant really do much other than say say, My Python doesnt have sqlite installed so by default i cant run manage.py lol

gaunt quiver
twilit dagger
#

Maybe you should get like VSCode

gaunt quiver
#

I have that

twilit dagger
#

then you can use the terminal in that rather than cmd

gaunt quiver
#

Alrighty everything is working perfect and as expected after reinstalling and running in the visual studio code terminal

#

Thank you two

marble carbon
surreal whale
#

I need help

#

Lots of help

simple sentinel
#

Posting your specific question will let people help you faster

surreal whale
#

I'm trying to fix up a models for different text sections

#

for example

#

this is hard coded

#

but I want those text field soft coded

#

here is my code

#
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse


# Create your models here.
class ProfileImageBox(models.Model):
    profile_image = models.ImageField()
    name = models.CharField(max_length=50)
    sub_description = models.TextField(max_length=150)

    def __str__(self):
        return 'Profile Image'


class InfoBox(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=4000)

    def __str__(self):
        return self.title


class DescriptionInfoBox(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=2000)

    def __str__(self):
        return self.title
#

But how do I link this to the database?

#

so it should work

#

but

#

it doesn't

#

I can't see it in the django admin page

#

Could anyone help with this problem?

simple sentinel
#

when you said you applied migrations, you mean you ran the make migrations and then the migrate command?

surreal whale
#

ye