#web-development

2 messages Β· Page 115 of 1

twilit needle
#

pycharm issue

native tide
#

I'll come back later

twilit needle
#

okay

#

its what field

#

a char field?

#

the token for the user

native tide
#

yup

#

just go into a DB browser and see exactly what fields it has

twilit needle
#

I finished authentication

#

oof

#

now what should I do

#

Which (on sign up / login) you should be sending a token to your frontend which then saves it as a cookie.
@native tide how can I do this?

#
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def login(request):
    username = request.data.get("username")
    password = request.data.get("password")
    if username is None or password is None:
        return Response({'error': 'Please provide both username and password'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(username=username, password=password)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)
    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)```
I found this example
#

i think its right

#

how do I save the token now as a cookie

#

I know how to get the token now

native tide
#

Yea so u return JSON as a response then use js-cookie to save it as a cookie

twilit needle
#

is it a module

native tide
#

then in every api request include it as a config in the axios request

twilit needle
#

js-cookie

native tide
#

just search it up

haughty turtle
#
Not Found: /create
[19/Nov/2020 09:31:31] "POST /create HTTP/1.1" 404 1767```I am using fetch to send a post request and it said that the page is not found 

my main urls ```py
urlpatterns = [
    path('', include('product.urls')),
    path('create/', include('product.urls')),
    path('capture/', include('product.urls')),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)``` and this is my product urls ```py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('create/', views.create, name='create'),
    path('capture/', views.capture, name='capture'),
]
native tide
#

did you make a request to /create/ or /create

haughty turtle
#

The second one

#

@native tide

native tide
#

well your path is to create/

#

so you need to make the request to <your_domain>/create/ with the trailing /

haughty turtle
#

Thanks @native tide

native tide
#

Also I think Django props up an error which explains this when it happens iirc. May be in the logs

haughty turtle
#
def create(request):
    if request.method =="POST":
        print(request)
        # Get json from request, gets loop through items and get cuantity, calculate total cost per item, and total cost of all items
#         json_items = {}
#         create_order = OrdersCreateRequest(request)
#         response = client.execute(create_order)
#         data = response.result.__dict__['_dict']
        return JsonResponse(request)
#     else:
#         return JsonResponse({'details': "invalide request"})```
#

I am trying to print out request in cosole, in order to troubleshoot. its not doing so

#

@native tide

native tide
#

yhuI don't think you can print stuff like that into the console with Django

haughty turtle
#

So how would I log this, save it to a text file?

haughty turtle
#

Hmm print does print out to console

#

But whats its returning confuses me, <WSGIRequest: POST '/create/'>

#

its supposed to print a JSON but just returns this

#

I am using logger to mimic development setting, but print works also,

def create(request):
    if request.method =="POST":
        logger = logging.getLogger(__name__)
        logger.warning(request.method)```
#

when I print out request.method is returns POST as it should but its not showing me the body

#
            return fetch('/create/', {
                method: 'post',
                headers: {"X-CSRFToken": csrftoken},
                body: JSON.stringify(cartJson)```
#

this is what I am sending in

#

NVM

#
def create(request):
    if request.method =="POST":
        logger = logging.getLogger(__name__)
        logger.warning(request.body)```
#

this got me to print out the body

native tide
#

Do you have a seperate frontend?

haughty turtle
#

but its so weird, when printing request itself it doesnt show the body, it only shows <WSGIRequest: POST '/create/'>

#

yeah I got it to work, just weird that when printing request itself it doesnt show any signs of it containing a body, but magically when I do request.body it grabs it.

plucky tapir
#

@native tide I want to take in input from the user, and then they enter 5 into the integer field and I want it to become -5 in the database. What would be the best way to do this? Would I definite it with a certain field in models? I’m using generic class based views

torpid pecan
#

I made a DNS record to direct my domain to my website but it does not work. Do I need to make any changes to my nginx, gunicorn, or django files for this to work?

lofty matrix
#

@torpid pecan If you ping the domain, does it work?

torpid pecan
#

It takes me to a default nginx page when it should the default django page

lofty matrix
#

Ok, so that should mean that your DNS record worked

#

Can you show your nginx config? I think that is the issue

torpid pecan
#

The red is just the server address

lofty matrix
#

Is server_name your domain?

#

It should be

#

And did you enable your config? Look in /etc/nginx/sites-enabled/ . What files are there?

torpid pecan
#

I think I changed it and forgot to reenable it

lofty matrix
#

If only the file default is then, then try sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/ then reload nginx

#

also reload nginx if you try changing any values

torpid pecan
#

Yeah, I forgot to run that command πŸ€¦β€β™‚οΈ . Thanks.

lofty matrix
#

np, that worked?

torpid pecan
#

Yeah that worked. Thanks

crystal cairn
#

hi please wanna ask abt mysql.connector , what does cursor.execute return on success ??

lofty matrix
#

Great. One thing to keep in mind if you have other issues is that the user that nginx is running as will need to be able to access that socket file. There might be some issues with that as it is in your home directory

#

Try saving the return value to a variable then

print(the_return_value_variable)
print(type(the_return_value_variable))
crystal cairn
#

that's what I thought it like I can compare the statement to true ?

#

but I guess its not a boolean to return true

#

what I wanna do exactly is like

if thestatement executed succesfully :
  smtng
else : 
  smntng
native monolith
#

Hey, got simple problem with css not being aplied to head

head{
    text-align: center;
    text-transform: capitalize;
    color: rgb(190,0,0);
}
    <head>
        {% block style %}
            <link rel="stylesheet" href="{{ url_for('static', filename='styles/style.css') }}">
            <link rel="stylesheet" href="{{ url_for('static', filename='styles/google-icons.css') }}">
        {% endblock %}
        <title>ZoomIt - {% block title %} Gif maker{% endblock %}</title>
        <meta charset="UTF-8">
        {% block header %}{% endblock %}
        {% block head %}{% endblock %}

    </head>

{% block header %} Hello, this is home page.{% endblock %}

lofty matrix
#

header is not head

native monolith
#

it was head, then I started to experiment to find solution

#

I wonder if raw text is ok, or it has to used with any tag

#

{% block header %} Hello, this is home page.{% endblock %}

#

Andrew πŸ˜„

#

save me

native monolith
#

nvm got it

#

but why is renderin comments?

<html lang="en">

<!--    <link rel="stylesheet" href="static/style.css">-->
    <div class="navbar" id="TopNavBar">
      <a href="/home" class="active">Home</a>
      <a href="{{ url_for('save')}}">New Zoom</a>
<!--      <a href="{{ url_for('results')}}">Results</a>-->

i disabled Results but it throws stil error

native tide
#

@plucky tapir in your view, get the integer from the field, multiply it by -1, save that to the db

fading plaza
#

I am building a webapp using node. js express. js and mongodb . There are users in app and I want to add a chat service option between users , how I can achive it? (edited

quick cargo
#

websockets

plucky tapir
#

@native tide fields = ['tname', 'recipient', 'amount'*(-1), 'date']
Something like that?
From:


class TranCreateView(LoginRequiredMixin, CreateView):
    model = transactions
    success_url = '/users/tactionslist'
    fields = ['tname', 'recipient', 'amount', 'date']

    def form_valid(self, form):
        form.instance.user_id = self.request.user
        return super().form_valid(form)

native tide
#

I'm not familiar with class based views, but if the form is valid, just get the user input, make it negative, assign it to a variable and then pass that into the DB

frozen python
#

When you run Django Admin. In the terminal, how do you have a β€œquestion” come up to name the project? I have a β€œTASK” setup to run that creates/sets up the project and super user, BUT, I want to have the option as I run a code, to name the project and any apps

plucky tapir
#

Having issues because its not considered an integer ATM. Does anyone here have experience with CBV?

opal vale
#

What exactly are uvicorn workers?
If I run app with
app.counter
on 2 workers, will I have 2 different counters or just one?

hybrid bobcat
#

how do I decide over IaaS, BaaS, and PaaS services when it comes to hosting web applications?

#

what do I need to consider?

#

I'm using a Django based app btw if that counts as a factor

native monolith
#

how to use svg box? it won't render :/

#

in flaks

limber laurel
#

I am having trouble understanding the benefits and a typical use case of serializers in django, maybe someone could link me a helpful resource?

native monolith
#

you do this for api I think

native monolith
#

how do I integrate that thing to flask? 😐

native tide
#

@limber laurel serializers validate the data incoming to your backend. useful for saving to a model

native monolith
#

svg viewbox is not working too good

jade lark
#

You almost have it working. What specifically are you having for an issue?

#

Create a new view like you have done. If the request method is a get then render the same template as the creation but populate the fields.

#

Then check for an post event.

#

So for example on update_note() you can pass the id in the URL for the note to load and allow them to edit.

swift heron
#

how would I go about sending a list of dictionaries to the fronted of a django application? would I have to use transform it all as json and send it?

native tide
#

@swift heron DRF serializers

jade lark
#

f = ContactForm(initial={'subject': 'Hi there!'})

#

Change the ContactForm to your own values.

#

I wish I had more time to explain how to do it right now but sadly I don't.

trim star
#

What is the proper way to do logging in Django?

jade lark
#

Depends on the use case.

trim star
#

Just a simple web application to log error from exceptions

#

non-fatal errors @jade lark

jade lark
#

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/filepath/site_logs.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers': ['file'],
'propagate': True,
'level': 'DEBUG',
},
'MYAPP': {
'handlers': ['file'],
'level': 'DEBUG',
},
}
}

#

make sure you only run this when debug is turned off. That or you can do a custom solution.

trim star
#

So what would the name of the logger be when i use logging.getLogger() in the case above? @jade lark

jade lark
#

That logs everything into a file.

#

MYAPP can be replaced with the name of your app.

trim star
#

Ok thanks

native tide
#

what do you guys think of the current animations / colors

trim star
#

@native tide nice

#

@native tide what are you using for screen capture

native tide
#

web plugin

mortal cloak
twilit needle
#

@native tide I dont get you because you told me that
I needed to store the user's token inside the database along with the user model

#

instead I can just access the user by doing request.user right

#

or what should I be doing to access the authenticated user?

#

every user has an id, so what If I just return the id along with the token and then I can reference the user with the id?

#

OH WAIT NO

#

NOW I GOT IT

#
from rest_framework.authtoken.models import Token

try:
    Token.objects.get(key="token").user
except Token.DoesNotExist:
    pass```
So the token objects are stored in the database by default with user information.
All I have to do is something like this
#

but where will I store the token after login/register @native tide ? pls help me

fickle cobalt
#

hello

lavish ruin
#

im makin a thing the BaseHTTPRequestHandler and im trying to see how i can get the current html content i know self.wfile.write adds text but i dont know how to get it

vestal hound
twilit needle
#

okay

#

now I am stuck with axios post request pls help me

#
async handleSubmit(event) {
        await axios.post(api_url+'register/', this.state.values.items())
            .then(response =>{
                const token = response.data.token;
                localStorage.setItem('token', token);
                //setJwt(token);
                // bring up app container
            })
            .catch(error =>{
                console.log(error)
                this.setState({
                errors: error.response,
                values: error.data.input_data
                })
                // set the given field values return by api along with errors

            });
    }
#

this post request always gives an error code of 404

#

@vestal hound could u pls help

#

axios is bugged, I guess

#

Any solutions? I tried what they told me there but still it doesnt work

#

and if not any solutions somebody please recommend an alternative

twilit needle
#

ping me when help pls thanks

onyx flume
#

Hey guys

#

I'm looking to make a button to clone one record in admin page in django

#

For example when I open first object I can see save button and etc
I want to add another button to make a new object and clone all values from the last one

#

How can I do this?

tardy heron
#

what would be a good websockets tutorial. For the protocol itself and python

gaunt marlin
#
tardy heron
#

thanks

native tide
#

@twilit needle Store the token as a cookie then send it as a header in your axios request

#

Django will know the user from request.user from the token value in your Authorization header

green snow
#

whats the easiest way to extend django user model

native tide
#

or AbstractUser if you still want the user fields

green snow
#

like i want user model for resgisteration

#

only new field i wish to add is teacher/student a boolean value

#

so what should i be using?

gaunt marlin
#

@green snow this is how you would extend the user model in models.py:

from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
     #your extra custom fields

for authentication you have to tell Django to use your custom user models for it in your settings.py:

AUTH_USER_MODEL = 'myapp.models.CustomUser'
green snow
#

oh ill try this

native tide
#

read the docs on abstractUser and you'll understand what to use

green snow
#
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    isteacher = models.BooleanField```
#

so i have pasted this to models.py of that app

gaunt marlin
#

did you created the migration and migrated it?

green snow
#

no

gaunt marlin
#

you should do that first

green snow
#

ok and where does this go

gaunt marlin
#

what "this"?

green snow
#

AUTH_USER_MODEL = 'myapp.models.CustomUser'

gaunt marlin
green snow
#

ok

gaunt marlin
#

your django settings file

green snow
#

thx , ill try and tell if it worked

#

btw

gaunt marlin
#

sure

green snow
#

when i was learning django , the tutoral which i refered had used the user model ()

#

withut any extendion

#

and he did it usiing postgres

gaunt marlin
#

@green snow first you add user models and settings , after that create migration - > migrate

green snow
#

so when he created the db he automatically got user table

gaunt marlin
#

because the tutorial you watched create a custom user model one, not extending django based user model

green snow
#

well ill try dis first

twilit needle
#

pls ping me when you help here!

gaunt marlin
#

this isn't related to python at all :/

#

you should probably ask it in a React discord server instead

tardy heron
#

change to angular, then you can ask :/

#

j/k

twilit needle
#

@gaunt marlin this channel has support for js

sudden sierra
#

Not sure if that's what you want but, if you want to create a class that inherits from PostForm then write:

class ChildClass extends PostForm {}
twilit needle
#

the props of PostForm?

#

like props.title

sudden sierra
#

yeah

twilit needle
#

and props.post_url

#

where I define that

sudden sierra
#

The same way you defined it in PostForm, using super(props)

twilit needle
#

an example pls

#

like where I define props.post_url = 'aaa'

native tide
#

@twilit needle pass the same prop of the parent component to the child component

twilit needle
#

okay, then?

#
export default class RegistrationForm extends PostForm {

    constructor(props) {
        super(props);
}```
#

like this?

native tide
#

Can u explain what u want to do

twilit needle
#

So I have a base form class

#

I want a child class to inherit from it which has its own title, footer and fields

native tide
#

inherit what?

twilit needle
#

inherit some of the functions it has

#

like handling submissions and changes in field values

native tide
#

so pass the functions as a prop to the child?

twilit needle
#

yes

#

and also

#

pass the title and post_url

#

how can I pass it?

native tide
#

with props

twilit needle
#

please If you can give me an example I can learn from it

#

I am quite new and learning react

native tide
#

search react props. it'll give u examples and explanation better than i can

#
import AnotherComponent from '...'
 const MyComponent = () => {
    return (
       <AnotherComponent url="something" ... />       
)
}```
twilit needle
#

no like props for classes?

native tide
#

there are props for classes

twilit needle
#

I can understand props for vars and functions

native tide
#

You just render another component like:

<Component propName = "something" />

Then in that component you can access it (let's say it's a class) like this:

{this.props.propName}
#

but the faster you move onto function-based components the better, because some libraries only work for function-based not class based components

twilit needle
#

Oh

#

But my problem is

#
* Functions to be overwritten by child classes */
    form_body () {
        super.custom_body();
    }

    form_footer () {
    /* The footer is enclosed by the formFooter container */
        super.custom_footer();
    }

    act_upon_response() {
        super.act_upon_response();
    }

    act_upon_errors() {
        super.act_upon_errors();
    }
#

there are some functions like these

#

which need to be overwritten

#

so they can be only included inside classes right

native tide
#

wdym by "overwritten"

#

This seems like an overcomplication

twilit needle
#

overwritten in the sense the child component has its own form_body() function and the like

native tide
#

How about you make a new component, which is the form, and the parent will just handle the submit etc

#

So you want to pass those functions to the child component?

twilit needle
#

okay

native tide
#

You can pass functions to the child component via props too, same example as before

#
act_upon_errors() {
        super.act_upon_errors();
    }

Get rid of the super, I have no clue what it's purpose is here

#

It would be best practice though to split up components into smaller chunks. Have the child which renders the form, and have the parent handle all of the submitting, with props between the two so the child can run the parent's functions

twilit needle
#

thats a good idea i guess ill do it

native tide
#

Also forms/inputs are fiddly in native React

twilit needle
#

I have a django Virtual form for backup

native tide
#

Especially if you want to perform validation

twilit needle
#

to validate*

#

so no issues :)

native tide
#

Ok

#

Once you practice a bit of React I highly recommend the react-hook-form library, it is very good for forms.

#

Which also helps because you won't have to send a request to your server everytime for validation, slowing thinks down

versed python
#

I am making a drop down box where you can select from a number of color schemes- dark, light, sepia. As soon as you select one, the frontend retrieves the color scheme from the database and then updates the website according to it. I was wondering how I go about implementing this?

I am using python-django, Vue, and Tailwind CSS.

native tide
#

@versed python You could definitely use React or Django templates (submit a form, then re-assign the class of whatever you want to change the color for)

versed python
#

Can you elaborate what component of React you would use? I am sure that'd exist in Vue too.

#

I am not familiar with react so idk if I am looking for a component or something else

native tide
#

Infact you could probably just do it with Django's templating. Idk about Vue but it's likely to be there too

versed python
#

I am neither using React nor Django templating

native tide
#

so... what are you using?

#

because a few lines up you said:
"I am using python-django, Vue, and Tailwind CSS."

versed python
#

sorry typo

#

I meant React

native tide
#

Ok, but are you using Django?

versed python
#

yeah

#

for its databases, not for the frontend

native tide
#

So, does it do any rendering of the HTML?

versed python
#

Can I explain my use case to you? Maybe you can suggest a better solution altogether.

native tide
#

Sure. But I wouldn't be able to help with Vue, but I can give you an idea in respect to Django which may carry over

versed python
#

Would you prefer a DM?

native tide
#

Whatever you prefer

versed python
#

Okay. I will write it out. Thanks.

twilit needle
#

@native tide

#

so the FormHandler is a component

#

how can I use it to handle requests

#

its a react component right

native tide
#

is that the child, or the parent?

twilit needle
#

parent

#
class PostFormHandler extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
                values:{this.props.fields},
                errors: {},

            };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

     async handleChange(event) {
        const value = event.target.value;
        const name = event.target.name;
        await this.setState(prevState => {
          let values = Object.assign({}, prevState.values);
          values[name] = value;
          return {values};
        });
        console.log(this.state.values);
     }

    async handleSubmit(event) {
        event.preventDefault()
        await axios.post({this.props.post_url}, this.state.values)
            .then({act_upon_response()})
            .catch({act_upon_errors()});
            });
    }

}```
native tide
#

so you setup the Submit function in your parent (what happens when the form is submitted).

<ChildComponent handleSubmit={this.handleSubmit} />

You pass this to your child component as a prop.
Then in the child component you assign it to your form onSubmit event handler.

<form onSubmit={this.props.handleSubmit}

You'll have to change your parent's function to accept your form data, and be sure to include them in the parameters from your child component.

twilit needle
#
async handleSubmit(event) {
        event.preventDefault()
        await axios.post({this.props.post_url}, this.state.values)
            .then({act_upon_response()})
            .catch(error =>{
                console.log(error.response);
                this.setState({
                    errors: error.response.data.error,
                    values: error.response.data.input_data
                });
            });
    }```
#

over here

#

how can the parent access the child's this.state.values

#

??

native tide
#

You add more parameters to that function to handle the fields and pass the parameters through the onSubmit event handler in your child

naive oar
#

Hi I have a Django question?

native tide
#

In the child:

<form onSubmit={() => this.props.handleSubmit(this.state.name, this.state.email)}

In the parent

async handleSubmit(name, email) {
        event.preventDefault()
        await axios.post({this.props.post_url}, <your data in a dict>)
            .then({act_upon_response()})
            .catch(error =>{
                console.log(error.response);
                this.setState({
                    errors: error.response.data.error,
                    values: error.response.data.input_data
                });
            })}
    }```
#

Something like that

#

Also you don't need event in the handleSubmit function because you're not using it.

twilit needle
#

event.preventDefault()

native tide
#

oh gotcha

#

@naive oar Hey, what's the question

naive oar
#

@native tide I have a list of images and sometimes one image can represent multiple model numbers but I only want to display one image and the list of model numbers.

twilit needle
#

done the handling stuff

#

``js

native tide
#

@naive oar whats the HTML template looking like

twilit needle
#
this.setState({
                    errors: error.response.data.error,
                    values: error.response.data.input_data
                });```
So the error is set in the state here how do I return it?
#

to the form

native tide
#

{this.state.errors}

twilit needle
#

no it is there in the parent

#

how can I return it to child

#
lass PostFormHandler extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
                values:{},
                errors: {},

            };```
#

this one

native tide
#

Take a guess

naive oar
twilit needle
#

this.props.state.errors

#

???

native tide
#

Ok, so you think it should be this.props.state.errors in the child component. But you missed a step

#

Before a component can access a prop, what must happen for it to even be possible?

twilit needle
#

this is confusing

#

I think I forgot

#

sorry

native tide
#

You have to actually pass the prop to the component first

#

Just as we talked about before

twilit needle
#

so I have a child element?

naive oar
twilit needle
#
    <ChildComponent handleSubmit={this.handleSubmit} />
    <ChildComponent errors={this.state.errors} />```
like this?
native tide
#

@naive oar So you have a model, and each entry has an image, model, size and finish?

naive oar
#

@native tide yes that is correct

vernal furnace
#
SMTPSenderRefused at /password-reset/
(530, b'5.7.0 Authentication Required. Learn more at\n5.7.0  https://support.google.com/mail/?p=WantAuthError h2sm1061663ejx.55 - gsmtp', 'webmaster@localhost')
native tide
#

You're gonna have to group an image to multiple models then, because in your HTML code it's just looping through every entry.

vernal furnace
#

can anyone explain why

#

I get this

#

After trying to reset the password

native tide
#

@twilit needle No, look at the code you sent. How many times will that render ChildComponent?

twilit needle
#

only once?

native tide
#

Nope, you're calling it twice

naive oar
#

@native tide what would be the best approach to group an image to models?

twilit needle
#
<ChildComponent handleSubmit={this.handleSubmit} errors={this.state.errors}/>```
#

I meant like this

native tide
#

Yep

twilit needle
#

I have to call only once

#

ok I got it this is sooo interesting

#

thanks a lot for teaching me

native tide
#

Ok then how would you access errors

#

In the child

#

All good haha

twilit needle
#

errors = this.props.errors

native tide
#

Nice

twilit needle
#
        this.state = {
                values:{
                    email: '',
                    username: '',
                    password: '',
                    last_name: '',
                    first_name: ''
                    }
                errors = this.props.errors
            };
    }```
#

likethis?

native tide
#

@naive oar Well, how do you know which images correspond to each model?

twilit needle
#

in the state>?

native tide
#

Rethink that

twilit needle
#

only in component?

#

what if I wan in state?

naive oar
#

@native tide the image would be tied to the part_number

native tide
#

Yes it can be in the state, but you didn't specify it right

#

State is an object (a dictionary)

#

Anyway I got class now I will come back later and help

#

@naive oar Just a quick thought but it would have to be done manually I think. Maybe make a dictionary which includes {model numbers: image}

naive oar
#

Can I solve with a group by?

native tide
#

You could probably do some model filtering too

#

There's something on that in the docs

#

I'm not sure of it though

naive oar
#

Okay, I'll look up model filtering

#

@native tide Than you for the help!

#

*Thank you

vernal furnace
#

help guys

#

linode banned 587 port

#

how should I send emails to reset the passwords now

#

everything else is paid

#

.-.

hollow torrent
#

in drf

#

there are some fields i want to add programatically some i want to take from user

#

how to do that in serliazer

native tide
#

@hollow torrent can you explain further pls

native monolith
#
<svg width="500" height="200">
    <text text-anchor="middle", x="50%", y="50%", dy=".35em">
      | Hello John.
    </text>
</svg>

does css overwtires dimensions?

svg {
    width: 500px;
    height: 200px;
    background-color: rgb(190, 190, 255);
    fill: rgb(255,0,0);
    font-size: 5em;
    font-weight: 800;
}
hollow torrent
hollow torrent
#

have another question now

#

class SomeMode(models.Model):

#

user = models.ForeignKey(User)

#

how to have both models created in the same call

toxic flame
#

huh

hollow torrent
native monolith
#

no, css heigh is actually changing size

forest blade
#

Can anyone help me with an issue related to python flask nginx?

young oyster
#

guys, im trying to register users wth django rest framework, im using perform_create to save it and override a custom field but not sure how to properly hash the password sent in there

#
    def perform_create(self, serializer):
        ref_id = self.request.data.get('ref')
        if ref_id is not None:
            serializer.save(ref=ref_id)
        else:
            serializer.save()
native monolith
#

send token to user, hash on his side and decrypt on yours probably

native tide
#

@young oyster can you show us your serializer

swift sky
#

err so is this the correct channel to speak about nginx and websockets?

#

trying to build a chat app

#

and idk how to set up my config file

native monolith
#

its good for web building, but there is also #networks

#

depends

green snow
#

The field admin.LogEntry.user was declared with a lazy reference to 'home.customuser', but app 'home' doesn't provide model 'customuser'.

#

m getting dis error @gaunt marlin

mighty sonnet
#

Good morning everyone, does Python have an equivalent of Elixir's Phoenix Live View? For those who don't know Live View allows you to dynamically render changes to a client side ui just like React however it is actually happening on the server side and the client updates through data passed via websocket. Why would anyone want to do this you ask? Because for smaller SPAs you don't need to bring in all this complex web tooling associated with JavaScript ie: React/Redux, you handle all your state server side and only use one language

native monolith
#

how can I use scss?
i impot this
<link rel="stylesheet" href="{{ url_for('static', filename='styles/animation.scss') }}">

torn gust
#

Hey guys. I am trying to make a website connected to my bot. When you hit sign in on the site, it redirects you to the ouath2 link for the bot ("The bot would like to access your username and profile")
etc
And I want the website to display the username and profile after logged in
My bot is in discord.py, I just dont know how to connect the bot to the site in terms of code.

quick cargo
#

websocket

torn gust
#

Ive got this

wise yacht
#

Hi Guys, trying to scrape a site for a list of US states and send it to a list. i have ```for url in page_soup.find_all('div', {"class": "state-list"}):
states_list.append(url.text.strip())

print(states_list)but the output is all in a single item that looks like['Zip Codes by State\n\nAlabama\nAlaska\nArizona\nArkansas\nCalifornia\nColorado....]```

#

how can i break that out to its own list

chilly warren
#

break it down

onyx crane
#

Django (channels):
I get a value error for No route found for path
Where exactly does django look those paths up ? Is it an issue with routing.py , url.py or consumers.py ?

vivid canopy
#

hey guys i have a question i m doing site for graduation test for middle school from math....what i want to do it is generate math example but i have teoretical question there is like around 25 themes i was thinking i will do for 2 examples one html file and link him with themes site where are writed all themes but wount it be slow ....any idea or used method to do things like this'

onyx crane
#

@vivid canopy pls give more information. Your english makes it hard to understand exactly what you're trying to do ...
Are you using flask or django ?

prisma jackal
#

Can I introduce new method in class based view in django(not overriding)

vivid canopy
#

sorry my eng is so bad ...D i m using flask....just want to know how is normal to do something with a lot of themes. i was mainly meaning that if i will have a lot of html's files for example first two themes will have one html file --> it means there will be 13+ html files just for themes and all of them will use a lot of def from main.py ....i m asking if its normal do it this way or is there some other option like have all themes in one html file and what should be right way to do it (think on that i want on one theme to generate one concrete type of math example , calculate an example and comment it ....this i want from one theme )...like will not it be slow that site? if u understand it ....and sry for eng

prisma jackal
#

How can I call method in class based view inside the template django

lyric carbon
#

What's up

quick cargo
#

!rule 6 @native tide

lavish prismBOT
#

6. No spamming or unapproved advertising, including requests for paid work. Open-source projects can be shared with others in #python-general and code reviews can be asked for in a help channel.

native tide
#

oh dang

#

oops

#

😦

#

sorry

prisma jackal
#

What is slug field in django

snow sierra
#

i forgot website which can create GIF from video, (not giphy).. please?

#

ezgif also not ...

native tide
#

@prisma jackal a string of characters, like an ID

graceful falcon
#

Hey guys. Im doing my first web scraping project but vscode is throwing me some error that says unresolved import for the both the requests package and beautifulsoup package.

I have the latest version of python installed. I've created a virtual env using the pipenv shell method. I then went on to install:

pip install beautifulsoup4
pip install lxml
pip install requests

I run pip freeze and it shows that they are installed. And I can't really find anything on the internet.

If it helps, inside vscode when I try to select an interpreter in the bottom left corner or using Ctrl+Shift+P, the virtual enviro

#

I would really appreciate your assistance

cold zephyr
#

Css question

#

How do I make text have a margin in desktop but full with on mobile?

#

I used margin right:50% but looks dumb on mobile

vestal dove
#

i would like to start with web development, i've heard that "django" is one of the best libraries, is that true?

rose field
#

anyone here?

rustic pebble
#

Hi
Is there a way I can lock a Flask route so that before it gets accessed again it needs to be finished?
I am using heroku which lets you choose how many processes you want to have running at the same time which then leads to a process being run twice at the same time and accessing wrong data because it hasn't had the chance to get updated

clever hedge
#

Hey guys. I am trying to make a website connected to my bot. When you hit sign in on the site, it redirects you to the ouath2 link for the bot ("The bot would like to access your username and profile")
etc
And I want the website to display the username and profile after logged in
My bot is in discord.py, I just dont know how to connect the bot to the site in terms of code.

rustic pebble
#

I figured it

#

I am doing this:

#
        lock.acquire()
        if data['stock']:
            if not product.in_stock:
                webhook_url = 'xxxxx'

                webhook = DiscordWebhooks(webhook_url)
                webhook.set_content(title='An item has been restocked!', color=0x8f68c)
                webhook.add_field(name='Product Title', value=data['title'], inline=True)
                webhook.add_field(name='Product Price', value=data['price'], inline=True)
                webhook.set_image(url=data['product-image'])
                webhook.add_field(name='Product Link', value=product.shortened_url, inline=False)
                webhook.send()

                wu = 'XXXXX'

                wh = DiscordWebhooks(wu)
                wh.set_content(content=product.url)

                wh.send()

            product.title = data['title']
            product.image = data['product-image']
            product.price = data['price']
            product.date = data['date']
            product.in_stock = True

        else:
            product.in_stock = False
            if data['title'] != '':
                product.title = data['title']
            if data['product-image'] != '':
                product.image = data['product-image']
            product.price = data['price']
            product.date = data['date']
        product.update()
        lock.release()
#

@vestal hound

#

Basically a multiprocessing lock, I read it on stackoverflow. I basically won't to lock a route to only be done by one process at a time since I am using gunicorn and multiple processes at the same time

vestal hound
#

you'll get a deadlock if your code raises

rustic pebble
#

ah alright

#

thanks

#

Hmm do you have any idea why its not working? @vestal hound

vestal hound
#

probably because

#

you're running in multiple processes

topaz widget
#

I've got a weird issue where mobile devices don't seem to be interpreting vw units appropriately.
The units appear to work properly when using the full-size browser in "responsive mode" but not on either my iPad or my Android phone.
Has anyone run into this problem and found a solution?

rustic pebble
#

But isn't a named lock shared across all processes?

vestal hound
#

and locks exist in individual copies

#

I could be w rong

acoustic oyster
#

hello friends, I would like to listen for webhooks and I would like the practice, would it be reasonable to write this somewhat from scratch? i.e make my own http server that would be listening for several different webhooks and do different things when different webhooks are sent?

When I see examples, they all use flask or django, but this seems like overkill/not the best way to make to do this.

twilit needle
#
class PostFormHandler extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
                values:{},
                errors: {},

            };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    act_upon_response = (response) => {}

    async handleChange(event) {
        const value = event.target.value;
        const name = event.target.name;
        await this.setState(prevState => {
          let values = Object.assign({}, prevState.values);
          values[name] = value;
          return {values};
        });
        console.log(this.state.values);
    }

    async handleSubmit(event, values, post_url) {
        event.preventDefault()
        await axios.post({post_url}, values)
            .then(this.act_upon_response)
            .catch(error =>{
                console.log(error.response);
                this.setState({
                    errors: error.response.data.error,
                    values: error.response.data.input_data
                });
            });
    }

    render() {
        return (<ChildComponent handleSubmit={this.handleSubmit} errors={this.state.errors}/>);
    }
}
#

I get this error though when running npm run build for the react app

#
 Line 47:18:  'ChildComponent' is not defined  react/jsx-no-undef
#

Why? How Can I fix this?

acoustic oyster
#

I am also open to other methods to do this. I am just having trouble finding ways to do CD, without adding tons of tools inbetween

#

my original idea was to use SimpleHTTPServer but it seems like a terrible idea to use in production

twilit needle
#

can someone pls help me

#

thanks

rustic pebble
#

Github webhooks use json I think. Using a flask server is probably the easiest way.

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['POST'])
def webhook_route():
  data = request.json()
  print(data)
  return {'state': 'request_received'}

app.run()
#

@acoustic oyster

acoustic oyster
#

ok, ty. I saw that same example, I am unfamiliar with flask, so I am not sure how much boilerplate would be needed for that to work. So idk if that is a great solution? edit: I literally am unsure, pretty new territory for me.

rustic pebble
#

That's it

#

What I sent is all you need

warm igloo
#

Yeah the code posted is it.

acoustic oyster
#

would I need to use gunicorn or similar to serve it on a port?

rustic pebble
#

Not really

#

Are you planning to go production?

acoustic oyster
#

it is only for production

#

it will have very very light usage though

rustic pebble
#

Are you going to integrate it with another program?

acoustic oyster
#

it is going to be a handler that calls bash scripts (most likely) based on webhook data set from various webhooks

warm igloo
#

Also: some reason you’re trying to roll your own cd? Why not just use GitHub actions since you’re already listening for GitHub webhooks?

#

If light usage you can easily host that for free on heroku. It’ll help you set up the wsgi server etc with little for you to do.

rustic pebble
#

Then you can just do the following things:
1.

pip install gunicorn
  1. Create a a file called Procfile exactly like this:
web: gunicorn app
pip freeze > requirements.txt
  1. Change the following:
app = Flask(__name__)

to

application = app = Flask(__name__)
  1. Create a github repo and push your project
  2. Create a free tier heroku project and push the repo
  3. Boom you got urself webhook receiver
#

@acoustic oyster

acoustic oyster
#

I am using github actions, however I have not found a solution I like nor one that I can find good info on. The one webhook that is commonly used has a big red banner on the docs saying "do not use" for the exact thing I want to use it for

warm igloo
#

@rustic pebble nailed it.

rustic pebble
#

Haha

rustic pebble
#

@acoustic oyster see what I sent above

acoustic oyster
#

tyty

#

ok, I was unsure if flask made the most sense here. But I think you have convinced me haha

rustic pebble
#

Yea haha

warm igloo
#

Flask is perfectly suited for this. It’s by far my default go to.

rustic pebble
#

@warm igloo Are you good with flask?

native tide
#

what "editors" do you guys use? the only good thing ive seen so far is dreamweaver.

#

and i dont even know if thats that good

rustic pebble
#

Dreamweaver is more of a frontend tool

#

I use PyCharm

#

@native tide

native tide
#

i dont even know where to start lol. id like to use django but i dont even have any html pages made or anything yet

#

the free host i use doesnt even support django it seems. i wanna be able to modify my website, ie add photos to a page and make 'posts', without having to always edit the html and access it via FTP

#

i came across joomla, any good?

rustic pebble
#

Joomla is a CMS

#

Django is a framework

native tide
#

i see

#

think im gonna stick with joomla at the moment, i dont need anything really complicated. its just a personal site

#

i am by no means a designer lmaoo

twilit needle
#

anyone there?

#

please please help me

#

I am using Reactjs

#

and its throwing this error

#
Objects are not valid as a React child (found: object with keys {type, message, ref}). If you meant to render a collection of children, use an array instead.```
#
const onSubmit = data => {
    console.log(data);
    axios.post('/api/register/', data)
        .then(response =>{
            const token = response.data.token;
            localStorage.setItem('token', token);
            //setJwt(token);
        })
        .catch(error =>{
            const api_errors = error.response.data.error
            console.log(error.response);
            console.log(error.response.data.error);
            console.log(Object.entries(error.response.data.error));
            for (let field_property in api_errors) {
                setError(field_property, {type:'manual', message: api_errors[field_property]});
            }
        });
    }```
#

this is what am doing

#

so I am using react-hook-forms and for the error object that the api returns, I want to set errors in the form's fields

#
{data: {…}, status: 400, statusText: "Bad Request", headers: {…}, config: {…}, …}config: {url: "/api/register/", method: "post", data: "{"email":"","username":"Magical","password":"abcd1234","last_name":"","first_name":""}", headers: {…}, transformRequest: Array(1), …}data: {error: {…}, input_data: {…}}headers: {allow: "POST, OPTIONS", content-length: "228", content-type: "application/json", date: "Sat, 21 Nov 2020 05:07:35 GMT", referrer-policy: "same-origin", …}request: XMLHttpRequestΒ {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: Ζ’, …}status: 400statusText: "Bad Request"__proto__: Object
authenticationForms.jsx:20 ```
#

this is the error object returned by the api

#
data:
  error:
    email: ["This field is required."]
    first_name: ["This field is required."]
    last_name: ["This field is required."]```
#

please help me whydoes this error arise whatcan I do to stop it

hybrid bobcat
#

Do I still need virtual environment if I have docker?

twilit needle
#

pls ping me when help, thanks!

naive sparrow
#

@twilit needle you're rendering javascript object instead of a string/text that's why you are getting this error

#

If you intentionally rendering javascript object to the dom then use JSON.stringify(<your object here>)

twilit needle
#

no

#

I just want to set error with the data in the object

#

not render the object

#

@naive sparrow

naive sparrow
#

Try console.log your data you would figure it out what's wrong

twilit needle
#

I did

#

I got the data

#

the problem is with the loop I guess

#
const api_errors = error.response.data.error
            console.log(error.response);
            console.log(error.response.data.error);
            console.log(Object.entries(error.response.data.error));
            for (let field_property in api_errors) {
                console.log(field_property);
                console.log(api_errors[field_property]);
                setError(field_property, {type:'manual', message: api_errors[field_property]});
            }
        });```
#

So the error object is like this

naive sparrow
#

Can you share screenshot of your code that would be helpful to figure out what's wrong

twilit needle
#
data:
  error:
    email: ["This field is required."]
    first_name: ["This field is required."]
    last_name: ["This field is required."]```
#

@naive sparrow

naive sparrow
#

@twilit needle also send the screenshot of the code

twilit needle
#

so I have the api errors

#

@naive sparrow

naive sparrow
#

Ok let me see

twilit needle
#

so.. do you get what am trying to do

#

or should I explain more?

naive sparrow
#

@twilit needle your api is returning 400 response

twilit needle
#

yeah

#

I wanted it to respond with 400

#

because the form data is invalid

#

it also returns errors

naive sparrow
#

I guess you are setting a wrong error message somewhere

twilit needle
#

wdym

naive sparrow
#

The property is misspelled or not exit somehow

#

On the error object

#

I can't tell you what's wrong b/c i never tried a hook-library for form validation i usually use joi for that

twilit needle
#
for (let field_property in api_errors) {
                console.log(field_property);
                console.log(api_errors[field_property]);
                //setError(field_property, {type:'manual', message: api_errors[field_property]});
            }```
#

I checed the for loop

#

its fine

#

the problem is with the setError function

#

;(

naive sparrow
#

Ok Good luck

twilit needle
#
email
authenticationForms.jsx:24 ["This field is required."]
authenticationForms.jsx:23 last_name
authenticationForms.jsx:24 ["This field is required."]
authenticationForms.jsx:23 first_name
authenticationForms.jsx:24 ["This field is required."]```
#

the for loop printed this

#

it logs in console fine

#

but cant set error

#

I know the error

#

can u pls help me fix it?

#
setError(field_property, {type:'manual', message: api_errors[field_property]});```
#

So over here

#

field_property and api_errors[field_property] are objects

#

and not strings

#

so in the error object when its set, we aren't setting the string message value, but an object

#

how can I make it a string?

#

@naive sparrow

twilit needle
#

@native tide

native tide
#

In django project, if we have to create different apps, which have different purpose but the template should be same. where do you create the base.html, so that you can extend that template on every other apps?

twilit needle
#

hello
So I am using react-hook-form
I am contacting the api for error responses from it
how can I set the error obtained in my form?

const onSubmit = data => {
    axios.post('/api/register/', data)
        .then(response =>{
            const token = response.data.token;
            localStorage.setItem('token', token);
            //setJwt(token);
        })
        .catch(error =>{
            const api_errors = error.response.data.error
            for (let field_property in api_errors) {
                setError(field_property, "manual", api_errors[field_property][0]);

            }
        });```
this is what I am doing
when I console.log the field_property and api_errors[field_property][0]
the values are printed
but when I try to set an error with the same,
I get this error 
```Objects are not valid as a React child (found: object with keys {0, 1, 2, 3, 4, 5, ref}). If you meant to render a collection of children, use an array instead.```
why?
I also try to set a sample error like this 
```js
setError("username", "manual", "please choose a different username");```
I get the same error
```Objects are not valid as a React child (found: object with keys {0, 1, 2, 3, 4, 5, ref}). If you meant to render a collection of children, use an array instead.```
Can you please help me resolve this error?
https://mystb.in/AccordanceClipMelissa.javascript
this is my full code
can you please help me when you're free, thanks!
this is what I referred to also
https://react-hook-form.com/v5/api/#setError

Performant, flexible and extensible forms with easy-to-use validation.

rotund token
#

hey is anyone decent css

#

i have these links and i want to make them transition to a different colour when u hover over it and some sort of movement of the text. is this possible

twilit needle
#

yeah it is

#

send me ur code

rotund token
#

can u please help me if so

twilit needle
rotund token
#
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
  <title>Mr. Canino's Class!</title>
</head>
<body>
  <nav>
    <div class="logo">
      <h4>Mr. Canino's Class</h4>
    </div>
    <ul class="nav-links">
      <li><a href="#">Home</a></li>
      <li><a href="#">Web Development</a></li>
      <li><a href="#">Python Programing</a></li>
      <li><a href="#">Scratch Programing</a></li>
    </ul>
  </nav>
</body>
</html>```
twilit needle
#

I meant

#

the css

rotund token
#

that is the html

twilit needle
#

ok

rotund token
#
* {
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
}

nav{
    display: flex;
    justify-content: space-around;
    align-items: center;
    min-height: 8vh;
    background-color: #2e2a27;
    font-family: 'Poppins', sans-serif;
}

.logo {
    color: rgb(226, 226, 226);
    text-transform: uppercase;
    letter-spacing: 5px;
    font-size: 20px;
}

.nav-links {
    display: flex;
    justify-content: space-around;
    width: 50%;
}

.nav-links li {
    list-style: none;
}

.nav-links a {
    color: rgb(226, 226, 226);
    text-decoration: none;
    letter-spacing: 2px;
    font-weight: bold;
    font-size: 14px;
}

.nav-links::hover {
    cursor: pointer;
    color: black;
}```
#

i was sending both πŸ™‚

#

and when you scroll down and it fades away

dreamy seal
#

How to store the user uploaded pic in django

twilit needle
#
.nav-links a:hover{
  color: /* color code u want */;
  transition:0.25s; /* this eases transition */```
dreamy seal
#

If suppose there are 2 users we have to store those in django.How would i do it?

twilit needle
#

I suggest u use animate.css for movement of text

#

its an elegant solution

dreamy seal
#

just like social media thing

rotund token
#

so make a new file

twilit needle
#

@rotund token

twilit needle
rotund token
#

@twilit needle it isn't working

twilit needle
#

what isnt working

rotund token
#

dw

twilit needle
#

assuming the color,
this is overwriting it css .nav-links::hover { cursor: pointer; color: black; }

rotund token
#

how do i make it go away when i scoll down

twilit needle
#
.nav-links a:hover{
  color: /* color code u want */ !important;
  transition:0.25s !important; /* this eases transition */```
this prevents overwriting props
#

check out the animation.css lib

rotund token
#

how do i use it and import it

twilit needle
#

and link it with onscroll event in css

twilit needle
#
$ npm install animate.css --save```
#
  <link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
  />```
#

here's an example

.my-element {
  display: inline-block;
  margin: 0 0.5rem;

  animation: bounce; /* referring directly to the animation's @keyframe declaration */
  animation-duration: 2s; /* don't forget to set a duration! */
}```
rotund token
#

can u add it to my code and then teach me how to install it

twilit needle
#

do you have node.js?

rotund token
#

no 😦

twilit needle
#

okay

#

go to your project root and open a cmd line there

#

type

yarn add animate.css```
#

to install the lib

#

sorry I gtg

#

so will be fast

#

then, go to the head section of your html

rotund token
#

ok im in the root now what

twilit needle
#

thats the setup.
After that you can use it like

rotund token
#

yarn didnt work

twilit needle
#

wait

rotund token
#

okk

#

it didn't work

twilit needle
#

on windows?

rotund token
#

yessir

twilit needle
#

better install it ur gonna need it in the future and now

#

so that should be it

#

I really should go now, if you have any doubts ask it here someone else will answer it :)

rotund token
#

ok

green snow
#

how to take value from a button?

#

like i need a boolean value in django views

gusty hedge
green snow
gusty hedge
#

?

#

what do you want to do?

green snow
#

so i need that "register as" value

gusty hedge
#

so you need to send that to django?

green snow
#

yup

#

i sent evrythng except that boolean field

#

which is bydefault false

#

"isteacher" is the name in DB

twilit needle
twilit needle
gusty hedge
#

you can convert it to Boolean in your view or...

twilit needle
#

this is the form on codesandbox

gusty hedge
twilit needle
#

me?

gusty hedge
#

no

green snow
#

well ive done it

twilit needle
green snow
#

it is a boolean field in my db and views

#

isteacher = requests.POST['isteacher']

gusty hedge
#

so your problem is not in Django but how you send the data to Django

green snow
#

yup

#

idk html really well

#

ill send u the html snipped

gusty hedge
#

are you using Django Widgets?

green snow
#

idk what that is

gusty hedge
#

ok. Share your html

green snow
#

<button class="btn btn-outline-secondary" name="isteacher" value="True" type="button" >Teacher</button> 

<button class="btn btn-outline-secondary" name="isstudent" value="False" type="button">Student</button> 
</div>```
#

this is in a form

gusty hedge
#

ok, hold on

lavish prismBOT
#

Hey @green snow!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .webm, .webp, .flac, .afdesign, .m4a, .csv.

Feel free to ask in #community-meta if you think this is a mistake.

green snow
#

@gusty hedge

#

bro

#

ill send u the whole file u will understand

gusty hedge
#

ok

lavish prismBOT
#

Hey @green snow!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

green snow
#

man how do i send it

lavish prismBOT
gusty hedge
green snow
#

i pasted

#

u can see now?

gusty hedge
#

yep

coral raven
#

Hey I need some help with deploying flask app on heroku

#

I pushed the code, added environment variables, upgraded the database and restarted the server

#

Still there is an error

gusty hedge
#

@green snow what don't you replace those buttons to checkboxes?

green snow
#

i can do that

#

only i dont know the difference

gusty hedge
#

I don't think buttons can hold states like you are trying to

green snow
#

ok

#

but wat if the user checks both

gusty hedge
#

if you don't want multichoice then you might want to use radiobutton instead

green snow
#

ya like the user can either be a teacher or a student not both

#

i thought wat i was using so far was radio button

gusty hedge
#

those are regular buttons

green snow
#

silly me

#

the thing is i searched radio buttons on bootstrap and got this

gusty hedge
#

though you won't get a True/False value from it

#

you will get "isteacher" or "isstudent", decide what to do with that info in Django, I guess?

green snow
#

ya like use if else

#

i m not sure but ill try dis

echo river
#

Hi, I facing some problem on Django, when I run manage.py collectstatic, it bound from django.contrib.contenttypes import generic, ImportError cannot import name generic

green snow
#

@gusty hedge

#

so that "options" will return : whatever u will put in place of "Active"/"Radio"/"Radio" , correct?

gusty hedge
#

I think you are missing the value attribute

green snow
#
<input type="radio" name="options" value="True" id="option1" checked> Teacher
</label>

<label class="btn btn-secondary">
<input type="radio" name="options" value="False" id="option2"> student
</label>```
#

@gusty hedge dis does?

woeful nymph
toxic flame
#

@woeful nymph the default / console way on creating entries

#

lol

green snow
#

it worked @gusty hedge thx a lot , this is my ,firsttime doing a web project so i make such silly mistakes

gusty hedge
#

glad to know, don't punish yourself, we all make mistakes everyday

green snow
#

πŸ˜‡

toxic flame
#

Personally i think a drop down would make it look alot better

woeful nymph
green snow
modest shale
#

guys hola

broken hare
#

while fetching stuff from the database there are such strange things, does someone know how to fix it?

coral raven
#

What was in your db?

native tide
#

how to set debug false in django 3.1

#

pls sombody see this and help me

broken hare
coral raven
#

@native tide settings

woeful nymph
#

Help plz

prisma jackal
#

I can't see

stable kite
native tide
#

best way to get started on node.js

#

a/

#

?

#

can someone tell me the best way to get started in node.js?

vale vault
#

Hey guys. I got a blog website up, and i want to improve it. Right now, blog post as text in the data base, but it's very limited. I rather use html or markdown.

#

My website is written in flask

native tide
#

hhelp

#

can someone tell me the best way to get started in node.js?

vale vault
#

Build a project.

native tide
#

how

#

i m a complete beginner to server side programming

#

i know my client side well

#

html and css

vale vault
#

To start i would try the documentation, and searching github for examples.

native tide
#

ok

vale vault
native tide
#

what is the easiest way to deploy a flask website?

#

also what is this gunicorn thing i keep hearing about when i search for deployment options?

#

i didnt install that. neither did i make a venv .so am i f*cked?

marsh canyon
#

gunicorn is a wsgi server, basically, it converts your raw HTTP request to a readble python object(a dict)

#

and then this dict is passed into your flask/django app

#

a common setup is
nginx -> gunicorn -> flask/django

native tide
#

so flask uses gunicorn behind the scenes?

marsh canyon
#

ye

native tide
#

ok

marsh canyon
#

u need to install gunicorn tho

#

and configure it to use flask

native tide
#

what

marsh canyon
#

there should a bunch of tutorials online

native tide
#

u just said it uses it

marsh canyon
#

I meant, it needs*

#

sry

#

they work together

native tide
#

my app somehow runs without that

marsh canyon
#

they use waitress instead of gunicorn tho

native tide
#

thanks . ill look into it when i get the time. ive been on for five hrs and i cant even type

#

thanks @marsh canyon

marsh canyon
#

πŸ‘

toxic flame
#

@woeful nymph .create bro

#

Model.objects.create(

stuff here

)

native tide
#

Anyone know about Flask Jinka Extension

#

*jinja

#

tried to creat jinja env with loopcontrol extension, still {% break %) not working πŸ˜₯

spring sequoia
#

anyone have experience running running a web server using express js, we are having issues with cookies not working, but in vscode live server they do

haughty turtle
#

Trying to understand how Django verifies if a user is still logged in, I get how it logs in, sends the I'd and pass over through post and it's checked through backend, but how does it verify that a user it's still logged in without having to send the I'd and pass again...

haughty turtle
#
Warning

If the SECRET_KEY is not kept secret and you are using the PickleSerializer, this can lead to arbitrary remote code execution.

An attacker in possession of the SECRET_KEY can not only generate falsified session data, which your site will trust, but also remotely execute arbitrary code, as the data is serialized using pickle.

If you use cookie-based sessions, pay extra care that your secret key is always kept completely secret, for any system which might be remotely accessible.

The session data is signed but not encrypted

When using the cookies backend the session data can be read by the client.

A MAC (Message Authentication Code) is used to protect the data against changes by the client, so that the session data will be invalidated when being tampered with. The same invalidation happens if the client storing the cookie (e.g. your user’s browser) can’t store all of the session cookie and drops data. Even though Django compresses the data, it’s still entirely possible to exceed the common limit of 4096 bytes per cookie.

No freshness guarantee

Note also that while the MAC can guarantee the authenticity of the data (that it was generated by your site, and not someone else), and the integrity of the data (that it is all there and correct), it cannot guarantee freshness i.e. that you are being sent back the last thing you sent to the client. This means that for some uses of session data, the cookie backend might open you up to replay attacks. Unlike other session backends which keep a server-side record of each session and invalidate it when a user logs out, cookie-based sessions are not invalidated when a user logs out. Thus if an attacker steals a user’s cookie, they can use that cookie to login as that user even if the user logs out. Cookies will only be detected as β€˜stale’ if they are older than your SESSION_COOKIE_AGE.

Performance

Finally, the size of a cookie can have an impact on the speed of your site.```
#

NVM found it, got the security warnings I wanted

torpid pecan
#

I have added new pages to my Django site but they only appear on my Dev server(localHost) and not my actual server using nginx and gunicorn. Both server contain the same files. How do I get it to update?

haughty turtle
#

Not one detailed guide on file based sessions πŸ‘

atomic mulch
#

Hello everyone, I was wondering if I could get some help. I am passing a dictionary from a route to an html page. I want to unpack the dictionary in the html page and display that information via a <li> tag but can only either get all the information in two <li> or only the key's value depending on which I choose. Ex) test = {key1 : [chapter1, chapter2, chapter3, etc] ,
key2 : { chapter1_link, chapter2_link, chapter3_link]

jaunty sedge
#

can anybody explain how flask_sqlalchemy is different from regular sqlalchemy?

odd swallow
#

hi was wondering if someone could help me trouble shoot setting up gunicorn in docker. been trying to convert my local to a dev server i think i have a slight error in my docker command but not sure what

small crest
#

How would I add markdown to a django website?

#

I just want the markdown to work in the content

#
blog/models.py


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
#

so a markdown field instead of text

native tide
#
{% for img in image %}
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="{{ img['url'] }}" alt="img['caption']">
      <div class="carousel-caption">
        <h3>{{ img["caption"] }}</h3>
      </div>
    </div>
  {% endfor %}

I'm getting a data set from a database, and it results in something like:

[{"url": "this", "caption": "This"},{"url": "this", "caption": "This"}]

However, this is the result:
Any help would be appericated

#

Please ping me, I need to go soon

surreal horizon
#

Guys would it be better to use Javascript as frontend and backend for my web applications, or use Javascript as frontend and Python (Django) as backend? Please ping me and thanks in advance πŸ™

small crest
#
{% extends "blog/base.html" %}
{% block content %}
    {% for post in posts %}
        <article class="media content-section">
          <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
          <div class="media-body">
            <div class="article-metadata">
              <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
              <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
            </div>
            <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
          </div>
        </article>
    {% endfor %}
    {% if is_paginated %}
#

How do I render the post.content in markdown

#

Currently it is a Django text field, and it won't highlight links, bold etc.

#

Here is all the code

cerulean remnant
#

ummmmm, idk anything about web development, so i can't help, sry

small crest
#

Ohh... That's fine, this is just a hobby project for me

coral raven
#

@native tide The alt attr in the img should be wrapped with {{ }}. Check if the url works as intended

#

@surreal horizon Its your choice actually, both will do the same thing in the end.

#

@small crest you would need a package to render text to markdown

#

You can also do that in the frontend by using JavaScript marked library

dense yarrow
#

Hello, IΒ try to custom validate a field using flask appbuilder

#

the UI it says "invalid input" ..

#

Someone knows how to deal with from validation in Flask AppBuilder ?

winter spindle
#
{% if {{ tasks.count }} > 0 %}
        <button><a href="{% url 'todo:delete_all' %}">Delele all</a></button>
    {% else %}
        <button style="display: hidden;"><a href="{% url 'todo:delete_all' %}">Delele all</a></button>
    {% endif %} 
#

hey i wanted to make a button appear when the items in my todo list are more than zero

#

and to disappear when it is zeo

#

but this doesn't seem to work

#

tasks is the list of all the objects i.e all the items in the list

twilit needle
#

I have a doubt

#

So I make a post request to the api and it responds with a token for authentication

#

where and how can I store this token?

#

And how can I use the token to access token info?

native tide
#

yo

rotund token
#

can anyone help me with adding a drop down menu to my nav bar

#

@twilit needle

prisma jackal
#

How can I grab the pk variable from url and make it available to view, I am using django

stable kite
prisma jackal
#

I want it to be available inside the class based view

winter spindle
marsh canyon
#

try tasks|length instead @winter spindle

winter spindle
#

wait i will send the error

#

this is the error tht i get @marsh canyon

marsh canyon
#

dont use {{ }} inside {% %}

#

remove those

haughty turtle
#

Trying to figure out the best practices for Django.

#

So do I really need to create a separate app just for user registration and login?

#

Or should I store this all under an app called mainApp?

green snow
#

id reccomend seperate app

#

also it will be easier if u want to reuse it

#

but im no expert

haughty turtle
#

I just find it a bit annoying creating so many apps.

green snow
#

i think it depends on what u r making

haughty turtle
#

I'll create a new app, thanks @green snow

green snow
#

yea

#

im unable to use list index in an html page

#

(im doing a django project)

#

the thing is the list is being displayed {{listname}} but {{listname[1]}} isnt working

#

error: Could not parse the remainder: '[1]' from 'nests[1]'

#

okay so the thing is u cant do this normally like u do in python

#

   {{ listname.index_no}}

{% endwith %}```
#

add this to your code it will work

#

it is working now ,thanks

native tide
#

hey guys

#

I just started learning Flask today and i'm stuck

#

i'm getting this error

#

help

haughty turtle
#

Linode best site to host my web app?

#

$5 linode vps enough ?

#

Starting out? Less then 500 users per month?

tawdry oasis
#

hry guys how can i put a background wall paper to my website

devout coral
#

@haughty turtle That’s plenty. If you really want go with a t2.micro from AWS.

#

Which should be free.

devout coral
tawdry oasis
#

i did @devout coral

#

its just not showing me

devout coral
#

Let me see the css plz

tawdry oasis
#

body {
background-image: src = "htmljpg.jpg") no-repeat fixed;
}

#

body {
background-image: url= "htmljpg.jpg") no-repeat center center fixed;
}

#

this one too

devout coral
#

!code

tawdry oasis
#
body { 
    background-image: src = "htmljpg.jpg") no-repeat center center fixed;
    }
#
body { 
    background-image: url= "htmljpg.jpg") no-repeat center center fixed;
    }
devout coral
#
body { 
    background-image: url(β€œhtmljpg.jpg”);
    }
#

Try that

stable kite
tawdry oasis
#

its not working

#

idk why

devout coral
#

You have the right name for your image?

tawdry oasis
#

yeah

devout coral
#

It’s in the same directory as your css file?

tawdry oasis
#

yeah

devout coral
#

Can I see your directory tree and paste bin your entire css file for me?

tawdry oasis
#

how can i do that

devout coral
#

Uhhh, go to the root directory of your project and just take a screenshot I guess

#

How many lines of code is your css file? If it’s small just put it in a code block

tawdry oasis
#

htmljpg is the photo/img

#

that i want to put

devout coral
#

Are you not using a css file? You are using a style tag?

tawdry oasis
#

what do you mean by that

#

??

devout coral
#

Where are you writing the code you posted earlier?

tawdry oasis
#

Vs code

devout coral
#

I mean which file

tawdry oasis
#

i made a file calles my web

#

and puted every thing in it

devout coral
#

Ok the css code, is it wrapped inside of a style tag?

tawdry oasis
#

yeah

devout coral
#

Ok, can you post everything inside the style tag?

tawdry oasis
#
<!DOCTYPE html>
<html> 
<style>
<body>

body { 
    background-image: url(β€œhtmljpg.jpg”);
    }
</style>
<h1>  Welcome to  web </h1>
devout coral
#
<!DOCTYPE html>
<html> 
<head>
<style>


body { 
    background-image: url(β€œhtmljpg.jpg”);
    }
</style>
</head>
<body>
<h1>  Welcome to  web </h1>
</body>
</html>
tawdry oasis
#

i try this?

devout coral
#

Try that

tawdry oasis
#

nope

#

there is something wrong with the url i think

#

how can i make sure the url is working

devout coral
#

What is the name of the file that contains that?

tawdry oasis
#

?

#

myweb

devout coral
#

Is the h1 tag showing?

tawdry oasis
#

yeah

#

you mean like welcome to web?

#

yeah

devout coral
#

Hmmm, One second

#
<!DOCTYPE html>
<html>
<head>
    <style>


        body {
            background-image: url("htmljpg.jpg");
        }
    </style>
</head>
<body>
<h1>  Welcome to  web </h1>
</body>
</html>
#

That should work assuming your jpg is in the same directory as the file with the html code

native tide
#

@haughty turtle don't create new apps for individual things, like login/signup, make apps more generally

haughty turtle
#

So just create a mainApp for non complicated functions? Such as linking to my index and login sign up etc?

#

@native tide

native tide
#

Yeah so say you had a dashboard, keep everything that's linked with that dashboard inside that app. Maybe you have a landing page with the login/signup form that appears, keep that linked inside the landing page app, etc

tawdry oasis
#

how can i make my background not repeating

woeful nymph
#

Do you guys know any good learning sites for Django?

haughty turtle
#

The Django documentation has a good tutorial

#

Just add no-repeat in background in your CSS file @tawdry oasis

#

background: url() no-repeat;

tawdry oasis
#

its remooving the background

#

when i put it

#

@haughty turtle

haughty turtle
#

background: url("htmljpg.jpg") no-repeat;

#

Use that and remove the background-image you have

#

@tawdry oasis

#

Really I suggest you follow some CSS videos in detail so that you can search w3 for all CSS attributes @tawdry oasis

#

@devout coral got a tc2 set up for testing purposes, what should I use to serve my files Nginx or Apache

#

I see people say to use both one for Static files and one to serve the python files is this true?

devout coral
#

I’ve used Apache in the past but it’s also old. I’m currently transitioning to using Traefik.

#

Granted that’s because I have everything in Docker containers now. If you have a simple Django set up Apache2 will probably be the easiest.

haughty turtle
#

@surreal horizon ummm JavaScript and Django are not the same o.o

surreal horizon
#

ik

#

but which one can i use for backend

haughty turtle
#

Django

#

It's a framework built to provide you ease and security

surreal horizon
#

i see

haughty turtle
#

Your going to fail miserably with JavaScript as a backend and you should not be doing so. Have people really used JavaScript for backend...

surreal horizon
#

yeah

#

ppl have

#

lol

haughty turtle
#

You use JavaScript to send sensitive information over to your backend as JavaScript isn't build with security in mind to serve as a backend.

#

Could be Node.js?

#

It seems to be a framework

hidden yoke
#

Heyy i need some help with Instagram API.
Anyone here who can help?

serene prawn
#

Hello, my django sends wrong Content-Type content type headers for my js files. How could i change that?

#

Content-Type is text/plain but should be text/javascript

#

And chrome refuses to load files at all

haughty turtle
#

@serene prawn

#

Take a look at that link

#

Also it's a warning not an error, is it preventing you from achieving something?

native tide
#

Hey, I'm learning FastAPI, anyone has an idea for a website? I have already made a blog

#

I'm a student so I have a lot of free time right now because of the pandemic

native monolith
#

timezone converter

#

or decimal time converter

native monolith
#

my web breaks when I send files larger than 10MB ~

#

is flask restricted somehow ?

native tide
#

@haughty turtle @surreal horizon You can use JS for backends - and it's very popular w/ Express. Idk which one is more popular: Django or Express, but they have their own uses.

#

And a lot of people start with JS as their first language, learning something like React pairs well with JS backends like Express. It's harder when you're trying to juggle languages.

quick cargo
#

Django is still more popular atm

#

though its pretty tight

#

Express is easy for people to get into but god damn does it doesnt protect new users anywhere near as much as Python frameworks

native tide
#

That's surprising, which would you say is the most popular backend framework then?

#

Out of all them

#

Laravel 😳

native monolith
#

backend?

#

flask and django are frameworks for sure

#

django has some backendish stuff but ...

native tide
#

what?

native tide
#

FastAPI is better though

#

:d

#

No it depends on what you do

#

But it can be scaled up to whatever you want it to be

native monolith
#

got simple question, how can I verify if upload picture is ok, before uploading and checking in next function?

native tide
#

It depends on what you mean by "ok"

native monolith
#

check size and extension

#
@app.route("/upload", methods=["GET"])
def upload():
    "Image is beeing uploaded here"


@app.route("/process_image", methods=["GET", "POST"])
def process_image():
    "I check image in next url"
#

I upload image in first page, then user gets redirected by form action

#
<div class="container">

  <form action='{{ url_for("process_image") }}' method="POST" enctype="multipart/form-data">
    <div class="form-group">
<!--      <div class="custom-file">-->
        <input type="file" class="custom-file-input" name="upImage" id="upImage">
<!--        <label class="custom-file-label" for="image">txt2.</label>-->
<!--      </div>-->
    </div>

    <button type="submit" class="btn btn-primary">Confirm</button>

  </form>

@native tide

copper lagoon
#

How can I get the State of a checkbox in html using flask? Ping me with responses

native tide
#

(venv) PS C:\Users\chris\Documents\Programming\Github\React-App\DRF-Django> coverage run --omit='*/venv/*' manage.py test

Fatal error in launcher: Unable to create process using '"c:\users\chris\documents\programming\github\react-app\venv\scripts\python.exe"  "C:\Users\chris\Documents\Programming\Github\React-App\DRF-Django\venv\Scripts\coverage.exe" run --omit=*/venv/* manage.py test': The system cannot find the file specified.

can anyone help me re-configure the file path for coverage?

#

currently can't view any .exe views to change the file path.

native monolith
serene prawn
hybrid bobcat
#

WSL2 does not come with docker

#

and i have no idea how to get it

#

does anyone?