#web-development

2 messages ยท Page 24 of 1

wicked kernel
#

essentially I want the server to send a message every second

#

and only actually send or append based on permissions

north swift
#

honestly I cant see what's wrong there

wicked kernel
#

is flask open source?

#

do they have a github i can post an Issue to?

north swift
#

for sure

outer lynx
#
.center {
    position: absolute;
    margin: auto;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 0.5em;
    height: 10em;
    text-align: center;
    display: inline-block;
} .center-under {
    height: 0;
  }

.samaritan {
    transform: translate(-50%, -50%);
    border: 0;
    font-size: 48px;
    box-shadow: none;
    border-bottom: 1px solid #000;
}  :focus {
    outline: none;
  }```
#
<html>
<head>
    <title>IลŸฤฑk Kaplan</title>
    <link rel="stylesheet" type="text/css" href="onecsstorulethemall.css">
    <script defer src="onescripttorulethemall.js"></script>
</head>
    <body>
        <div class="center">
            <input
                type="text"
                class="samaritan"
                placeholder=""
                spellcheck="false"
                autocapitalize="off"
            >
        </div>

        <div class="center center-under">
            <span>HELLO</span>
        </div>
    </body>
</html>```
#

Hello is not directly under the help, rather starts typing from the exact middle
I want the entire hello to be in the middle
Not the start of the hello to be the middle

limber orchid
#

I'm looking at someone else's code for a flask app and trying to learn some basic stuff with it. I don't quite understand what's going on with this in a template and how it's 'seeing' these variables despite not being passed in the render_template() method

<div class="w3-container">
    <p>
    {% if config.lang == 'fr' %}
    Pour commencer un test, utilisez le lien d'activation
    que vous avez reรงu.
    {% else %}
    You need an activation link to start a quiz.
    {% endif %}
    </p>
outer lynx
#

There are context processors

limber orchid
#

config is app.config, I've seen that much but...

outer lynx
#

Context processors can give global context to templates

limber orchid
#

so if I make a variable of my own in my app how can I turn it into one of these global type things?

outer lynx
#
@app.context_processor
def _():
    return {'global': 'hello'}```
limber orchid
#

where context_processor is the name of the variable?

outer lynx
#

no

#

global is

limber orchid
#

I'm looking for it in the py file and don't see anything named like that

outer lynx
#
@app.context_processor
def _():
    return {
        'global_var_1': 'val_1',
        'global_var_2': 'val_2',
        'global_var_3': 'val_3',
    }```
#

This can be anywhere

#

But config is by default

#

config session request url_for are just a couple of them

limber orchid
#

thanks, I'll keep digging

#

I just can't find where they hid this dictionary

#

or is it possible to set a new entry inside the app?

#

like, all I'm seeing is things being initialized like

app.config['key'] = 'thing'
#

do I need to go into the config to create first 'key' entry or will it let me set it like this?

#

ok nm, I tested it and it seems to work like that

#

thanks again for the help

late gale
#

hi is there a way to get a template and put it in my django cause it takes too much time to make a custom template

#

hello?

outer lynx
#

hi is there a way to get a template and put it in my django cause it takes too much time to make a custom template

#

as in?

#

"get a template"

#

you can just google for templates

#

and pick one

kindred cosmos
#

Build your templates so they are easy to make

#

A django template is tied to the application

hushed burrow
#

hi, has anyone deployed a python web app on azure before ?

#

got a simple question regarding their deployment tutorial for python apps

outer lynx
#

Mind showing your app structure?

native tide
#

I re-write everything

#

it's working now.

native tide
#

oh god solved it

kindred cosmos
#

@outer lynx Who?

inner kayak
#

Hello guys!
I'm looking for a big community for Django/DRF specifically, am I in the right place? ๐Ÿ˜„

kindred cosmos
#

I use Django Rest Framework

#

Are you using swagger too?

#

@inner kayak

inner kayak
#

I learned Django like a year ago and I'm getting back to it.
No I haven't used Swagger yet, still getting my hands dirty learning the basics to build confidence around the framework, the docs come later!

kindred cosmos
#

True but it wouldn't hurt to use it

#

I guess it depeneds on the project at hand

inner kayak
#

Do you recommend any project to get myself started? still going thru the tuts, that would help me alot ๐Ÿ˜„

kindred cosmos
#

Something usefull for your self

#

Build something that you yourself would use

#

Timetracking isn't a bad place to start

#

That's how I started

#

What I like to do also is finding a project you think is good and learn it

#

Even if you don't end up changing any code it's very intersting see how other people programmed their django apps

inner kayak
#

Honestly i'm lacking imagination, I need to build a project that is consistent enough to show it on my portfolio, yes its generally a good idea to read other people's code, its one the best way to learn thank you for the tip!

kindred cosmos
#

Try but you can get ideas from other people's code

#

Believe me, sometime I look at code and I am like damn I want to do that and implement it in my own project

inner kayak
#

Alright man thanks for the tips ๐Ÿ˜„

kindred cosmos
#

No problem

#

I could talk all day about code

inner kayak
#

One last thing, which django app you recommend me reading?

kindred cosmos
#

I would high recommend looking at Raymond Hettinger talks on wirting better python code too

#

Hmm

#

Huge project

inner kayak
#

No way, didnt know OpenStack was built on django!

kindred cosmos
#

Parts of it are

#

That frontend peice is

#

Almost all of the api servers are built in flask such as nova, cinder and neutron

#

Those are intersting too to look at

#

I remeber looking at what it would take to wirte my own openstack nova driver

#

It didn't look too hard

#

Because their code is pretty good

inner kayak
#

Very interesting indeed, lost myself on reading now tbh x)

kindred cosmos
#

You're good man

inner kayak
#

Tell me, Is Django Rest considered the best way to create robust/secure API? because that's the reason i started learning it. do you think other frameworks offer better alternatives? (I prefer batteries included type )

kindred cosmos
#

Honestly the django rest framework belows me out the fucking water

#

It's so powerful yet simple

#

Anything I would ever want to do with a Rest api is possible with the django rest framework

#

I told a programmer, who has never touch django, or even knew about rest to make an api endpoint. He figured the django rest framework out in like 4 hours

inner kayak
#

That's encouraging, glad to know I'm on the right track x)

#

I'm surprised there is too few content

#

had a hard time finding a community

kindred cosmos
#

Good luck man! I figured this out and I ended getting a job for doing django deveoplment

#

I think it's crazy because I don't even have a degree

inner kayak
#

Thank you so much for the help mate. Really appreciated it ๐Ÿ˜„

kindred cosmos
#

No problem, I am glad to shoot the shit anytime

kindred cosmos
#

I don't know why but I hate frontend so much

#

Javascript feels like mine field of anti patterns

outer lynx
#

@kindred cosmos Why ping me?

kindred cosmos
#

You said Mind showing your app structure?

pallid root
#

hello guys
iam beginner in leaarning pyhton
i want to prompt the user to write serial key and user name in the displayed string any one know how to excute two command at the same time in python ??

#

here the simple code

#

i still learn the basics

#

i want user name and serial key to be appeared at the same time in the compiled code

#

any help

#

??

outer lynx
#

Why would I say show your app structure to you when you didn't even ask a question??

#

@pallid root You might be better off at one of the #help channels, doesn't look like #web-development

pallid root
#

iam sorry @outer lynx

outer lynx
#

why?

rare oar
#

all, I've worked out some of my things from earlier and I thank you for it. I'm working on a problem right now where my annotations seem incorrect when I try to incorporate more filtering with django_filter
Here is a mockup of everything
https://dpaste.de/RoQi

#

The annotations get bloated almost like its not going over the model's queryset but the full queryset

uncut solar
#

I'm looking for an async Flask-like webframework

#

There seems to be millions of options

#

So far I've looked at Sanic, Quart, Starlette

#

Any recommendations?

north swift
#

@outer lynx may I get an explanation about the @app.context_processor thing?

outer lynx
#

uhh

#

sure

#

What do you need explained

north swift
#

Im unsure if its due to me using blueprints

#

I have currently an app.py implementing a blueprint with my routes

#

@app.context_processor
def _():
return {
'test': '123'
}

#

and that

outer lynx
#

Any context processor you create from the app is global

#

And will be applied to your blueprints

north swift
#

shouldnt I get to read 123 if I do {{ test }} in the rendered template?

outer lynx
#

yes

north swift
#

that's not happening

outer lynx
#

Any errors?

north swift
#

nope

outer lynx
#

what happens instead?

north swift
#

i'll double check really fast just in case

#

just blank

#

damn I'm not smart

#

did the app context under the app start

#

<.<

#

also, is the context_processor the place where I should initialize a db connection?

#

considering that I'll need to access it from the blueprints

outer lynx
#

what

#

You should be handling the db stuff in your view

#

not in your template

north swift
#

so I'll need to connect to mysql with sqlalchemy on each .py file that needs it?

outer lynx
#

No

#

It is like blueprints

#

you write your database stuff in a file

#

you import it in blueprints

#

use it

#

then import it in your main

#

and init it

north swift
#

ah makes sense

#

ty

outer lynx
#

^^

junior cloak
#

@uncut solar what matters most to you for an async framework? What will you be using it for? Iโ€™ve building our platform on startlette, which is among the newer but is the best performing, has a lot of momentum, and is written by the guy who also created the ASGI spec that other frameworks use under the hood: https://www.starlette.io/

#

It doesnโ€™t have as much baked in as others but itโ€™s actively developed and then again it also has a few things baked in that others do not (such as graphql, swagger, etc)

#

@uncut solar the others Iโ€™ve used and enjoyed the most over the last couple years are aiohttp and sanic. They all have their ups/downs so let us know if you have more specific criteria. Iโ€™ve only been writing async backend code for at least a couple years now and Iโ€™ve encountered most of the joys as well as pain points

uncut solar
#

Idk, the only requirement right now is websockets

#

Thanks, I think I'll go with starlette

junior cloak
#

@uncut solar starlette is great. they all handle websockets well. just gotta be really good about using async properly and all that jazz. the same guy also makes a good async framework for use with sqlalchemy and such

native tide
#

How to do a 24 hour clock in html?
In 00h00 format.

junior cloak
#

@native tide well, not much to do. you use javascript. you get a new Date(). it will return an object with the current date and time. running its getHours() method will return what hour it is in 24-hour format.

meager anchor
#

+1 for starlette, great framework

native tide
#

Thx.
@junior cloak

limber orchid
#

I have a WTForm and it's being printed via flask this way

<form action="/" method="POST" role="form">
                        <table class="w3-container w3-table w3-bordered w3-striped">
                        {% for field in form %}
                          <tr class="w3-red">
                            <th>{{ field.label }}</th>
                          </tr><tr>
                            <td>{{ field }}</td>

                          </tr>
                        {% endfor %}
                            </form>
#

but the fields, which are radio buttons, are being printed with bullets

#

how do I specify that I don't want the bullets?

hollow aurora
#

@limber orchid I don't see any radio buttons here

limber orchid
#

they are in the object, one sec I'll grab the source .py

#
class Quiz(Form):
    name = StringField(u'username', validators=[input_required()])

    q1 = RadioField(
        "Rule #1 prohibits",
        choices=[('chioce 1','chioce 1'),
        ('chioce 3', 'chioce 3'),
        ('chioce 2','chioce 2'),
        ('chioce 4','chioce 4'),
        ('all of the above','all of the above')
        ],
        validators=[CorrectAnswer('all of the above')]
        )
    submit = SubmitField("Submit")
hollow aurora
#

and what is the html output?

limber orchid
hollow aurora
#

i mean in code?

limber orchid
#

diff q, but from the same class

#

sorry, sec

#
<tr class="w3-red">
                            <th><label for="q3">How often can you post a link to your site?</label></th>
                          </tr><tr>
                            <td>
            <ul id="q3">
                <li><input id="q3-0" name="q3" type="radio" value="never"> 
                <label for="q3-0">never</label></li>
                <li><input id="q3-1" name="q3" type="radio" value="as often as you want"> 
                <label for="q3-1">as often as you want</label></li>
                <li><input id="q3-2" name="q3" type="radio" value="no more than once every 3 days"> 
                <label for="q3-2">no more than once every 3 days</label></li></ul>
            </td>
                          </tr>
#

ugh, formatting

#

I'll fix

hollow aurora
limber orchid
#

I've tried placing this in the css but no luck

fieldset.inlineLabels ul {list-style:none}
native tide
#

How is Python used for web devs

hollow aurora
#

can someone help me with WEBSOCKETS
to understand what is wrong here?

same code on nodejs working fine
but on py - no errors, no outputs, nothing
I need to connect via WS to another server and listen for events

from flask import Flask
import socketio
 
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "test"
 
 
sio = socketio.Client()
sio.connect('wss://socket.............')
 
@sio.on('connect')
def on_connect():
    print('I\'m connected!')
    sio.emit('add-user', {token: '.............', type: '.............'})
 
 
@sio.on('donation')
def on_message(data):
    print('donation')
    print(data)
austere apex
#

Hi

#

Can anyone help me adding product quantity

#

:((((

#

All is working good til that product quantity
im having issues i think in my views.py

meager anchor
#

@hollow aurora i'm pretty convinced you can't do that with synchronous code like that - you'll need to delegate the client to a separate thread or you will block your webserver

#

alternatively, use something like asyncio with starlette as web framework, you'll need to search for a async websocket library though

#

@austere apex we need way more context for that, see

#

!ask

lavish prismBOT
#
ask

Asking good questions will yield a much higher chance of a quick response:

โ€ข Don't ask to ask your question, just go ahead and tell us your problem.
โ€ข Try to solve the problem on your own first, we're not going to write code for you.
โ€ข Show us the code you've tried and any errors or unexpected results it's giving
โ€ข Keep your patience while we're helping you.

You can find a much more detailed explanation on our website.

native tide
#

But I'm pretty shit at CSS

vagrant adder
#

@native tide

#

try using <center>somehting</center>

#

you can also put divs and whatever you want inside center tag

native tide
#

Somehow did not receive a notification even though you mentioned me... got to check my settings.

#

Thanks, it really was that easy.

vagrant adder
#

np

north swift
#

isnt that deprecated?

vagrant adder
#

nope

shrewd sand
#

@native tide use flexbox.

#

It fixes most centering issues.

limber orchid
#

is there some special trick to linking a css stylesheet when running your site locally?

#

it's in the same directory as the flask app .py

#

I've tried for the href values: style.css and http://127.0.0.1:5000/templates/style.css

#

and without the port, too

native tide
#

can you put it on git?

limber orchid
#

which part do you want to see?

#

so like, if I reference an online .css file, it does work

#

it's just local ones that are not

native tide
#

did you try making an "Assets" folder and just routing it?

#

and later referencing everything such as href = "./Assets/filename.extension"

limber orchid
#

I've tried giving it the full path from C:/

native tide
#

thats always a bad idea lol, keep all your paths relative

limber orchid
#

yeah well we all do desperate things when trying to debug

limber orchid
#

hmm this seems like more work than necessary just to do my local testing. I have it working on pythonanywhere using the static file stuff, but am just doing local running to test it

#

I'll just upload the .css to a website and reference it with http

native tide
#

you do you

limber orchid
#

but thanks

native tide
#

try to cut external frameworks/platforms to a minimum if you're just starting out

limber orchid
#

what do you mean?

native tide
#

Algum mago do R ai?

hardy bridge
#

in django

hushed burrow
#

is there any meaning to setting DEBUG = True in a flask configuration if flask uses environment variables at initialization to determine the environment? the config won't do anything since the application would've already been running in a production environment

vagrant adder
#

@limber orchid
Make folder called static

#

And link it from there

austere apex
#

Can someone help me with my thesis project, adding product quantity. Using teamviewer app. Im willing to give. Im really sorry im just so desperate

hardy bridge
#

@austere apex, you could try codementor.io for help if you're willing to pay for it

stable shadow
#

Guys i am new to REST APIs. I am exercising and i am confused. There are many ways to do things. For example lets say i have Library object which has child object Book, when i make POST request should i add the Book objects as well or should i make separate url for adding Book objects to the Library?

timid arrow
#

you would usually go for a separate resource for books in this case, to keep api simple. That will allow you add/delete/modify books without modifying Library itself.

stable shadow
#

@timid arrow ๐Ÿ‘

long zinc
#

Has anyone had trouble getting gitlab to load static assets (CSS) for a gitlab pages?

#

It works on my laptop, I push it to gitlab pages and it doesn't work.

limber orchid
#

regarding WTForms, for anyone familiar, I'm using them for a multiple choice quiz and would like to have the ability, when the user gets one wrong, to reload the page and show which were incorrect.

#

I feel like there's gotta be a way to do this, but can't find in the docs how to get it to return which fields failed their validations.

vagrant adder
#

@limber orchid
Can you provide what you've done till now?

limber orchid
#

yes, so its a standard WTForms class using one StringField() object and several RadioField() objects (I will post an example in a sec, opening my IDE now)

#

and then I'm using the 'validate on submit' method in my flask app to decide what to do.

#

I wish I could just find a nice list of all the methods and what they do but these particular docs I can't seem to ever find just like a nice cheat sheet of all the functionality...

#

this is the WTForms class

class Quiz(Form):

    def no_slashes(form, field):
        if '/' in field.data:
            raise ValidationError('Be sure that you are NOT including /u/ or u/ with your username.')

    name = StringField(u'username', validators=[input_required(), no_slashes])

    q1 = RadioField(
        "question 1 text?",
        choices=[
        ('option 1','option 1'),
        ('option 2','option 2'),
        ('all of the above','all of the above')
        ],
        validators=[CorrectAnswer('all of the above')]
        )
    submit = SubmitField("Submit")
#

this is the flask app

@app.route("/", methods=["GET", "POST"])
def quizlet():
    error = ''
    form = Quiz()
    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                reddit = bot_login()
                #reddit.subreddit('subreddit').contributor.add(reddit.redditor(form.name))
                print(form.name + 'approved assigned')
                return render_template('quiz_results.html', user_passed=True, approved_submitter=True, user=form.name)
            except:
                print('approved not assigned')
                return render_template('quiz_results.html',user_passed=True, approved_submitter=False)
        else:
            print('not approved not assigned')
            return render_template('quiz_results.html',user_passed=False, approved_submitter=False)

    return render_template('quiz.html', errors=error, form=form)
#

@vagrant adder

vagrant adder
#

Not home rn

native tide
#
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $('.dropdown-item').click(function(){
            var clickBtnText = $(this).text();
            var clickBtnId = $(this).attr('id');
            var ajaxurl = 'ajax.php',
            data =  {'id': clickBtnId, 'text': clickBtnText};
            $.post(ajaxurl, data, function (response) {
                alert("Doing stuff...");
            });
        });
    });
    </script>```
#

Do you guys see any error here?

#

my ajax.php php <?php echo "<script type='text/javascript'>alert('shit');</script>"; ?> doesn't do anything, or so it seems

#

But alert("Doing stuff..."); is run

outer lynx
#

More of a #python-web-dev I think

#

Although it seems just a js question

#

lemme see

north swift
#

I'm having an issue with font awesome when loaded locally

#

thing is, only the datatable sort icons arent working

sweet wharf
#

I am creating a portfolio website with Django and I want to create a contact form. What is the best way to store the data of a contact form. Should I store it in the database or should I make a mail message??

north swift
#

that's on you honestly, if you setup a portfolio and want someone to contact you, will you check your email or that database?

fringe fog
#

anyone using FastAPI? it looks pretty great

sweet wharf
#

Anyone used the function send_mail() in django to send confirmation mails?? I am trying it with the gmail mail server but I cant figure it out I tested SSL and TLS and this is my error (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError f13sm1232182ejj.7 - gsmtp', '=?utf-8?q?Paul?=')

vagrant adder
#

you aren't specifying email and password for the sender somewhere in the code

sweet wharf
#

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'paulogameplays12@gmail.com'
EMAIL_HOST_PASS = '*********'
EMAIL_PORT = '587'
EMAIL_USE_SSL = False
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#

this is my views.py

def mainview(request):
    all_projects = Projects.objects.all()
    if request.method == 'POST':
        messagecontainer = request.POST['name']

        host_mail = settings.EMAIL_HOST_USER

        send_mail('Contact Form', host_mail, messagecontainer,
                  ['paulaldabaghwork@gmail.com'], fail_silently=False)
    return render(request, 'portfolio/index.html', {
        'all_items': all_projects
    })
#

I tried changing my password, using SSL instead of TLS, using only plain strings, turning on lesser apps and different emails

grand badge
#

@sweet wharf gmail is a bit security paranoid i think

#

i think there is a setting that you have to change on your gmail account

tulip meadow
#

hello guys i am working on a school ERP and i want to add a feature in this project which is when admin add a new student a message will send to user on there email and sms so how can i add this any idea ?

unborn terrace
#

How would you define a "global" object to be used within each Django or Celery process? In my case I want to define a ConnectionPool for redis. I do not really know where I should define it to be clean ๐Ÿค” (I cannot use django-redis)

dark geyser
#

@sweet wharf if send_mail isn't working try EmailMessage method

north swift
#

will flask be able to take a somewhat big pandas dataframe?

shrewd sand
#

@sweet wharf @grand badge I find to get Gmail to work, you need to have 2FA and app- specific passwords.

#

Otherwise, it will not allow you to use it.

#

Its their attempt to stop spoofers using Gmail

prisma glacier
#

If I were to write a website writer in python, what other languages would I need to learn for that? I heard css and Linux was good but I'm not sure which ones to use

proper hinge
#

Html, css, javascript

#

Well I am actually not sure how much you could get away with on JS knowledge

#

But other two are essential

north swift
#

I stumbled upon this article not long ago

#

so apparently you can do a lot with no or minium javascript... if you are bored

prisma glacier
#

Awesome thank you

native tide
#

Hey guys.

#

any ideias to make it?

#

I have an API with django rest framework.
I want to display the users of the respective groups in the API.

north swift
#

to make what exactly?

native tide
#

I just want to display the users that are in their groups.

#

something like: users: [<users in the group>]

native tide
#

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    users = UserSerializer(many=True)
    class Meta:
        model = Group
        fields = ('url', 'name', 'users')

#

guys

#

i tried to make like that but

#

i got a : Group has no attribute users

#

AttributeError at /api/groups/ Got AttributeError when attempting to get a value for field userson serializerGroupSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Group instance. Original exception text was: 'Group' object has no attribute 'users'.

#

Maybe i have to overwrite the Group models?

austere apex
#
asd

#
asdas
#

Just tryin lol. sorry

#
class CartItem(models.Model):
    product     = models.ForeignKey(Product)
    quantity    = models.IntegerField(default=1)
    updated     = models.DateTimeField(auto_now=True)
    timestamp   = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.product.title


class Cart(models.Model):
    items       = models.ManyToManyField(CartItem, null=True, blank=True)
    user        = models.ForeignKey(User, null=True, blank=True)
    products    = models.ManyToManyField(Product, blank=True)
    subtotal    = models.DecimalField(default=0.00, max_digits=65, decimal_places=2)
    total       = models.DecimalField(default=0.00, max_digits=65, decimal_places=2)
    updated     = models.DateTimeField(auto_now=True)
    timestamp   = models.DateTimeField(auto_now_add=True)
#
def cart_update(request,slug):

    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id
    cart = Cart.objects.get(id=the_id)
    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        pass
    except:
        pass

    cart_item, created = CartItem.objects.get_or_created(product=product)
    if created:
        print("yeah")

    if not cart_item in cart.items.all():
        cart.items.add(cart_item)
    else:
        cart.products.remove(cart_item)

    new_total = 0.00
    for item in cart.items.all():
        line_total = float(item.product.price) * item.quantity
        new_total += new_total

    request.session['items_total'] = cart.items.count()
    cart.total = new_total
    cart.save()

    return HttpResponseRedirect(reverse("cart"))
#

Can i have some help with my qty

#

my html doesnt count the product default as one

#
{% if cart.items.exists %}
<table class="table cart-table">
  <thead>
    <tr>
      <th>#</th>
      <th>Product Name</th>
      <th>Product Price</th>
      <th>QTY</th>
    </tr>
  </thead>
  <tbody class='cart-body'>
    {% for item in cart.items.all %}
    <tr class='cart-product'>
      <th scope="row">{{ forloop.counter }}</th>
      <td><a href='{{ product.get_absolute_url }}'>{{ item.product.title }}</a> 

        {% include 'carts/snippets/remove-product.html' with product_id=product.id %}
      </td>
      <td>{{ item.product.price }}</td>
      <td>{{ item.quantity }}</td>
    </tr>
    {% endfor %}
meager anchor
#

@fringe fog fastapi is pretty nice. Iโ€˜ve rewritten one of our internal services to Starlette (from Flask) and that one turned out great, so I am now working on the next, which will use FastAPI. The Python types as schemas idea of pydantic is great

fringe fog
#

Cool, glad to hear it. Iโ€™m just digging into the docs now and it looks good.

If you donโ€™t mind my asking what are you doing for your data layer? Sqlalchemy is great but not async, I was looking at the databases package as an option. After reading issues and whatnot I see that pydamtic models are separate which seems a little laborious but probably fine (it looks like they are working on that)

#

@meager anchor ^

junior cloak
#

@fringe fog i currently use databases with sqlalchemy core with starlette. it is not ideal, and there's some minor issues, but it's been fine for the most part in a production setting. i don't do anything fancy with models -- i just have the db tables, my pydantic object schemas match what the table fields will be, and pass a dict of the pydanctic model to it

#

havent done too much with fastapi as somewhat ironically ive just finished a total move to graphql for this particular project but i use pydantic a lot and starlette

meager anchor
#

@fringe fog aioriak

fringe fog
#

Cool, thanks for the tips guys!

#

Iโ€™ll have to look up aioriak

#

Ahh i see riak is a nosql datastore

meager anchor
#

Yeah, for a hobby project Riak is probably a bit overkill, but it's really nice regardless :P

#

Asyncpg is also a great pick

deep narwhal
#

Wrong place sorry

limber orchid
#

I've got a flask app that's taking user input and generating an excel spreadsheet. How do I serve this to the user (one time) while not retaining a copy on the server?

vagrant adder
#

@limber orchid can we see the code?

limber orchid
#

it's openpyxl so the part that makes the xlsx is
book.save('weekly2019_anne.xlsx')

#

I haven't actually done anything in terms of the flask part because I honestly don't know where to start

#

my knowledge of flask goes as far as getting the form input and returning html templates

native tide
#

writing a user test case for django

#

if i'm not mistaken

#
from django.contrib.auth import SESSION_KEY
from django.test import TestCase, Client

class UserTest(TestCase):
    def setUp(self):
        self.credentials = {
            'username': 'testsuser',
            'password': 'testsuser'
        }
        self.client = Client()

        user = User.objects.create(username=self.credentials['username'])
        user.set_password(self.credentials['password'])
        user.save()
    def test_login(self):
        logged_in = self.client.login(**self.credentials)
        print(logged_in)
        self.assertTrue(logged_in)```
#

does this test register and login?

vagrant adder
#

so, you want to server some xlsx files and delete the file after serving it @limber orchid

#

@native tide sry but you are interrupting

#

might wanna take it to some #help channel

native tide
#

oh my fault man

limber orchid
#

yes, exactly

vagrant adder
#

can you show the code for the route where you want to server

#
@app.route("/something")
    def something():```
limber orchid
#

sorry, which part is that?

#

ah ok

#

it's the root

vagrant adder
limber orchid
#

flask_app.py yeah

#

right now it's local but I'll be running off pythonanywhere, if that makes a difference

vagrant adder
#

nah

#

can you send your code here

#

but don't show us the secret_key

limber orchid
#

sure, I'll show what I have but it's not finished obviously ๐Ÿค“

vagrant adder
#

doesn't matter

limber orchid
#

damn I think I need to do pastebin

#

another min, sorry

vagrant adder
#

i am going to bed in few mins hurry up

late gale
#

Can i use two frameworks and connect them to each other? like Angular and Django

vagrant adder
#

yes

late gale
#

Sorry but which is better for a blog either i choose Wordpress or make my website on my own and why

junior cloak
#

@late gale using one front end framework paired with one backend framework is almost always how you do things

native tide
#

Please if someone can refer me a good comprehensive beginner level course for django

#

I had developed webpages previously using php html css

#

I know basic of py

junior cloak
#

@native tide go through the official django tutorial

austere apex
#

Does anyone know how whats wrong with my code for quantity

#
def cart_update(request):

    cart_obj, new_obj = Cart.objects.new_or_get(request)
    entry_obj = Entry.objects.filter(cart=cart_obj)
    # product_id = request.POST.get('product_id')

    product_id = request.POST.get('product_id')
    quantity_input= request.POST.get('quantity-field')

    if product_id is not None:   

        try:
            product_obj = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            print("Show message to user, product is gone?")
            return redirect("cart:home")


        # cart_obj, new_obj = Cart.objects.new_or_get(request)
        Entry.objects.create(cart=cart_obj, product=product_obj, quantity=quantity_input)
        # Entry.objects.create(cart=cart_obj, product=product_obj, quantity=quantity_form)
        if product_obj in cart_obj.products.all():
            cart_obj.products.remove(product_obj)
            added = False
        else:
            cart_obj.products.add(product_obj) # cart_obj.products.add(product_id)
            added = True
        request.session['cart_items'] = cart_obj.products.count()


        # Entry.objects.create(cart=cart_obj, product=product_obj, quantity=quantity_input)
        # cart_obj.products.add(product_obj)            
        # added = True
        # request.session['cart_items'] = cart_obj.products.count()        
    return redirect("carts:home", {
        'cart': cart_obj,
        'entry': entry_obj,
        'some_var': some_value,  
    })
#

Cannot resolve keyword 'cart' into field. Choices are: eCart, eCart_id, id, product, product_id, quantity

rare oar
#

basically getting an error. I know I"m just approaching it wrong, but trying to StringAgg the qs from MatchEvents into the main match

slender knoll
#

@rare oar an error is very descriptive

rare oar
#

Hey my apologies, its in the dpaste

#

Full traceback here

#

any ideas @slender knoll ?

slender knoll
#

im looking

#

i never quite liked such dense code and it gives me a headache

rare oar
#

yeah I tried to nest it so its more readable

slender knoll
#

its complaining about line 21

#

which line is that in here

#

57 or 41

rare oar
#

I honestly don't know. Let me cancel my changes I've been experimenting and paste this origjnal back in here and see

slender knoll
#

ok

rare oar
#

to be honest it looks like it points to the delimiter parameter of StringAgg

slender knoll
#

wh

#

ngl django is meh lol

#

i cant see anything wrong, maybe my inexperience

#

sounds like a complicated query though

rare oar
#

here is the updated traceback

#

which line specifically were you saying?

slender knoll
#

21

rare oar
#

heh yeah thats the delimiter parameter

#

that is so weird

slender knoll
#

django's just weird lol

rare oar
#

its gotta be the aggregate function doing something I don't know about

#

StringAgg must be referencing it or something

slender knoll
#

maybe

#

tbh idk how django works but i sure as hell know that this is odd lol

rare oar
#

yeah its the aggregate function in general

#

ugh

slender knoll
#

oof

frigid egret
#

Hi all

#

Need some help with Django. I'm learning it by making a blog app. Following "Django 2 by example" book.

#
Internal Server Error: /blog/2019/5/19/post-3/
Traceback (most recent call last):
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vm/PycharmProjects/Example/mysite/blog/views.py", line 43, in post_detail
    comment_form = CommentForm()
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/forms/models.py", line 285, in __init__
    raise ValueError('ModelForm has no model class specified.')
ValueError: ModelForm has no model class specified.
#

This is the full error I'm getting

#

The file it refers to is views.py, i've made some changes to it to allow comments on posts

#

Here's the section I've made changes to.

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)

    comments = post.comments.filter(active=True)

    new_comment = None

    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
    else:
        comment_form = CommentForm()
    return render(request,
                  'blog/post/detail.html',
                  {'post': post,
                   'comments': comments,
                   'new_comment': new_comment,
                   'comment_form': comment_form})
#

If I get it right, the error is pointing at the line:

comment_form = CommentForm()

But frankly I don't understand what is wrong with it and how it is related to "ValueError: ModelForm has no model class specified."

frigid egret
#

can someone please help me?

vagrant adder
#

sure what's up

frigid egret
#

^

slender knoll
#

does the modelform meta have a model attribute

vagrant adder
#

@frigid egret i think you need to pass something as CommentForm()

#

can you post commentForm code?

frigid egret
#

1 sec

#

@slender knoll I have another form working fine. If that helps

#
class CommentForm(forms.ModelForm):
    class Meta:
        models = Comment
        fields = ('name', 'email', 'body')
slender knoll
#

model

#

not models

vagrant adder
#

that's it?

frigid egret
#

@slender knoll

class Comment(models.Model):
    post = models.ForeignKey(Post,
                             on_delete=models.CASCADE,
                             related_name='comments')
    name = models.CharField(max_length=250)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created',)

    def __str__(self):
        return 'Comment by {} on {}'.format(self.name, self.post)
#

Here's class comment

slender knoll
#

i gave you the fix

frigid egret
#

ok, sorry, I don't get it

#

ok, it doesn't

slender knoll
#

wait

frigid egret
#

at least, I don't see it

slender knoll
vagrant adder
#

white theme

#

ew

slender knoll
#

ยฏ_(ใƒ„)_/ยฏ

#

european

#

ew

frigid egret
#

"class BaseModelForm(BaseForm):" in models.py, right?

slender knoll
#

no

#

read your code

#

and read my comment

vagrant adder
#

try putting model=Comment

#

instead of models=Comment

#

@slender knoll don't be so harsh

#

some are new here

slender knoll
#

im not being harsh ? this is how i teach people at school

frigid egret
#

I don't get what "modelform meta" is.

#

it's clearly not something that's in the code i've posted.

slender knoll
#

it definitely is

#

CommentForm is a subclass of ModelForm

frigid egret
#

@vagrant adder which file is it?

slender knoll
#

class CommentForm means "define new class accessible by using CommentForm name"
(forms.ModelForm) means "base our new class on the ModelForm class"

#

and in there, there is another class, called Meta

vagrant adder
#
class Meta:
        ordering = ('created',)   #remove trailing ,
#

first

slender knoll
#

why remove , ?

#

that makes it a set

vagrant adder
#

string with what

#

string with null?

slender knoll
#

it has to be set or list iirc

vagrant adder
#
class CommentForm(forms.ModelForm):
    class Meta:
        models = Comment        #try putting model=Comment
        fields = ('name', 'email', 'body')
frigid egret
#

Oh, got it... almost

#

now I gotta read on what's the difference between model and models.

#

cause it is confusing me rn

slender knoll
#

models isn't a meta attribute

#

model is

frigid egret
#

Is this the relevant page in docs?

slender knoll
#

no

frigid egret
#

uh... where do I look then?

frigid egret
#

Thank you guys! ^_^

slender knoll
frigid egret
#

Hello guys!

vagrant adder
#

hello

frigid egret
#

I don't know if it's a weird request but still.

#

I'm learning Django via the book "Django 2 by example"

#

I have a case here when I understand what this particular code given by the book is doing but I can't quite grasp HOW it does that.

#

Can someone be so kind to explain it to me in detail?

vagrant adder
#

i don't know django sry man

#

i am learning flask

frigid egret
#

I could just skip through it cause it's working but I'd like to actually understand

#

I think it may be more related to Python in general rather than Django specifically

#

Can you take a look at least? @vagrant adder

vagrant adder
#

yeah i can try

frigid egret
#

Ok, so here's the code

    post_tags_ids = post.tags.values('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]
#

I have tags implemented and this next chapter is about filtering "associated" posts by looking at similar tags on other posts.

vagrant adder
#

what do you not understand

frigid egret
#

I don't quite understand how that last line works. I can see the result but it's not 100% clear to me how it's being achieved

vagrant adder
#

it just orders posts by given parameters

#

in this case these are 'same tags' and 'publish'

#

posts = Post.query.order_by(Post.date_posted.desc())
this is from my project^^

#

it orders posts by date posted

frigid egret
#

can't find what "annotate" does

frigid egret
#

Thanks. Google wound't give it to me somehow. Only gives a bunch of "data science" articles

native fractal
#

Hello all! Am currently working on a Django project but got stuck in trying to add a 'next' parameter to url after user signed in via django's own allauth.

The idea is this, user tries to perform an action on the site in a page say 127.0.0.1:8000/addimage but isn't yet logged in, will be directed to the login page(either google or facebook social sign in) upon clicking on the link. Am trying to append the page where the user was(/addimage) to the sign in link that will be sent to either facebook or google depending on user's method so that upon sign in completion, user will be redirected back to the old page, in this case /addimage

still talon
#

Hi, trying to place circles within a radius of a point without overlapping for my html5 canvas game. Are there any algorithms or design methods for this or other similar 'spawning' patterns? Thanks.

red spear
#

Guys, i will start working a migration of a Django 1.10 project to version 2, any tips on how to do it?!

grand badge
#

@red spear make a separate git branch that is django 2.x and make issues on everything that needs to get done so you dont get lost

safe rover
#

Hi, can i ask PHP questions here?

red spear
#

@grand badge that's actually pretty amazing, ty

#

If anyone has more tips about it, I would love to hear it yert yert

native tide
#

Hi guys, I'm trying to send an extra parameter (url) to my serializer but it tells me that the url field is not declared in the 'fields' option
Code: https://dpaste.de/Zz1z

#

I've seen it can be done with context, but i can't get to make it work

ancient zinc
#

is there a way to change the whole page on web ?
like on flask i have

@app.route("/")
def home():
    return render_template("test.html")
@app.route("/test")
def home1():
    return render_template("test1.html")```
can i do something to change the page from `test.html` to `test1.html` without changing the url
stone pelican
#

Can someone explain when websockets stop receiving frames? What's to stop an attacker from sending a variety of frames without the final code set? Is there a max amount of frames a websocket message can be made out of? I so what's that magic number?

north swift
#

is it possible to debug flask blueprint routes?

timid arrow
#

debug means what in this context?

reef rose
#

good morning - I want to make a simple web app that captures input from a single form and automatically does some io stuff with the data received on that form. is Flask good for this or would I be better off using a different library?

fast escarp
#

IMO Flask is perfect for your task @reef rose ๐Ÿ˜ƒ

patent cobalt
#

I agree, Flask sounds great for that

native tide
#

I have a question I want to ask

#

How can I fix the top padding of the ul to match the example given

#
<!DOCTYPE html>
<html>
<head>
    <title>Revision excrsise </title>
    <link rel="stylesheet" href="tutorial_1/lab_pratice.css">
</head>
<body>
    <h1>King of kongs</h1>
    <p id= "intro">I'm male, 89 years old, and am a giant, empire state building climbing ape</p>
    <hr>
    <img src="https://s3.amazonaws.com/codecademy-blog/assets/da840950.jpg" alt="Gorrila image">
    <hr>
    <ul>
        <li>interest</li>
        <ul class="center">
            <li>Bananas</li>
            <li>climbing stuff</li>
        </ul>
        <li>Jobs</li>
        <ol class="center">
            <li>giant ape</li>
            <li>web developer</li>
        </ol>
        <li>where i went to school</li>
        <ol class="center">
            <li>Diddy kong jr. High school</li>
            <li>Donkey kong Sr. high school</li>
        </ol>
        <li>favorite quotes</li>
        <ul class="center">
            <li>"at first you dont succeed climb a giant building"</li>  
            <li>"A Banana in hand is worth two on a tree"</li>  
        </ul>
    </ul>
</body>
</html>
#
hr{
    background-color: green;
    height: 20px ;
    width: 70%;
}

img{
    margin-left: auto;
    margin-right: auto;
    display: block;
    size: 400x300;
    border: 1px green;
    
}

h1{
    text-align: center;
}

#intro {
    text-align: center;
}


body{
    text-align: center;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
  

}

.padding-left-none{
    padding-left: 1em;
    text-align: center;
}

ul{
    list-style: none;
    display: inline;
}

ol{
    list-style: none;
    display: inline;
}





.center{
   padding-top: 0px;
   
}
fast escarp
#

hmm I am not quite sure what you need to do here. Which one is the example and which is your site and what exactly do you need to match? ๐Ÿ™‚

native tide
#

the padding between the ul and nested ul

fast escarp
#

ah you don't want additional space after "interest" for example?

reef rose
#

try ul.center { margin-bottom: 0; }

#

no that won't work

#

try changing your padding-top to margin-top in .center i think that'll do it

native tide
#

Canโ€™t seem to work

#

Is it because of the display: inline; ??

reef rose
#

it's actually because of left padding

#

.center { padding-left: 0; } fixes it

native tide
#

hmmmm still doesn't seem to work

fast escarp
#

hmmm are we sure that's the correct HTML part and you need just to fiddle the css?

#

@native tide what I mean is ... is this for some assignment or you're teaching yourself to HTML/CSS etc? The current way the lists are set is not great for accessing them with CSS. For example ul li will be applied for both levels and will mangle anything. I think there is a better way to write these, but I am not sure if that's what you need. ๐Ÿ™‚

native tide
#

mainly doing this for practice to understand the concepts

#

but it kind of bugging me

#

is there anything you could suggest on how to rewrite this

fast escarp
#

@native tide sorry I am at work, so I am answering slower I will have a look now

native tide
#

No worries

fast escarp
#

@native tide I would suggest don't go into two lists really, not needed at all in this.

       
        <ol>
        <li>Interest</li>
                <li>Bananas</li>
             <li>climbing stuff</li>
        </ol>       
        <ol>
        <li>Jobs</li>
        <li>giant ape</li>
        <li>web developer</li>
        </ol>
        <ol>
        <li>where i went to school</li>
        <li>Diddy kong jr. High school</li>
        <li>Donkey kong Sr. high school</li>
        </ol>
        <ol>
        <li>favorite quotes</li>
        <li>"at first you dont succeed climb a giant building"</li>  
        <li>"A Banana in hand is worth two on a tree"</li>  
        </ol>
native tide
#

Okay

fast escarp
#

I would also suggest to use

li:first-child {
  color: red;
}

this will change only the first element in all <li> elements so it will be easy for you to manipulate these

native tide
#

Thanks

#

Will try tomorrow as in my time zone itโ€™s almost midnight

red spear
#

Guys i've been doing a migration of Django 1 to 2 however when i try to run the project i'm getting this error below:

#
[INFO][2019-05-23 18:18:45,510][autoreload][29927][140178872248128]Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/xunjin/pyenv/python3cp/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/xunjin/pyenv/python3cp/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/home/xunjin/pyenv/python3cp/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
    raise _exception[0](_exception[1]).with_traceback(_exception[2])
TypeError: __init__() missing 1 required positional argument: 'code'
#

does anyone have an idea what it might be?!

late gale
#

Hi excuse me Does anyone know how to integrate Django with Angular

vagrant adder
#

sounds like google time

native tide
#

@late gale , do you need to integrate Django with Angular? you can treat them as two seperate projects

late gale
#

Ik but Django is so bad in templates so i want to integrate it with Angular

#

Django is so powerful in backend while angular is powerful in frontend

#

i want to mix them

#

but i cant understand from google

#

that's why i am asking here

#

do you know how @native tide

native tide
#

there's probably a way to integrate them into a one project, but, personally, I wouldn't do that

late gale
#

why so what're the cons

native tide
#

if you want tu use django as a backend and angular as a frontend - make your django a rest app

#

and consume it with angular

late gale
#

how

#

i am new in django

#

i only know basics

native tide
#

hmm

#

are you also new in angular?

late gale
#

typically yes

#

i want to integrate them then i gonna continue on learning both and updating the web app

native tide
#

typically? I'll assume you are new at angular. My advice: go through a decent Angular tutorial where you will, no doubt, learn about consuming rest apis

#

after that, go to django

#

where, instead of html, (default), you will have to return dictionaries

late gale
#

thank you

native tide
#

np, but ask if you have more questions, even if you think the questions are stupid

#

it's just that I think, you'll have a lot of problem if you tackle both at the same time

#

for Angular, I'd really recommend tutorials from Maximilian Schwarzmรผller

#

note: I haven't done any tutorials from him, but I've heard a lot of good things about his tutorials from multiple sources

late gale
#

Thank you

#

should i use angular or django for a blog

vagrant adder
#

Both

native tide
#

I'd say it depends what you want from it

#

if the goal is to learn, use both

#

but if you want to have a blog? use django

#

if the two tools are the only options

late gale
#

thanks

native tide
#

but if the goal isn't learning, there are better tools than django

late gale
#

nope i am not learning i want to make a professional blog and very responsive

native tide
#

if you don't want to learn prrogramming, I'd suggest looking at existing services

winged island
#

hi everyone

#

i need help with flask

#

im on windows 10 (yes, i know)

#

and am using VS Code

#

im following Cory Schafer's tutorial

#

but unfortunately, he uses MacOS

#

this is my code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello, world!"
#

the name of my file is flasktestapp.py

#

when i try to do set FLASK_APP=flasktestapp.py and then flask run, it doesn't work

#

what should i be doing?

#

somebody please help

#

somebody help please

#

anybody

#

SOMEBODY

#

ANYOBDOY

#

sigh

willow garnet
#

@winged island buddy, you have to be more patient. Everyone here is a volunteer. I invite you to ask your question in a help channel, that might get you a quicker response

winged island
#

yeah

#

im sorry

rare oar
#

hey harbar yeah the web scene here isn't as fast

#

by flask run I think you mean a command?

#

oh nm flask run is a console command

north swift
#

@timid arrow sorry I didnt notice your response, for example put a breakpoint on a route form post and check the object that I'm receiving, change its values, etc.

north swift
#

Maybe its me not understanding how flask works, I usually debug my .py scripts by running it on debug mode (I'm using spyder ide if that helps), doing that with flask just wont run the app.

vagrant adder
#

You can't debug flask apps with breakpoints

stray nexus
#

@winged island if still needed: to use flask run in a directory you need your main file to be in myapp/init.py and set the flask app to myapp.

north swift
#

@vagrant adder then what's the approach to debug stuff?

vagrant adder
#

use print statement

#

A lot

#

And i mean, A LOT

#

Since you can't just make a breakpoint, you need a lot of info to know what's happening

north swift
#

that's a bit and by bit I mean a lot underwhelming

vagrant adder
#

print or pprint will do the job

fast escarp
#

@north swift to add to saki's print statements ... sometimes it will crash and you will still be able to see the print statement but you should have to scroll through all of the crash dump, so make sure you're reading from the top down when checking for the print statement, if it's not there, it crashed before that, if it's there it will give you better idea where crashed. ๐Ÿ™‚

runic musk
#

any idea why the override threed.js doesn't seem to be getting used?

#

i tried dropping it to root and root/js

north swift
#

@fast escarp I mean, sure, but its the first time I dont get to play with the request data before sending the response

fast escarp
#

@north swift sure, I didn't mean it in a bad way, just helps overall whatever you're building. And if you're doing the front with JS for example alert and console.log are your best friends really. ๐Ÿ™‚

north swift
#

my issue is that I need to start a process on a post request and personally I dont think printing everything is a good way to find errors

fast escarp
#

hmmm why is that? what do you think it will be better approach?

north swift
#

just allow us to stop on the request part and debug normally as other languages?

#

I'm used to java (spring dev) and I can literally go step by step on everything and modify data on the go if I need it

fast escarp
#

I know, that would be great really

north swift
#

I'm actually used to do it on python overall too

#

I do 90% of my python work on a temp file loading stuff as I need

fast escarp
#

Yeah, but not always the best approach in Python

timid arrow
#

never had to run debugger with flask, but I think you still can do it, why not.

north swift
#

it just wont start the app

timid arrow
#

I mean, here is tutorial on how to set it up in VS code

#

so it's definitely can be done

north swift
#

guess I'll try that later but I dont really want to move away from spyder

timid arrow
#

I doesn't' matter which IDE to use

#

it's all about running flask app with specific command line args

#

and that is it

north swift
#

hmmm I wonder if that will be a problem since I use flask-socketio

#

will give it a try when I get some spare time, now I sadly must attend this meeting

rare oar
#

instead of print statements, use the logging module

#

I use the Django Debug Toolbar and it is super helpful

#

Also it does look like there is a flavor of the "Debug Toolbar" for Flask

solid cave
#

I'm trying to serve my flask application using uwsgi, I did the tutorial and got it working but now trying to get my actual flask app and running into road blocks because I have it configured as a package instead of running from a single file (I think thats the right terminology), in the pocoo docs for uwsgi it says to run something like this:

$ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app

but this doesn't seem to be working, I'm not sure why it says to use a sock here but I made one anyway, it keeps saying that my package name doesn't exist, i have been running it like this, but have tried different configs as well and nothing recognizes correctly:

uwsgi -s /tmp/flask_audit.sock --manage-script-name --mount /app/py_sox=flask_audit:app

I'm not sure what i'm doing wrong but it feels to me like i'm not even on the right track because this is nothing like the tutorial I followed

#

My app's index.py lives in /app/myapp/flask_audit and the root dir for the whole app is /app/myapp

#

I've been running it in development with flask run on a specific port but need to move it to a web server now

native tide
#

Hello

rugged pecan
#

waddup

native tide
#

I moved to django from php, i just used django template to display a table from database which has numbers in it, i want every column of that table to have sum total please anyone can guide. I searched all over but everything i find closes to that it can't be done in template i have to use filter or annote in views.py

#

Thanks

#

@rugged pecan please help me sir

rugged pecan
#

I cannot help, I apologise

native tide
#

@everyone

rugged pecan
#

hehe

native tide
#

Anyone please help

still briar
#

@native tide Could you show a snippet of your current views and template?

#

Since a sum wouldn't be in the database, you would have to calculate it first I'm views and then provide the data as an additional argument to your template while rendering.

native tide
#

This is very difficult i ha e tons of tables

#

I want to use like {{entries.amount.sum}}

#

Is there a way?

#

@still briar i solved it by using aggregate function but that is very time taking because i have like 1000 tables and this means i would be using aggregate 1000 times sepately in views

still briar
#

Usually if you want to pass that kind of data to your template, you would do it like ```py
sums = ...
return render(request, 'something.html', { 'sum': sums })

#

What does your view function in views.py look like?

native tide
#

Thanks to everyone i finally found a library

#

Django-tables2

#

@still briar I am talking about automation, thats what django is about, i create models and django automatically creates db, forms and tables now yay!

zealous igloo
#
urlpatterns = [
    path('admin/', admin.site.urls),
    path('chat/', include('chat.urls'))
]
#
urlpatterns = [
    url('<str:room_name>/', views.room, name='room'),
    url('', views.index, name='index'),
]
#

hi guys I am just going thru the django channels tutorial but it is written in django 1. something and i am currently using django 2.2 and I ran into some issues while trying to write the equivalent syntax

#

so the first urlconf is for my mainproject direcotry and teh second one is for an app. When i type in the url chat/someroomname shouldnt the views.room function be called? When I type chat/someroomname the views.index is called instead and I am confused as to why

still briar
#

It looks correct to me. Try going to chat/someroomname/ with a slash at the end.

#

Normally, an include could look like this, where you fetch the list from your app.

urlpatterns = [
    path('<page_slug>-<page_id>/', include([
        path('history/', views.history),
        path('edit/', views.edit),
        path('discuss/', views.discuss),
        path('permissions/', views.permissions),
    ])),
]
#

@zealous igloo

tacit barn
#

I do algorithm design in my day to day job (math degree, working in augmented reality), so I'm not much of a programmer.
Two years ago I took a short web dev course with Google App Engine using python and jinja, urllib2, webapp2.
Now I want to privately set up a small website from which users can make REST/RPC calls for crypto to an unrelated node. I want to stick to Google Web Engine and Python. The page itself will be minimal w.r.t. to storage required.
It should e.g. enable people to broadcast payments to the bitcoin network (web wallet).
The web engine is just to deploy that web page conventiently. It will have some light weigth interface
What's the options I can go for here? Is jinja serious enough for my demands?
I have some friends handling the network communication with Twisted/Klein. Is the suitable? But I also don't see people on the web using it. Does something like Flask do all things at once? What's other options.

zealous igloo
#

@still briar sorry yeah i tried that thing and it doesnt work the views.index is caled rather than views.room when i do chat/someroomname/

native tide
#

Can you become a web developer without learning JavaScript

steel tiger
#

Not a great idea and you will learn it in industry anyways

#

I have not done js as my projects have never needed to be reponsive

still briar
#

You could become a backend developer and work with Python!

#

It's of course good to know javascript, but you don't have to be proficient. Nowadays it's all about frontend frameworks anyhow.

barren path
#

Hi all :)
I know Flask, HTML, CSS, Sass.
Anyone have any project ideas for me?

zealous igloo
#

A search engine

frigid egret
#

Hi all

#

I have a problem implementing sitemap on my practice project

#

Am following the docs but apparently I'm missing something

#

Also there's something weird going on in urls.py

#

Here's the error that I've got:

#
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute
    self.check()
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
    issues.extend(super()._run_checks(**kwargs))
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
#
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check
    for pattern in self.url_patterns:
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 579, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/vm/PycharmProjects/Example/mysite/mysite/urls.py", line 25, in <module>
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
NameError: name 'sitemaps' is not defined
#

And the weird part in urls.py is that PyCharm highlights parts of code that seem to be totally fine.

#

can someone help me with this please?

waxen cedar
#

hey guys
i really need help right now
so i created a website and bought a domain name on GoDaddy website
but i have no idea how to link my code to the website
i would really love to be helped right now

jade egret
#

@frigid egret your not using that import anyway? and you have an s there is that supposed to be something else

frigid egret
#

Well yes except docs say that it has to be "sitemaps" specifically

#

If i try to change it to "sitemap" it doesn't render the page

waxen cedar
#

can somone help me ?

frigid egret
#

@waxen cedar Which guides have you tried following?

waxen cedar
#

i did search on yt and reddit

#

but i got confused

#

and i couldnt do anything

frigid egret
#

@jade egret If you look at the docs, you'll see that I'm trying to do it exactly as in the example. And it seem to be simple enough.

jade egret
#

can you post a link, so im looking at the same thing

waxen cedar
#

can someoen help me ?

frigid egret
#

@waxen cedar be patient please

waxen cedar
#

okay

jade egret
#
The sitemap view takes an extra, required argument:ย {'sitemaps':ย sitemaps}.sitemapsย should be a dictionary that maps a short section label (e.g.,ย blogย orย news) to itsย Sitemapย class (e.g.,ย BlogSitemapย orย NewsSitemap). It may also map to anย instanceย of aย Sitemapย class (e.g.,ย BlogSitemap(some_var)).```
I'd say that would suggest you can put your PostSitemap there
frigid egret
#

Yes, and I did that, didn't I?

#

It may have something to do with my project structure. Because it says "unresolved reference sitemaps" when I hover over it

jade egret
#

if you look further down you'll see examples.

@waxen cedar maybe try their website builder just to have the structure to look at, it seems you use ftp to add your webstuff

frigid egret
#

If I change path to "mysite.blog.sitemaps" there's no error but it fails to render the page

#

Yes, and I'm doing it just like in the example.

#

This is why I'm saying it might have something to do with the structure

waxen cedar
#

oh god i dont have that much knowledge with web @jade egret

#

my website is online but idk how to add my script to it

frigid egret
#

Because I know it's not set up exactly the same way as suggested by docs, it's because of how PyCharm community edition handles django projects

jade egret
#

have you changed it since? your sitemaps above is undefined, its not in the examples

#

how is it hosted atm? its running on gd?

waxen cedar
#

i dont know any of those

#

i just know that i signed up on GoDaddy

#

and bought a domain

#

thats the link

#

i just dont know how to put that script inside of the page

jade egret
#

what script?

waxen cedar
#

so i created the website right ?

#

and i dont know how to give it a domain

frigid egret
#

@waxen cedar are you trying to host it directly from your machine?

waxen cedar
#

yes

#

idk how to do that

frigid egret
#

You'll have to install a web server to do that. Like Apache for example

waxen cedar
#

okay but idk how to use Apache

frigid egret
#

try googling apache web server setup

waxen cedar
#

okay

#

thanks

frigid egret
#

There's no simple answer to "how to use apache" I'm afraid. That's a complicated topic

waxen cedar
#

okay

frigid egret
#

@jade egret can we go through it step by step cause I don't quite get what you mean

jade egret
#

there sitemaps is a defined dict, one above its a sitemap instance

frigid egret
#

Ok but I don't want it to use static views only

#

I'd like it to generate the sitemap based on existing article pages.

#

This code given as initiation example should be working fine if I get it right:

#
from django.contrib.sitemaps.views import sitemap

path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
     name='django.contrib.sitemaps.views.sitemap')
#

Given that I've added sitemaps to my installed_apps

#

Am I getting it right?

#

Cause that seem to be the problematic part

jade egret
#

try {"sitemaps": {"post": PostSitemap}}

frigid egret
#
    path('sitemap.xml', sitemap, {"sitemaps": {"post": PostSiteMap}},
NameError: name 'PostSiteMap' is not defined
jade egret
#

small m by bad

frigid egret
#

Oh right

#

Ok, it works. Thank you ๐Ÿ˜ƒ

#

So it takes PostSitemap class and gets all items from it as separate entries, right?

jade egret
#

havent a clue tbh, ive tried wrapping my head round django before and just couldnt do it, but yea it would seem to be making instances of that class as & when, not sure where that "post" label will come into play/be used

frigid egret
#

Hahah. Thank you anyway. It works now ๐Ÿ˜ƒ

waxen cedar
#

hey im back

#

i did apache and also ngrok

#

but how do i see my website now ?

#

nvm

#

i saw

#

it

#

just a weird freacking url

#

can I change it ?

jade egret
languid roost
#

Hey guys im in need of a backend web dev for a site i want to make. Dm me for more info! ๐Ÿ˜„

native tide
#

Django or Flask

#

Which should I learn

vagrant adder
#

i had the same question

#

and someone said learn flask if you are getting into web dev

native tide
#

But why

vagrant adder
#

it is easier to understand and solve problems

native tide
#

Django site looks more professional than flasks

vagrant adder
#

try googling it and see what fits your needs

#

it is not about what looks more professional

native tide
#

Which is better though

vagrant adder
#

imo flask is better

#

so you can understand the concepts of web dev

native tide
#

all the comments on that

#

says django is better

mint shuttle
#

going through the django official tutorial and: ```py

Lookup by a primary key is the most common case, so Django provides a

shortcut for primary-key exact lookups.

The following is identical to Question.objects.get(id=1).

Question.objects.get(pk=1)```
How is this a shortcut?

proper hinge
#

In this case it isn't but if the model's PK field had a longer name then it would be

mint shuttle
#

ah ok

#

ty!

pale fiber
#

Hello all, I create my first project, and i have some trouble with Django.
I need create URL path, generated of more one Slug:

urls.py in applications

from django.urls import path
from . import views

urlpatterns = [
    path('<category_slug>/<subcategory_slug>/', views.subcat_slug, name='subcategory'),
    path('<category_slug>/', views.category, name='category'),
]```
#

But I get no URL's combinations I need
I need to have URL's <subcategory_slug> that are included with the composition available on the way <category_slug>, and it turns out that all subcategories are available with any combination of categories

#
models.py 

class ProductCategory(models.Model):
    category = models.CharField(unique=True, max_length=30, blank=None, null=False, default=None)
    is_active = models.BooleanField(default=True)
    slug = models.SlugField(unique=None, blank=None, default='')

class ProductSubCategory(models.Model):
    subcategory = models.CharField(unique=True, max_length=30, blank=True, null=True, default=None)
    category = models.ForeignKey(ProductCategory, max_length=30, blank=None, null=False, default=None, on_delete=models.PROTECT)
    is_active = models.BooleanField(default=True)
    slug = models.SlugField(unique=None, blank=None, default='')```
#
views.py

def category(request, category_slug):
    category_slug = get_object_or_404(ProductCategory, slug=category_slug)
    return render(request, 'products/category.html', locals())

def subcat_slug(request, subcategory_slug, category_slug):
    subcats_slugs = get_object_or_404(ProductSubCategory, slug=subcategory_slug)
    cats_slugs = get_object_or_404(ProductCategory, slug=category_slug)
    return render(request, 'products/subcategory.html', locals())```
still briar
#

@pale fiber You forgot to check if the category is the subcategory's category.

#

It current fetches subcats_slugs and cats_slugs. Try checking subcats_slugs.category == cats_slugs

pale fiber
#

@still briar
Oh, thank you very much.
I check it before return function, and it all worked.
I am very grateful to you.

still briar
#

๐Ÿ‘

#

Make sure to return a 404 if the check fails.

pale fiber
#

I make this. Thanks for your rectification, otherwise 500 error would come out, I did not know about it.
I think this need make all render function's?

still briar
#

Not sure what you mean.

#

There's a 404 error you can import and raise in your view function, in case you want to keep things consistent.

frigid egret
#

Hi all
I have a problem with PostgreSQL.
can't create a database because user fails authentication.

#

All threads on SO with similar problem are about already having both user and database. Which doesn't work for me because I only have a user.

#
postgres@ubuntu:/home/vm$ createdb -E utf8 -U blog
createdb: could not connect to database template1: FATAL:  Peer authentication failed for user "blog"
vagrant adder
#

did you create your user?

frigid egret
#

Yes, I have a user

vagrant adder
#

also, try -u

frigid egret
#

I even created a second one just to be certain it worked

vagrant adder
#

try -u instead of -U

frigid egret
#

low case -u ?

#

ok

vagrant adder
#

yes

frigid egret
#

same result. "help" section also says it's high case -U

vagrant adder
#

hmm

#

what version of pg you using

#

yo sleeping insect

frigid egret
#

2.7.4

vagrant adder
#

exit postgres

#

then make db

frigid egret
#

like that?

vm@ubuntu:~$ createdb -E utf8 -U blog blog
createdb: could not connect to database template1: FATAL:  Peer authentication failed for user "blog"
vagrant adder
#

hm

#

try googling

frigid egret
#

Yea, tried

#

It results in a bunch of SO threads

#

And they are all about already having user and db. There are some fixes for that but I can't use them cause I don't have any db files to allow access to the user.

#

Like this one.

#

Also, somehow this is the only page I could find where someone has exactly the same problem. But it's really weird cause somehow it's on poker forums Oo

vagrant adder
#

hmm

frigid egret
#

...and there's no answer there, ofcourse

vagrant adder
#

try reinstalling postgres

frigid egret
#

reinstalling it

#

Same error =/

#

also I had to create user twice this time...

#
root@ubuntu:~# su postgres
postgres@ubuntu:/root$ createuser -dP blog
could not change directory to "/root": Permission denied
Enter password for new role: 
Enter it again: 
postgres@ubuntu:/root$ createuser -dP blog
could not change directory to "/root": Permission denied
Enter password for new role: 
Enter it again: 
createuser: creation of new role failed: ERROR:  role "blog" already exists
postgres@ubuntu:/root$ createdb -E utf8 -U blog blog
could not change directory to "/root": Permission denied
createdb: could not connect to database template1: FATAL:  Peer authentication failed for user "blog"
postgres@ubuntu:/root$ 
frigid egret
#

can someone help me with this please?

meager anchor
#

"could not change directory" is just a warning

#

the user was created only once

#

-U specifies the user to connect with, you likely wanted -O

#

see man createdb

inland gyro
#

what is everyone's opinion about deploying with azure?

floral seal
#

Hi, I'm new to JS and web development in general, I wanted to make a textarea that expands as the user types with jquery, this is what I've come up so far js $("textarea").on("keydown", function () { $(this).css("height", "inherit"); const height = parseInt($(this).css("border-top-width"), 10) + parseInt($(this).css("padding-top"), 10) + $(this).scrollHeight + parseInt($(this).css("padding-bottom"), 10) + parseInt($(this).css("border-bottom-width"), 10); $(this).css("height", `${height}px`); });, but it straight up doesn't do anything, any suggestions?

proper hinge
#

Can you provide a jsfiddle, codepen, something similar?

floral seal
#

mmh, sorry if this is a stupid question but what's jsfiddle and why would I need it?

proper hinge
#

It provides a minimal example and makes testing the JS easier

#

Cause you can put css, html, and js together on a page and then share a link with others

floral seal
#

mmh

#

alright

proper hinge
#

You weren't accessing scrollheight correctly

#

Use .prop("scrollHeight")

floral seal
#

Oh

#

thank you

zealous igloo
#

so i am tyring to build a webapp that uses websockets and I was wondering about something

#

so i saw that i can use websockets on the client side with javascritp but at the same time, django also lets u use websockets with an extention called django channels. to create an app that uses websockets, would i have to use teh websocket API in javascript and django channels?

honest flame
#

Does yarn have a feature wherein I can just store my node modules ( npm ) and fetch them if I'm offline -> the downloaded ones...
or it's built in npm ๐Ÿ˜ƒ there's a built in feature for that ?

#

so that I don't have to just to fetch modules from the internet, it's much faster

proper hinge
#

Maybe you can use the cache?

honest flame
#

what is that ?

proper hinge
#

Doesn't npm store downloaded modules in a cache?

#

Just like pip does

honest flame
#

idk

#

that's why I"m asking

#

I think arn has that feature , But i'm not sure

proper hinge
#

Well are you trying to use yarn or npm

honest flame
#

I'm referring on yarn

#

cause it's much newer than npm

proper hinge
#

Try this out

#

I believe you can set yarn's registry similar to how it's shown for npm here

honest flame
#

uhm,, how do you know if modules was properly installed in the directory with yarn ?

error D:\www\docs\node_modules\node-sass: Command failed.
because i got that```
#

how do you know if I installed thiese node-modules properly via yarn

loud mural
#

yo guys I get an Bad Gateway 502 error when trying to acces my website

#

I ran systemctl status nginx outpt is:

pi@web-server:~ $  systemctl status nginx.service 
โ— nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2019-05-28 17:53:15 CEST; 7min ago
     Docs: man:nginx(8)
  Process: 3556 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=1/FAILURE)
  Process: 3484 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; -s reload (code=exited, status=0/SUCCESS)
  Process: 3644 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 3641 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 3645 (nginx)
   CGroup: /system.slice/nginx.service
           โ”œโ”€3645 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           โ”œโ”€3646 nginx: worker process
           โ”œโ”€3647 nginx: worker process
           โ”œโ”€3648 nginx: worker process
           โ””โ”€3649 nginx: worker process

May 28 17:53:15 web-server systemd[1]: Starting A high performance web server and a reverse proxy server...
May 28 17:53:15 web-server systemd[1]: Started A high performance web server and a reverse proxy server.
#

my configfile in /etc/nginx/sites-enabled is:

server {
        listen 80;
        server_name test-host.ddnss.de;

        location /static {
                alias /home/pi/html/static;
        }

        location / {
                proxy_pass http://localhost:8000;
                include /etc/nginx/proxy_params;
                proxy_redirect off;
        }
}


#

nah nvm I apologize myself for that one, was just one god damm typo

wet ibex
#

I'm using django and trying to use apache + mod_wsgi (following django's docs + corey schafer's deployment tut), but it's always a gateway timeout when accessing the page (accessing the static files are ok)

looking at apache logs, it mentions about Py_Initialize module not found: encoding, which yields some results on google but none have worked so far for me

does anyone have any personal advice on this matter?

wet ibex
#

nevermind, apache2 + mod_wsgi can dig its own grave

#

nginx + uwsgi saved my day

native tide
#

Is there a way to catch Flask exiting with ctrl+c?

mild bridge
#

!ban @rapid magnet ping spam

lavish prismBOT
#

:ok_hand: permanently banned @rapid magnet (ping spam).

grand badge
#

Oh no

shut igloo
#

Raid? @mild bridge

mild bridge
#

seems like it

hazy stirrup
#

Anybody knows what IDE's can I use for jsp?

quiet solstice
#

vscode

#

It does a lot of things once you install the right extensions

kindred cosmos
#

Vim or emacs

vagrant adder
#

Atom for the win

hazy stirrup
#

I have hear of atom... I will try it... thanks

supple anvil
vagrant adder
#

try putting your id

#

i think you are not providing your id and you cannot login

supple anvil
#

you do heroku login in the console

#

i found out i need to do heroku create --buildpack https://github.com/heroku/heroku-buildpack-google-chrome.git but still wont work after i git push

vagrant adder
#

try git status

#

and send a screenshot

supple anvil
#

wait it did work, well half worked.
these are the buildpacks but when i print out the logs it says i dont have the right chromedriver directory, this is the directory i put in /app/.chromedriver/bin/chromedriver

vagrant adder
#

hm

supple anvil
#

made it work

vagrant adder
#

@supple anvil
How

supple anvil
#

I thought I can't put buildpacks here so after like 15 tries i decided to try it and it worked

rare oar
#

hey all weird issue with Django Debug Toolbar. The panels show, but the links don't work and the contents are printed below the page load. Any ideas?

native tide
#

Hey guys. I'm with a problem with django and rest framework.
I trying to make a relationship between users and group (default models in django) with rest framework.

#
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('url','username', 'email', 'groups')

class GroupSerializer(serializers.ModelSerializer):
    users = serializers.SlugRelatedField(many=True, read_only=True, slug_field='users')
    class Meta:
        model = Group
        fields = ('url','name', 'users')
#

but i'm getting a:
AttributeError at /api/groups/ 'Group' object has no attribute 'users'

rare oar
#

Hey all, given I want to use filter to go over a reverse object relation, I know that if I want to explicitly filter on AND, I would put them in a single filter expression... example filter(a__b__c=1, a__b__d=2). I know if I want to do AS WELL AS, I could chain the filter. My question is about making custom managers. If I wanted to do something like MyObject.ranked().current_season().stats() Where ranked and current_season are filters, and stats is some type of annotation, is there any patterns for the first case to make a call to filter that works in the first example? In this case I would want ranked AND current_season stats instead of ranked AS WELL as current_season stats. I'm just trying to find the right way to nicely represent it in a manager. Sorry if this is confusing.

supple anvil
#

Is there a way I can reload a Flask page if an error occurs? an Internal Server Error
Because my web app is acting weird, sometimes I get a NameError and when i reload the page 1-3 times I dont get the error anymore and cant figure out why so..

native tide
#

Hi

#

Anyone know how to reduce django response time

#

Its around 0.15 ms for a simple html page without any css or ja

#

In php i am getting around 0.05 ms

#

Any clues?

vagrant adder
#

That's python thing

zealous igloo
#

does anyone here have experience with basic electron? i am having trouble figuring out how to turn my super basic django website to an electorn desktop app

north swift
#

How would I connect to a remote mysql db through an sshtunnel?

#

I'm trying with the following:
!codeblock tunnel = sshtunnel.SSHTunnelForwarder(
(host, 22), ssh_username=ssh_user, ssh_password=ssh_pw,
remote_bind_address=(localhost, 3306))
tunnel.start()
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}:3306/{}'.format(db_user, db_pw, host, db)

#

but I'm getting the error:
OperationalError: (MySQLdb._exceptions.OperationalError) (1130, "Host 'my-ip' is not allowed to connect to this MySQL server")
(Background on this error at: http://sqlalche.me/e/e3q8)

open forum
#

!codeblock

lavish prismBOT
#
codeblock

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:

```python
print("Hello world!")
```

This will result in the following:

print("Hello world!")
open forum
#

Where do you set the "host" variable

#

?

north swift
#

a couple lines before

open forum
#

Show me

north swift
#

cant share that ip

#

its just an string with the remote ip

open forum
#

Ok, so what, did you replace it with the "my-ip" string in the error message?

north swift
#

yep

open forum
#

Ok then

north swift
#

Why would I post my public ip :p

open forum
#

I just wanted to make sure that you hadn't copy-pasted an example and forgot to replace the IP with your real one

north swift
#

so thing is, this connection is allowed and working (I'm connected with mysql front with the same parameters)

#

I'm going to check right now just to make sure no one did revoke privileges and I'm wasting time

#

yeah It's totally working

open forum
#

And when you connect with MySQL front, you do it from the same IP?

north swift
#

yeah

#

I'm trying to run the flask app from the same pc that's running MySQL front

north swift
#

Ok I think that's solved but its getting hardly stuck

#

I think it may be due to me trying to use the ORM mapping incorrectly typing... not sure

pseudo fjord
#

any async web devs here..?

#

having a real hard time finding the best way to debug async and await methods in my web application, doesn't seem like the good'ol PDB is working

native tide
#

Hi

#

Anyone know how to pass complex sql querys using django orm

#

Like distinct, inner join 4 to 5 tables

#

?

ancient zinc
#

how to disable Flask errors from coming to my page just in console

#

or auto redirect to /

swift trout
#

Anyone use hypothesis with django? What is the integration like these days? does it work ok?

kindred cosmos
#

Works great I justed go t hired to wirte a django application

vagrant adder
#

@ancient zinc
what do you mean by auto redirect to /

woeful sphinx
#

hi guys

#

i am having trouble with flask-sqlalchemy

#

i am trying to update a PickleType column

vagrant adder
#

try db.commit()

woeful sphinx
#

i have tried that, but still nothing. I will try one more time just to confirm it for you guys

#

thanks for the help !

vagrant adder
#

also, is product your variable with data from db or is it a model table name

woeful sphinx
#
CurrentPrices = db.Column('CurrentPrices', db.PickleType, default={})
#

@vagrant adder

vagrant adder
#

try db.add(product)

#

then db.commit()

woeful sphinx
#

It is already added to db

vagrant adder
#

after you change your price, try adding it to db

#

so you can insert your new price into database too

#

actually no

#

sorry

#

wrong docs

woeful sphinx
#

@vagrant adder Thanks for helping !

vagrant adder
#

does it work?

woeful sphinx
#

you mean db.session.add(CurrentProduct)

#

even though it has already been previousbly added

#

@vagrant adder

vagrant adder
#

hmm

#

just a sec

#

can you show how did you query your product

woeful sphinx
vagrant adder
#

don't use commit(db)

woeful sphinx
#

i have a custom function

vagrant adder
#

aaah

#

okay

woeful sphinx
#

; )

vagrant adder
#

lol

woeful sphinx
#

so it works everywhere else

#

but for soem reason i am not able to update this PickleType column

vagrant adder
#

maybe you should google

#

db.session.commit() should work

woeful sphinx
#

thanks for helping ! appreaciate it

#

@vagrant adder

vagrant adder
#

dude

#

try this

#

after you committed your data, try querying it again

#

commit(db)
then db.session.query() again

#

then print it

woeful sphinx
vagrant adder
#

oof

#

i give up

#

google time

ancient zinc
#

@vagrant adder
if page /persons/list has an coding error
and someone opened that page

#

intead off getting the error page

#

redirect to /