#web-development

2 messages · Page 30 of 1

native tide
tough star
#

I'm using bootstrap 4.
Why when I open this dropdown on mobile I get this:

<nav class="navbar navbar-light bg-light navbar-expand-lg fixed-top">
        <a class="navbar-brand" href="{{url_for('index')}}">
            <img src="{{url_for('static', filename='media/only_logo.png')}}" width="37" height="30" class="d-inline-block align-top">
            <span class="text" title="Torna alla home">Orari BEM</span>
        </a>
        <div class="navbar-nav ml-auto text-center">
            <div style="display: {{none if logged else block}}" class="nav-item">
                <div class="btn-group">
                    <a class="btn btn-secondary" role="button" href="{{url_for('login')}}"><i class="fab fa-google" style="position: relative;"></i> Login</a>
                    <button type="button" class="btn btn-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
                    <div class="dropdown-menu dropdown-menu-right bg-white">
                        <a class="dropdown-item text" href="{{url_for('help')}}"><i class="fas fa-question-circle"></i> Aiuto</a>
                        <div class="custom-control custom-switch dropdown-item" style="cursor: pointer; padding-left: 59px;">
                            <input type="checkbox" class="custom-control-input" id="darkSwitch" style="cursor: pointer;" />
                            <label class="custom-control-label text" for="darkSwitch" style="cursor: pointer;">Tema scuro</label>
                        </div>
                    </div>
                </div>
            </div>
</div>
tough star
native tide
#

Hello

#

How can I set a session variable at the start of the session?

#

Using Flask

flint breach
#

have you tried googling ?

native tide
#

Decided I could use app.before_first_request

desert thicket
#

Hmm. Looks like mixed opinion on Brython from this crowd.

frigid raft
#

If anyone has used markdownx for django, how do you get images to show?

final sparrow
#

Hey Folks,
I have a Django aggregation question: I'm trying to figure out how to return the latest child record of a parent entity.
I've Googled and read the docs best I can - I'm here as a last resort.
I've checked these SO questions:
https://stackoverflow.com/questions/15675672/get-the-latest-record-with-filter-in-django
https://stackoverflow.com/questions/17887075/django-orm-get-latest-record-for-group
https://stackoverflow.com/questions/30339490/how-to-use-meta-attribute-get-latest-by-properly-with-pk-in-django
With my limited understanding of Django I can't seem to decipher how to apply these concepts to my problem.
This is my view.py

from django.shortcuts import render

from rest_framework import generics
from .models import Installation, Status
from .serializers import InstallationSerializer, StatusSerializer

class ListInstallationsView(generics.ListAPIView):
    queryset = Installation.objects.all()
    serializer_class = InstallationSerializer

class CreateInstallationView(generics.CreateAPIView):
    serializer_class = InstallationSerializer

This is my serializer.py

from rest_framework import serializers
from .models import Installation, Status
from django.db.models import Avg, Count, Min, Sum, Max, Value

class StatusSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)
    installation_id = serializers.PrimaryKeyRelatedField(queryset=Installation.objects.all(),source='installation.id')

    class Meta:
        model = Status
        fields = ("id", "status", "notes", "date", "installation_id")

class InstallationSerializer(serializers.ModelSerializer):
    status = StatusSerializer(many=True)

    class Meta:
        model = Installation
        fields = ("customer_name", "address", "appointment_date", "date_created", "date_modified", "status")
#

This is my model:

from django.db import models
from django.utils import timezone

class Installation(models.Model):
    customer_name = models.CharField(max_length=64, null = False)
    address = models.TextField(null = False)
    appointment_date = models.DateTimeField(null = False)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "customer_name = {}, address = {}, appointment_date = {}, date_created = {}, date_modified = {}".format(self.customer_name, self.address, self.appointment_date, self.date_created, self.date_modified)
        
    class Meta:
        ordering = ('-appointment_date',)

    @property
    def status(self):
        return self.status_set.all()

class Status(models.Model):
    STATUS_CHOICES = [
        ('REQUESTED', 'Installation requested'),
        ('IN_PROGRESS', 'Installation in progress'),
        ('COMPLETED', 'Installation complete'),
        ('REJECTED', 'Installation rejected'),
    ]

    status = models.CharField(max_length = 16, choices = STATUS_CHOICES, default = 'REQUESTED', null = False)
    notes = models.TextField()
    date = models.DateTimeField(default = timezone.now)
    installation = models.ForeignKey(Installation, on_delete = models.CASCADE, null = False, related_name='status')
    
    def __str__(self):
        return "status : {},  notes : {}, date : {}, installation : {}".format(self.status, self.notes, self.date, self.installation)

    class Meta:
        ordering = ('-date',)
        get_latest_by = 'date'
#

What I get returned is this:

[
    {
        "customer_name": "Dono",
        "address": "XXX",
        "appointment_date": "2019-08-31T12:00:00Z",
        "date_created": "2019-08-22T20:58:09Z",
        "date_modified": "2019-08-22T20:58:09Z",
        "status": [
            {
                "id": 3,
                "status": "COMPLETED",
                "notes": "Another",
                "date": "2019-08-23T21:33:23Z",
                "installation_id": 2
            },
            {
                "id": 2,
                "status": "REQUESTED",
                "notes": "Test",
                "date": "2019-08-23T21:33:06Z",
                "installation_id": 2
            }
        ]
    }
]

So I'm trying to figure out how to cut the status result set down to just the latest status. Apologies for bombing this group with code dumps!

vagrant adder
#

since i don't work with django, i can't tell you what to type

#

but i think you have 2 options

#

you can query only last status and put that in json response

#

or

#

you can remove unwanted elements in list after querying

manic eagle
#

Hi there, is possible to get the full qualified URL on code without using request or site? I can get it in a template with get_absolute_url
but that doesn't includes the domain, is a relative address to the object, if you execute the same function to put in a text, I just get the relative URL
I need to generate a qr code from that absolute url, I can generate QRs but need the full qualified URL, any idea?

native tide
#

When using Python + Nginx + Gunicorn and SocketIO I get OSError: [Errno 9] Bad file descriptor as a error in my Supervisor log file

#

any reason as to why? I had previosuly fixed the problem with uninstalling and reinstalling gunicorn but that didnt work this time

#

I checked SO and Github but all I found were problems where the OP was closing the socket and trying to emit something then

#

I have SQLite in my Flask app if that makes a difference

late gale
#

Hey i have made an icon so it can change background color on click but the background color gets back when i go into another page can someone tell me how to do it

keen sphinx
#

@late gale use a cookie, it's what every website does for night mode

#

(you set a cookie with some value and then you read it and change what you need to change on the page)

native tide
#

anyone can help me with this?
i got data from api and send it to html but the html data doesnt render into html

#
json_data = url_api.json()
data = json_data["extract_html"]
patent cobalt
#

How do you "send" your data to the html?

#

It looks like a template language of some sort and things like the Django template engine will escape html by default to prevent injection

native tide
patent cobalt
#

Is this Django?

native tide
#

yess

patent cobalt
#

Right, by default, Django will escape html characters, but you can turn it off if you trust the data and actually want to insert it as actual html

#

One second

native tide
#

okay sir

patent cobalt
#

If this is a single variable that you want to mark as "safe", you can use the safe filter: <p>{{ data | safe }}</p> should do that

#

You can also designate blocks of the template that have the automatic escaping turned off or you can turn it off globally (probably not recommended)

native tide
#

Thanks sir! that worked

patent cobalt
native tide
#

okay, thank you very much

agile prawn
#

tbh i dont know where to type this but can someone teach me python

#

im kinda new and i want to learn to code .

vagrant adder
#

hello kritikal

#

there is a lot of resource on internet

#

youtube, books, podcasts...

#

!resources

lavish prismBOT
#
Resources

The Resources page on our website contains a list of hand-selected goodies that we regularly recommend to both beginners and experts.

native tide
#

hello guys
if i've made a little website, how do i put it on the internet?
how do i launch it
I just want to show my family really.
so i want to just give them the link

late gale
#

@keen sphinx oh thank you

rigid laurel
#

Well its quite involved to actually completely deploy a website depending on how exactly you have made it - I assume its Flask/Django @native tide ?

#

If so the easiest way is probably having a look at something like Digital Ocean for deploying a Flask App

#

Another option if you only want it to be temporary is to just use the built in web server - but that still requires something like a vps to host it on

keen sphinx
#

or maybe you just want to host it on your computer but make it available on the internet?

late gale
#

It's my first time to use cookies so does someone know how to set them on my website so whenever my icon is clicked it change the background color and keep it after refreshing

native tide
#

i just made it with html

#

like so:

#

<html>
<title>The website of Beefykenny</title>

<h1>Welcome to my Website! </h1>

<h2>Images </h2>

<p>In this article , an image is displayed
<br>This is the image: </p>
<img alt='Nissan Frontier' src="hqdefault.jpg"/>

<p>This is a Nissan Frontier<br>
The Future car of Angelo.
</p>

<h4>Denk ik </h4>

<h2>This is the link: </h2>
<p>If you want to know more about Nissan Truck, <a href="https://en.wikipedia.org/wiki/Nissan_Navara">Click Here</a></p>

</html>```
#

this is what i want to show

#

but i want to share the link

#

so that means posting this on the internet

#

to get a link

late gale
#
function checkCookie() {
  var color = getCookie("color");
  var color =["#521cd6","#ffa500","#907a53","#000040","#ffd700","#dc067e"];
  var i = 0;
  document.querySelector("li").addEventListener("click",function(){
    i=i < color.length ? ++i :0;

  if (color != "") {
    document.querySelector("body").style.background= color[i]
    } else {
      document.querySelector("body").style.background = url("../../../../static/blog/colors.jpg")
      if (colors != "" && colors != null) {
      setCookie("colors", colors, 365);
    }
  }
})}

I wanted to check if the user choosed a certain color it dont expire

#

Can someone help

#

Its my first time using cookies

rigid laurel
#

How is your Flask currently set up, using Jinja templates or more like a rest api?

late gale
#

I am using django

rigid laurel
#

same goes for there actually

#

I assume its using django templates right?

late gale
#

nope

rigid laurel
#

So a REST API?

#

what is being shown to the user?

#

response.set_cookie('my_cookie', 'my_cookie_value') # before returning the response

request.COOKIES.get('my_cookie') # getting the cookie when a new request comes in

late gale
#

What i mean is

#

Whenever the user clicks on the icon that changes the background color , It doesn't expire even after refreshing

rigid laurel
#

So unless you want to do a lot of JavaScript, the easiest way I think would be to set up a new Form/View that takes in an additional parameter of the colour, and have that set the cookie in the response

#

I think is the easiest way

hoary spruce
#

Okey I'm kind of getting lost right now. I'm using Flask, and I generated a page with inputs from a DB. But I want to have a button on my page, that takes the input from an input entry. And if the button is pressed, it runs a function. But without refresh or going away from the current page I'm at.

#

Is that possible?

rigid laurel
#

Its a problem that requires JS to solve

hoary spruce
#

So I found this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>

<div class='container'>
    <h3>Test</h3>
        <form>
            <input name="reason">
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>
@main.route('/background_process_test')
def background_process_test():
        print("hello")
        return "nothing"
#

And that worked

#

But when i try to get the input from reason:

@main.route('/background_process_test')
def background_process_test():
        reason = request.form['reason']
        print(reason)
        return "nothing"
#

It doesn't actually print

late gale
#
function checkCookie() {
  const possibleColors = new Set([
    "#521cd6",
    "#ffa500",
    "#907a53",
    "#000040",
    "#ffd700",
    "#dc067e",
  ]);
  const defaultBg = 'url("../../../../static/blog/colors.jpg")';
  var i = 0;
  i=i < possibleColors.length ? ++i :0;
  document.querySelector("body").style.background= possibleColors[i]
  document.getElementById("colorSwitch").addEventListener("click", function () {
    const color = getCookie("color");

    if (possibleColors.has(color)) {
      document.body.style.backgroundColor = color;
    } else {
      document.body.style.backgroundImage = defaultBg;
      setCookie("color", color, 365);
    }
  }, false);

The colors arent showing

#

@rigid laurel Do you know this

late gale
#
function setCookie(colors, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = colors + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(colors) {
  var name = colors + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
function checkCookie() {
  const possibleColors = new Set([
    "#521cd6",
    "#ffa500",
    "#907a53",
    "#000040",
    "#ffd700",
    "#dc067e",
  ]);
  const defaultBg = 'url("../../../../static/blog/colors.jpg")';
  var i = 0;
  i=i < possibleColors.length ? ++i :0;
  document.body.style.background= possibleColors[i]
  document.getElementById("colorSwitch").addEventListener("click", function () {
    const color = getCookie("color");

    if (possibleColors.has(color)) {
      document.body.style.backgroundColor = color;
    } else {
      document.body.style.backgroundImage = defaultBg;
      setCookie("color", color, 365);
    }
  }, false);
}
#

Here is my full code

#

and the background color doesnt change

#

Anyone?

frigid egret
#

I know that's a bit of off-topic but I don't really have anyone else to ask about this.

#

So, I'm using bootstrap on my website.

#

Trying to implement modal popups

#

Copy-pasting this code to one of my pages (I tried variations as well) and it refuses to work even though it works with my code in their test environment.

#

Can someone help me figure what I am missing please?

still briar
#

What exactly doesn't work? The modal doesn't appear when you click the launch button?

frigid egret
#

That's just weird, I've tested it on another machine in the same project and it works fine...

#

@still briar Exactly

still briar
#

Check what webbrowser you tried in and check the F12 console for any error messages.

frigid egret
#

Did that, no errors

still briar
#

Different webbrowsers?

frigid egret
#

Same behavior

still briar
#

But you said it works on another machine. Is that using a different webbrowser, or are you saying on your computer specifically it doesn't work in any browser?

#

In either case, it's hard to debug without your source code.

frigid egret
#

Yea, the source code is the one I linked. But nvm, I've got a friend figuring it out.

still briar
#

Oh, that snippet in particular isn't working? Thought you meant when you pasted it into your code.

round saddle
#

Hey. How can I connect my database with website with Python?

native tide
#

SQL?

rigid laurel
#

Flask + SQL

steel tiger
#

Flask = SQLAlchemy

gleaming herald
#

Does anyone know how to use same response in different post methods

#

using FASTAPI

steel tiger
#

To get the number of "followers" (for example) from sqlalchemy, would you pull back all the users followed and count the length of that list?

rose ginkgo
#

for database SQL only

steel tiger
#

Hm?

native tide
#

Hey guys
I'm doing a uni project , we have to build a web survey for our client . The problem is , nobody in the team has web Dev skills for front end. Backend is fine. What do you guys recommend we do?

junior cloak
#

@native tide not even html? honestly if nobody has the skills and the answer can't be "learn the skills" why not just use something like google forms, airtable, etc. to embed a survey? your backend folks can, if they want, use the apis from those services to still grab/do something with the survey results pragramatically if need be

native tide
#

@junior cloak unforunatly those apis are expensive! and not super automated

#

we will learn front end skills xD

surreal kayak
vagrant adder
#

python in web assembly? i think that's a thing already

#

i think its pydiode

near ridge
vagrant adder
#

yes

surreal kayak
#

He’s specifically looking to compile arbitrary code to a self contained wasm library. He explains in the video far better than I can in text (at least in this damned phone keyboard 😂)

brave otter
#

hey everyone - anyone in here who knows Django ever seen request.site append the text [default] to the site name when using it in a view? For some reason on my prod server request.site is coming back as mysite.com [default] instead of just mysite.com and it's messing up the success/cancel URLs for my payment system

#
protocol = request.scheme
site = request.site
success_location = reverse('checkout_success')
cancel_location = reverse('plans')

success_url = f'{protocol}://{site}{success_location}'
cancel_url = f'{protocol}://{site}{cancel_location}'
#

works fine on dev but on production it generates a URL like https://mysite.com [default]/plans/checkout/success/ which obviously is not right lol

brave otter
#

^ That's resolved. Turned out to be a setting in my wagtail site settings which was interfering w/ the default Django sites framework. I switched to using request.get_host() instead of request.site to get the hostname.

rigid laurel
#

I'm building a Flask web app with Flask/SQLAlchemy, I kinda wanna make something with Golang - is it reasonable to try and do my auth/user management there, or is it just gonna be impossible to get everything to talk to each other neatly?

junior cloak
#

@rigid laurel assuming you're handling auth in a sensible way, sure, if you want to. auth standards are pretty much universal, not unlike how your REST API made in python and one made in Go could be identical, compatible, etc etc.

#

another alternative, if users will mostly be using a browser or something, is to just... not worry much about it, and let firebase handle google auth or whatever social auth you may be interested in. (and then use the auth data from wherever you want)

#

if you're rolling some sort of session- or token-based system of your own (be careful) same thing -- nothing inherently incompatible unless you create a weird api for it

native tide
turbid fox
#

Anybody here familiar with django channels V2 and have time/ the desire to help me with a small project?

#

Im currently trying to embed matplotlib's webagg backend into django using django channels as the websocket.

#

Im having an error where the js side of the websocket doesn't seem to receive the messages. As a result, matplotlib doesn't draw anything.

#

AFAIK matplotlib comes with its own JS side of the websocket and should just be plug and play with the backend, but I'm new to django channels and websockets in general.

turbid fox
#

I think I've narrowed it down to a problem with async in the consumer.py

gleaming herald
#

I am getting this error

#

when running fastapi on linux

#

works fine on windows

junior cloak
#

@gleaming herald what do you get back when you run locale in your terminal? if py3 thinks you're in an ascii environment something bigger is misconfigured unrelated to python generally

gleaming herald
#

Okay NVM SOLVED IT

#

export LC_ALL=in_EN.utf-8
export LANG=in_EN.utf-8

#

Don't know what it does

#

but its working

junior cloak
#

yeah

gleaming herald
#

@junior cloak

junior cloak
#

so, that's going to go away later

gleaming herald
#

Thanks

junior cloak
#

that doesn't save those changes permanently

gleaming herald
#

in newer version

#

ohh

#

lol

#

everytime i need to do this

#

when I restart the server ?

junior cloak
#

what linux distro are you running

gleaming herald
#

@junior cloak

#
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"

junior cloak
#

try running localectl

gleaming herald
#
   System Locale: LANG=en_IN.UTF-8
       VC Keymap: in-eng
      X11 Layout: in
     X11 Variant: eng
#

i think because of export its changed

#

before it was C.UTF-8

junior cloak
#

hmm... that shouldve worked too but can be buggier. whatever

gleaming herald
#

Alright

#

If you find a permanent solution

#

ping me

junior cloak
#

so when you restart if it doesnt persist, do localectl set-locale [whatever locale]

#

are you in india?

gleaming herald
#

yeah

junior cloak
#

then yeah, localectl set-locale en_IN.UTF-8 should do it

gleaming herald
#

Thanks

#

It's because of your reasons

#

I am using FASTAPI

#

that too in production

#

Earlier we used to use flask

#

even though flask works well with nginx

junior cloak
#

yeah i used flask for years

gleaming herald
#

I tried FASTAPI anyways

junior cloak
#

flask is beautifully-designed but these days sync vs. async is a big deal

gleaming herald
#

little peculiar for doubt solving as the official docs is all we have

#

I don't know how to use async

#

maybe will dig it in later

#

I am using async obviously

#

but not the core functionalities

#

like the server which sends the request still waits for the response

#

and it takes time

#

one more doubt is there some kinda timeout for FASTAPI @junior cloak

#

Because sometime the response would take around 2 mins

#

Hope it handles well

junior cloak
#

uhhhh

#

what on earth is taking your api 2min to respond haha

#

not much should take longer than a second or two 😛

gleaming herald
#

I'm doing some processing depending on the input file

#

and the file I'm handling are more than 6GB

#

🤷

#

Any advice for such large files ?

junior cloak
#

is most of the time just spent dealing with the file upload, or with the client waiting while you process it?

#

(what sort of files are 6gb in size and what processing are you doing haha)

gleaming herald
#

client waiting while I process

#

you are not gonna belive

#

but it's csv files 🤣

#

uploading time is handled by the frontend team 😛

#

Apparently each file has around 20M Records . . .

junior cloak
#

in most situations, the API returns instantly with something like a job ID, and then contiues to process normally in the background. the client can make a request with the job ID to get the results later

#

this is assuming you're using just the REST API... if you have a webpage or something you can use websockets

gleaming herald
#

do you have a sample code

#

for things like this

#

I'm using REST API

#

Yes this would be best @junior cloak

#

JOBID thing

#

is there any webpage / sample_code/ youtube video

junior cloak
#

the concept isnt too difficult but implementing it varies. when you are doing this processing, are results saved to a database or anything like that? is the process being managed in any way, to see if it failed/succeeded, etc

#

or is it just... someone hits your API, you do a bunch of work right there in the endpoint handler, and then return it

gleaming herald
#

it's the latter

#

I load it to dataframe

#

do some processing

junior cloak
#

haha yeah that's what i was worried about

gleaming herald
#

it can't be done if it's latter ?

junior cloak
#

implementing this isnt hard but it could seem that way if you arent doing these other things

#

no it can, it just will seem like more work if you arent already doing things like storing job status somewhere for retrieval and whatnot

#

you just put it into a BackgroundTask object basically and your API will return and not block but do the work. convenient. however that doesnt help you if someone wants to retrieve the result later.

gleaming herald
#

lol

#

yeah

#

they could call my api in an async way

#

that would solve better

junior cloak
#

to do that, you need to create an ID for each job, store it somewhere, give it a status (like 'PENDING' or something), update that status from your background task based on how it goes (update it to 'SUCCESS' or 'FAILED' or something), and then have another API endpoint that expects the user to give you the task ID and have it pull that job result from wherever you've been keeping track of it

gleaming herald
#

whaaatttttt

#

okay reading it thrice I got some understanding

junior cloak
#

haha sorry

#

yeah this might be too complicated currently haha

#

async doesnt help you much here

gleaming herald
#

yeah

#

what kinda situation would it be useful

junior cloak
#

maybe for the moment you just keep the connection open and hope it doesnt disconnect 😛

gleaming herald
#

apart from chat apps

#

that's the only use case I could think of

#

lol

#

okay

junior cloak
#

are you using uvicorn?

gleaming herald
#

yes

junior cloak
#

then yeah it shouldnt be timing anything out inherently

gleaming herald
#

okay

#

thanks

#

you been of great help

#

💯

junior cloak
#

the API client might have its own timeout, depending on what you are using. a terminal one i use defaulted to 30s

#

but the others i use dont timeout by default. and i just tested waiting like 3min for a response from a starlette endpoint. not ideal but it's probably simplest for you currently 🙂

gleaming herald
#

Okay !

#

Thanks @junior cloak

#

Although since I am done with the basic version / working version

#

I would love to upgrade / optimize it

zealous igloo
#

so i have a site similar to kahoot where there is a quiz game and studnets playing on thier phone, with django channels, how can i make it so when a student submits an answer, a http request is sent to the server of the users answer and then how can i establish a websocket with the site that has the actual quiz and the server so that when the server receives an answer from a student, the server sends the answer to the quiz thing

gleaming herald
#

how do I run the fastapi thing infintely without command line with uvicorn

#

like for now i run it with uvicorn on comandline

#
uvicorn main:app --reload
#

and when the cmd stops

#

the server also

#

any other way to do

#

that will make it run independent of the cmd

unborn terrace
#

No, you'll have to run it at some point

#

Like every other web application

gleaming herald
#

so the cmd needs to be on

#

what if there is power failure

#

and server is done

#

how do I manage auto restart then

#

@unborn terrace

unborn terrace
#

Redundancy is a solution

#

Server's auto restart is managed by the server provider

#

(considering you configured a supervisor or something equivalent, or that it has been managed for you, to automatically restart the app on reboot)

gleaming herald
#

Alright

native root
#

screen is my goto for it, and you can do other things like hook it up to systemd

#

Others suggest tmux, basically they make sure your terminal session persists, but only systemd and similar will ensure that your application persists over restarts

surreal kayak
#

I use pm2 (a node site manager). It supports non-node apps quite well, and had handled my primary Flask based app well for over a year

#

It just calls gunicorn as the flask runner, but the management UI/cli is nice

late gale
#

Hey when someone contacts me on my website it sends the email but the from section is saying my email how to fix that
I gonna grab the codes here

#

Settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = os.environ.get('Email')

EMAIL_HOST_PASSWORD = os.environ.get('Pass')

Views.py

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)      
        if form.is_valid():
            subject = form.cleaned_data['Subject']
            from_email= form.cleaned_data['Email']
            message = form.cleaned_data['Message']
            recipient_list = [os.environ.get('Email')]
            try:
                send_mail(subject, message, from_email , recipient_list)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            messages.success(request, "Thank you!")

    form = ContactForm()

    return render(request, 'blog/contact.html', {'title': 'Contact', 'form':form})
junior cloak
#

@gleaming herald where do you plan on deploying FastAPI? a linux server, etc? if you'll be deploying to a linux vm somewhere setting up a systemd service is best and not particularly complicated. if you're using docker or something, this is different but also handled for you. or other various platforms. i still love using Heroku while in development because you can 'git push' your project and they do the rest and deal with failures, restarts, new versions, etc

junior cloak
#

this would work on your centos box as well as any linux server with systemd. just dropping that file into either /etc/systemd/system for the server itself or ~/.config/systemd/user/ to run it just for your user. it now be controlled by systemd and by default will start the app on startup, restart it if it dies, etc

zealous igloo
#
class instructorSerializer(serializers.Serializer):
    classes = classSerializer(many=True, required=False)
    class Meta:
        model = Instructor
        fields = (
            'id',
            'classes',
        )

class classSerializer(serializers.Serializer):
    instructor = instructorSerializer(many=False, required=True)
    students = studentSerializer(many=True, required=False)
    class Meta:
        model = Class
        fields = (
            'name',
            'instructor',
            'students',
        )
#

so this is django and on my second line i call a class serializer but that hasn't been defeind yet until several lines later, is there a way so that i can use the class serializer in my instructorSerializer method?

ruby palm
#

Hi

#

I got a question

#

This is more about design practices

#

I use classes in CSS and ids in Javascript

#

So you will see an <input class="checkbox-list" id="checkboxList" type="checkbox"> in my html document often

#

Is that a good practice?

#

Or you consider better to just do <input id="checkboxList" type="checkbox"> and use ids whether in js and css?

still briar
#

Ids allow you to specify which button to use in js. Without it, you'd either have to search for the button you want or generate it.

ruby palm
#

Yes I know

#

But what I actually mean is

#

Do you consider good to have both classes and ids in one element, to modify it through its class name in CSS and to modify it by its id in javascript? Or in that case do you consider better to just have an ID and work with it both in CSS and JS?

native tide
#

It could be confusing. To mix both id's and class.

#

But why would you have class and a id first of all? @ruby palm

keen sphinx
#

does anyone here have experience with MDL? specifically organizing grids

#

(Material Design Lite)

#

Nevermind, found the issue

steel tiger
#

Any way I could add CI to an api running to test it?

native root
#

Since ID's are unique, or at least using them non-uniquely leads to a large amount of problems, ID's should be used when you're intending to target a single, specific element. Classes are intended to be used across a variety of elements. If you're only targeting that one element with a class you should probably be using an ID, but if there is a case where you might want to target multiple you should be using classes.

vagrant adder
#

@steel tiger
Yes you can, travis ci is a good one

steel tiger
#

@vagrant adder That wasn't the question

vagrant adder
#

what do you mean CI to an api then

steel tiger
#

I have an api

#

I would like my CI to do automated tests

rigid laurel
#

You can use Travis to run unit tests as part of the build. As Saki said

vagrant adder
#

that's literally what i sad

#

CI's are made to run tests

#

you can use unittest or pytest to run and make tests

fallow fjord
#

My HTTPS server isn't working

It isn't set up to serve anything but it's not even detecting a connection

steel tiger
#

@vagrant adder @rigid laurel I have a flask api

#

I have a ci

#

How do I test the flask api using the ci

rigid laurel
#

I mean, this is pretty basic stuff that is mostly suited for following with a tutorial I've only used Jenkins myself, not Travis but this seems like a perfectly reasonable guide from Google - https://blog.travis-ci.com/2018-01-25-what-is-ci-part-2

Just write your tests and add a script

copper mica
#

Someone can tell me how to make my method repeat over and over once It redirect

#
@app.route("/rainbow")
def rainbow():
    rainbowFX(strip)
    return render_template('home.html')
#

and btw once I go to /rainbow it still loads while rainbowFX finish and then the url loads

steel tiger
#

🤦 @rigid laurel I know what a ci is..

#

I am asking how to test an api specifically

rigid laurel
#

well

#

You're clearly not doing a very good job of making yourself clear

steel tiger
#

How would you say it then

rigid laurel
#

clearly I don't know

#

becasue I don't know what the fuck you're asking

steel tiger
#

So you know what a restful api is, yes?

rigid laurel
#

you test APIs the same way you test most code

#

@steel tiger

steel tiger
#

Mostly the first one

#

Again, I know that a CI is

rigid laurel
#

again

#

what is your question?

#

Are you confused about how to run the unit tests?

steel tiger
#

What is the correct way to run a unit test on a Flask RESTful API that can be properly integrated into a CI platform. I know what a CI is and I know what a unit test is.

#

Would it look similar to this built-in requests-like feature of Flask/Werkzurg: py def test_main_page(self): response = self.app.get('/', follow_redirects=True) self.assertEqual(response.status_code, 200)

#

@rigid laurel

rigid laurel
#

You need to set up a client that executes the requests for you

#
def test_empty_db(client):
    """Start with a blank database."""

    rv = client.get('/')
    assert b'No entries here so far' in rv.data```
#

So they'd look like that

#
@pytest.fixture
def client():
    db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
    flaskr.app.config['TESTING'] = True

    with flaskr.app.test_client() as client:
        with flaskr.app.app_context():
            flaskr.init_db()
        yield client

    os.close(db_fd)
    os.unlink(flaskr.app.config['DATABASE'])```
steel tiger
#

You mean a test framework?

rigid laurel
#

Assuming you're using pytest you define a client that configures the app for you

steel tiger
#

Yes

rigid laurel
#

and then that client is what executes the requests as a fixture - the article I linked explains it better than I can I think

#
    with my_application.app.test_client() as client:
        with my_application.app.app_context():
            my_application.init_db()
        yield client
#

That is the important part of the above code snippet

native tide
#

im trying to make a site, as i am starting to sell my vpn i have made, and i want a site for my vpn to sell on. can someone help me make it

strong talon
#
@import url('https://fonts.googleapis.com/css?family=Arvo|Lexend+Deca|Montserrat|Open+Sans|Space+Mono&display=swap');

:root{
  --accent-hue: 335;
  --header-color: #00000000;
  --animation-length: 0.3s;
  --normal-text: #202020;
  --accent-color: hsl(var(--accent-hue), 75%, 60%);
}
*{
  box-sizing: border-box;
  font-family: "Open Sans";
}
.header {
  /* background-color: var(--accent-color); */
  width: 100vw;
  box-shadow: 0px 3px 6px var(--shadow-color);
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 3vw;
  position: fixed;
  font-size: 1.2rem;
}
.header a {
  margin-right: 1em;
}
.text-button{
  text-decoration: none;
  color: var(--normal-text);
  font-family: "Lexend Deca";
  /* font-weight: bold; */
}
.header .logo {
  font-family: 'Space Mono';
  user-select: none;
  font-size: 2rem;
  user-select: none;
  color: var(--accent-color);
}
#
<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'>
    <title>exciting</title>
    <link rel='stylesheet' href='{{ url_for("static", filename="css/style.css") }}'>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src='{{ url_for('static', filename='javascript/script.js') }}'></script>
  </head>
  <body>
    <div class='header'>
      <div>
        <a class='text-button logo' href='/'>owo</a>
        <a class='text-button' href='/link'>button</a>
      </div><div>
        <a class='text-button' href='/support'>other button</a>
        <a class='text-button' href='/login'>button too</a>
      </div>
    </div>
    <div class='content'>

    </div>
  </body>
</html>
#

i can't figure out how to get the things to line up?

#

looks like that right now

#

the left side is above by a bit

#

jsfiddle iguess

#

not actually sure how to do this

strong talon
#

the larger the text size the higher up the left side moves

#

for some reason if i make it stretch, it looks like this instead:

native root
#

Is your flex grid in row mode?

#

never mind

#

it's because of your "justify-content: flex-end"

#

If you take a look at the div's containing your two sets of buttons, you'll notice that the second one has space above it (probably)

#

You should pick "center" instead, for what you're looking for

keen sphinx
#

@CSS savy people: do you still discover new things in the language after a couple of years with it?

strong talon
#

Okay, I'll give that a go tomorrow

#

Thanks

native root
#

@keen sphinx yes, yes we do ;-;

#

@strong talon align-items: center, my bad. Tested it on your fiddle

#

Did you know that if you've got a 3d-render-spaced div, (via translateZ(0) or a perspective: application), and it's height is set to a floating point pixel value (via vw, for instance) in firefox there's a mismatch of round() vs floor() that results in single-pixel holes between the divs?

strong talon
#

What

keen sphinx
#

no, but I'm not CSS savy, so it doesn't surprise me

strong talon
#

I've seen the errors with sub pixel in CS s

#

Like if you have fifty 0.75 width five

keen sphinx
#

tbqh I'm a novice and my head can't predict how properties will interact with each other, and I don't know how to plan the HTML part too well

native root
#

I always tend to think in boxes that group things

keen sphinx
#

but it seems to me there aren't that many things to work with, it's just that there are many ways of using them and many possible goals

strong talon
#

Css is really strange to me

#

I'm like wow, I'll just use this property

#

It'll look so nice!

#

And then everythings of center

native root
#

It's a classic

#

Just remember, css comes from the era of IE6, and has not shaken off all of the related mess yet

strong talon
#

huh

#

different sized elements are kinda strange

strong talon
#

i think the main problem is thatthe owo isn't aligned to the bottom of the a tag

#

i reverted it back to flex-end

#

the owo is like

#

floating

#

is it a problem with the font?

#

yea its probably because there's an extra space below and the larger font size makes it wack

coral sorrel
#

whats the issue?

#

and do you think you can make a jsfiddle with the same setup?

strong talon
#

itsnot a super big issue but its off center

#

and if i have another link on the left side its really obvious

coral sorrel
#

which part isn't centre

strong talon
#

owo

#

oh thel ink is centered

#

right now

coral sorrel
#

hm

strong talon
#

but the owo isn't

#

because font i think

#

i don't think there's anything i can do

coral sorrel
#

is this vertically or horizontally centred

strong talon
#

vertically

#

tryna get everything vertically centered

coral sorrel
#

so you just want owo to line up with button's base, right

#

?

strong talon
#

yep

#

or center

coral sorrel
#

seems to be vertically matching

#

if the image isn't loading for you (because discord is having issues atm) then just open it externally

strong talon
#

ok

#

hm that's strange

#

in ur image it seems to line up but in mine it doesn't

#

this jsfiddle right?

coral sorrel
#

v6 isn't lining up now, no

#

the cause of this is

.header div {
  align-items: centre;
}
#

if you change align-items to baseline it'll realign to the base of the divs

strong talon
#

oh

#

changing both to baseline works

coral sorrel
#

sounds right

#

this is because align-items is important for anything using flex

#

if you don't use flex, the other method is to use line-height

#

but by default it should arrange to baseline and is only something people tend to play with when wanting to ensure consistent vertical centering

strong talon
#

default was stretch i think

#

ohhhh

#

i was using flex-end before

#

but baseline apparently adjusts for where the letters sit

strong talon
#

how come most sites put a ghost button/text button on log in or sign up and a fully filled button on sign up?

tame river
#

sooo i am trying to create a kind of proxy server and wanna forward stream request data as response

strong talon
#

is there a nicer solution to not having a gap because of the fixed width other than make a pseudo-bar?
my normal solution is to make another bar, except its completely transparent and position: relative

#

that way elements below are moved down the right amount

#

if i specify the height i can just put padding-top

#

but that might lead to issues as well

native root
#

Part of your issue is that your logo text, by virtue of being lowercase, is naturally offcenter

#

The gap issue's solution is position: sticky and position: -webkit-sticky

strong talon
#

oh, okay thanks

#

i remember there being a super complicated script for this before but i couldn't find it

#

maybe i'm not remembering this right

native root
#

There probably is a polyfill that's complicated

strong talon
#

ughhh

#

i just remembered that i even have to adjust everything for mobile adn stuff

#

yikes thats a pain

proper hinge
#

Is mobile first still a thing?

native tide
#

anyone familia with django?

patent cobalt
#

A bit, what do you want to know?

native tide
#

I have a django question- if you are having a rest API run side by side with a web application, is it proper convention to have the API its own "app" within the django project?

patent cobalt
#

Yes, I'd say so. In fact, it's not even the case that your entire web applications has to be one django "app"; sometimes it makes sense to split it up into logical modular parts.

native tide
#

ok, thanks for answering. its a bit to learn with django, but I'm enjoying it

#

I made a good sized app with flask, so that made the learning process for this a bit easier

patent cobalt
#

I'm still learning Django and it's a lot of fun. (I'm not a webdev, so all my Django projects are purely for fun.)

#

For our new Python Discord website, we use the Django REST API framework

#

It lives in its own app and on its own subdomain

native tide
#

I'm in the job hunting phase and I've read that django is valued quite a bit more than flask, hence my push towards learning it lol

#

oh very cool, I haven't seen the new site

patent cobalt
#

It's not up yet, we're still working on it

native tide
#

ah gotcha

patent cobalt
#

The api is for internal use, though. Our bot communicates with the database over the API.

native tide
#

ok. would you say learning to use oauth would be a valuable skill?

honest flame
#

Hello 🙂

native tide
#

good morning

honest flame
#
let days_in_array = this.marked_days.map(days => {
            return days === true;  
 });```
#

how do you return the indexes that are equal to false in this array for examle :

native tide
#

the help channels may be able to help you out better

balmy forge
#

js?

honest flame
#

this is web development

#

yep

balmy forge
#

map can return indexes as well, like enumerate

#

But not sure if it's the scope of this server

native tide
#

but to answer your question, you can just go through the loop, and if an item meets your criteria, you can add it to an empty list that you return at the end

#

ah I read it wrong, you want the index numbers. so you'd need a little more added to that

honest flame
#

yeah, like for that ones i need to push the ones into a new array

patent cobalt
#

@balmy forge We do help with technologies related to webdev in this channel (including js), but sometimes a server for general programming or js in specific just has more users that can help with such a question.

balmy forge
#

Thank you for the clarification

patent cobalt
#

(I don't know any js for instance)

balmy forge
#

If you look closer into .map() method

#
(method) Array<string>.map<void>(callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any): void[]```
#

A simple demonstration of how you use it is like this

#
const myList = ['a', 'b', 'c', 'd'];
myList.map((x, i) => console.log(i, x));
#

it'll outputjs 0 a 1 b 2 c 3 d

#

You can take it in and then return it in the map, so a better example you can use is like this

#
const myList = [1, 2, 3, 4, 5, 6];
console.log(myList.map((x, i) => [x % 3 === 0, i]).join('\n'));
#

You'll get thisjs false,0 false,1 true,2 false,3 false,4 true,5

#

Getting them is very easy via the use of .filter(), this time you also has the index from it

#

To expand the above example, here

#
const myList = [1, 2, 3, 4, 5, 6];
const results = myList.map((x, i) => [x % 3 === 0, i]);
const filtered = results.filter(([value, index]) => value);
console.log(filtered.join('\n'));
#

You'll get js true,2 true,5

#

Does that answer your question @honest flame

#

You can chain it alright

#
myList = [1, 2, 3, 4, 5, 6].map((x, i) => [x % 3 === 0, i]).filter(([value, index]) => value)```
honest flame
#

yep thanks

#

I will try to digest this comments

balmy forge
#

No worries, if you need help, don't hesitate to ask

#

Another way is to do index inside the filter

#

All of the code i posted are working codes, you can try running them as snippets

honest flame
#

yeah cool

mortal fern
#

Hello, I'm writing a simple personal website using Django to periodically send me Web Push notifications. I need to generate notifications periodically, my understanding is that normally things run periodically Django looks at tasks.py, or on a Linux server using CRON?

#

Searching leads me to packages such as Celery, but aren't supported on Windows which is what I'm working with

#

Should I be looking at a simple django scheduling package? or use something like Heroku's Scheduler since I plan to deploy on heroku?

vagrant adder
#

You are better off finding something related to django

#

Ideally, you want to have as similar environments as possible on your local dev machine and your production machine

mortal fern
#

ok that makes sense, thanks. I'll look for a Django task or scheduling package

hoary spruce
#

I'm kind of stuck I have a download button and I use this code using flask with it:

@securityApp.route('/download')
def download():
    return send_file(filename,
                    mimetype = "image/jpeg",
                    attachment_filename=FILENAME_WITHOUT_PATH,
                    as_attachment=True)
    ```
#

But it doesn't actually download it, but it turns me to this view

#

The file, is correct but yeh, it's not giving me a download option

vagrant adder
#

what is filename, and FILENAME_WITHOUT_PATH

hoary spruce
#

Variables that are the file path and filename

vagrant adder
#

i am betting problem is in those two variables

#

if it's not prompting you to download

hoary spruce
#

Filename is For example: ./static/images/apple.jpg

#

And FILENAME_WITHOUT_PATH: apple.jpg

vagrant adder
#

you should be using url_for() method for linking

hoary spruce
#

Instead of send_file()?

native root
#

Which as_attachment should be doing, presumably

vagrant adder
#

you need send_file()

native tide
#

is it at all possible to have a script outside of django still interface with the ORM? Django will be the user interface, and I'll have scraper using asyncio, as well as some added logic for alerting and some light analysis functions. both scripts would run at the same time, both of which reading and writing to the database. This is a bit beyond anything I've done before, and I don't know if this will require some frankenstein solution. thanks!

patent cobalt
#

It's probably best to expose an API to your other script from your Django back-end

#

You may associate that with external services, like the public APIs you're used to, but it basically means providing an interface for other applications, like your scraping script, to your Django application.

native tide
#

Thanks, that seems like a much cleaner approach to this.

open forum
#

Is ProtoRPC unsupported for GAE apps on the Python 3 runtime?

vagrant adder
#

excuse me what

patent cobalt
#

I don't know the answer, but ProtoRPC is Google'sl remote procedure calls protocol thing, GAE is Google App Engine

hoary spruce
#

@vagrant adder @native root Apperanly there was no problem, I decided to work again on it now. And it magicly works

#

¯_(ツ)_/¯

vagrant adder
#

Lmfao

#

😂 👍

rigid laurel
#
Things = Thing.query.filter_by(owner_id=g.user.id, is_public=True)``` Is there any way to use or in Flask SQLAlchemy neatly?
native tide
#

@rigid laurel what do you mean "neatly?"

rigid laurel
#

apparently you can do query(or_(Model.property == Val, Model.property2 == val2))

#

but I would just prefer to do two separate queries

native tide
#

I don't know if this answers your question but this might point you in the right direction,

#

but if you use filter instead of filter_by, you don't have to just use the object attributes

#

but you'd have to use database.session.query(TheObject).filter

#

so instead of attribute=4 for instance, you can have AnotherObject.attribute == value

#

as for having an or, I've read you can use a | in the parentheses, and a filter on each side

rigid laurel
#

Yeah, I think thats the solution I saw. I don't love it but I'll either go with that or just 2 queries

#

I was just hoping I was missing some obvious aspect of filter_by

native tide
#

what I did which probably isn't proper is just do two separate queries, and then add both lists into a set

#

I've only done one project utilizing flask/flask-sqlalchemy, thats just what I did to get my project working

turbid fox
#

Does anyone here have experience working with the webagg backend of matplotlib?

plucky fiber
#

Architecture question - If i wanted to build a web service that provided multiple IPC interfaces to a business logic/persistent layer, would I build a separate server per IPC protocol? Like, the business logic would be a library, then I would have one server wrap that with a REST interface, another server with a SOAP interface, another with a AMQP interface, so on and so forth?

surreal thicket
#

summarizing my response from elsewhere: no, you can put it all on one webserver

#

but im also wondering if thats even wise -- maintaining 3 separate implementations of an API could be a lot of work

plucky fiber
#

It would be, yeah, And its definitely a case of premature optimization - I don't really have plans to implement anything but a REST API, but would like to make the option easier later

junior cloak
#

@plucky fiber you can do this however you want! check out nameko: https://github.com/nameko/nameko

#

very elegant service pattern

clear bloom
#

I need help with a request.put towards CloudFlares API to update a dns-record, anyone who can help me with that?
It's really simple - just not working! ^_^

fierce frost
#

Flask
What's a nice way to indent a dictionary sent as a web response to request?

vagrant adder
#

use json() function

#

indenting doesn't really matter

fierce frost
#

Well, I GET the endpoint from a browser, so I would like it to be somewhat readable :p
Either way, looks like I simply haven't read the docs, as it is apparently explained there

#

Thanks anyway

hoary lotus
#

Is there a python3 library which contains classes to generate HTML? I'm specifically looking for dynamic HTML object creation, management, and serialization, not HTML object deserialization and parsing. I'm also specifically not looking for a templating library eg neither Jinja nor Mako. A souped-up dict to apply attributes to key/value pairs might suffice

hybrid citrus
#

I'm pretty sure bs4 can do all of that

patent cobalt
#

The are looking for the opposite of parsing, though

hoary lotus
#

I know of bs4. I've used it for HTML parsing. How would I use it to generate HTML?

patent cobalt
#

I don't think you can generate HTML with BS4 (not that I'm aware of). I don't know anything that fits your needs, though, but I have never wanted to do something like that, so that doesn't tell much.

hoary lotus
hybrid citrus
#

You can generate html using bs4

hoary lotus
#

Okay I'm reading the documentation for beautifulsoup, which I understand is here: https://www.crummy.com/software/BeautifulSoup/bs4/doc/

The documentation seems to have a lot of information about parsing HTML. I don't see a lot of information for generating html programmatically. A simple example: how would I use it to generate a table from a list of lists, where the outer list is the table and the inner list is each row?

#

in the gist I provided, I do that by:

html.table(['this', 'is', 'a', 'header', 'row'], [['this', 'is', 'a', 'body', 'row'], ['another', 'body', 'row']])
>>> html.EscapedContent(...)
#

doing str(html.EscapedContent()) would give me the generated HTML markup

#

Doing this results in a blank page:

from bs4 import BeautifulSoup

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        soup = BeautifulSoup('', 'html.parser')
        soup.title = 'This is an example title'
        soup.body = '' # soup.table() ???
        self.set_status(200)
        self.write(str(soup))
        self.finish()

How would I insert a table into the body using beautifulsoup?

#

It also didn't write a title in the html header

stiff totem
#

Hi guys. I'm doing web application using graphql (ariadne) + Django. Now I want to integrate it with Facebook authentication without using DRF. So I wanted to use jwt. Is there any good practice or suggestions ? Blog post etc,.. ? In graphql + Django what is your tactic to solve authentication?

sacred perch
#

where can I deploy my python flask backend app for free?

proper hinge
#

Look at Google Cloud and Heroku

#

Google has a low spec option that's free

#

It may be good enough for your needs

sacred perch
#

okay thank you looking it up

proper hinge
#

Deploy can be confusing the first time you get into it

#

Just a hurdle you have to figure out

#

It's pretty common for guides to be written on how to do that

#

Even in blog posts

#

That's what helped me

sacred perch
#

where can I see what is the name of my App?

#

right now I have this file structure so is this the name of my app "pypi"

I think the name is app only

proper hinge
#

No, name = pypi is unrelated

#

Most likely yes your app is just called app

#

based on the module name

sacred perch
#

oh oky yes the app name is app

alpine dune
#

How to run python flask server on pythonanywhere ?

#

I am getting this error in error log

sacred perch
#

hi this is my friend adi who is getting theses impoort errrors on pythonanywhere while deploying

proper hinge
#

Install that dependency then

#

It tells you it is missing and it can't import it

sacred perch
#

yes we installed jsonify, flask-cors but it doesn't seem to pick it up

alpine dune
#

But I have already created virtual env and then I have done pip install jsonify, flask-cors, flask flask-pymongo etc

proper hinge
#

Did you install for the correct python version?

#

Pip install is likely for python 2

#

Pip3 install would be for python 3

alpine dune
sacred perch
#

we already had created virtualenvironment with python 3 so I guess that was already installed with python 3

alpine dune
#

This is folder structure is it correct? What is module name in my case? It is app or pypi or backend??

sacred perch
#

I'm trying to deploy to heroku now : but my crashes there and the log for the same is as follows:

2019-09-06T08:19:24.037954+00:00 app[api]: Release v1 created by user pbdivyesh@tutanota.com
2019-09-06T08:19:24.154405+00:00 app[api]: Enable Logplex by user pbdivyesh@tutanota.com
2019-09-06T08:19:24.154405+00:00 app[api]: Release v2 created by user pbdivyesh@tutanota.com
2019-09-06T08:19:24.037954+00:00 app[api]: Initial release by user pbdivyesh@tutanota.com
2019-09-06T08:19:40.000000+00:00 app[api]: Build started by user pbdivyesh@tutanota.com
2019-09-06T08:20:49.105158+00:00 app[api]: Deploy ae2462df by user pbdivyesh@tutanota.com
2019-09-06T08:20:49.128631+00:00 app[api]: Scaled to web@1:Free by user pbdivyesh@tutanota.com
2019-09-06T08:20:49.105158+00:00 app[api]: Release v3 created by user pbdivyesh@tutanota.com
2019-09-06T08:20:53.091060+00:00 heroku[web.1]: Starting process with command `gunicorn deploy:app`
2019-09-06T08:20:55.017478+00:00 heroku[web.1]: State changed from starting to crashed
2019-09-06T08:20:55.030615+00:00 heroku[web.1]: State changed from crashed to starting
2019-09-06T08:20:54.995464+00:00 heroku[web.1]: Process exited with status 127
2019-09-06T08:20:54.941721+00:00 app[web.1]: bash: gunicorn: command not found
2019-09-06T08:20:59.050614+00:00 heroku[web.1]: Starting process with command `gunicorn deploy:app`
2019-09-06T08:20:59.000000+00:00 app[api]: Build succeeded
2019-09-06T08:21:01.110223+00:00 heroku[web.1]: State changed from starting to crashed
2019-09-06T08:21:01.083451+00:00 heroku[web.1]: Process exited with status 127
2019-09-06T08:21:01.027817+00:00 app[web.1]: bash: gunicorn: command not found
unborn terrace
#

@sacred perch add gunicorn to requirements.txt

sacred perch
#

like this, right? I don't know I have not seen requirements.txt file before

#

@unborn terrace ^^

unborn terrace
#

yeah, without commas though

sacred perch
#

okay

unborn terrace
#

Like this

flask
flask-cors
flask-pymongo
gunicorn
jsonify
sacred perch
#

it still doesn't work

#

wait I have removed that whole app and I'm trying with a new app

#
(D:\practice\pizza_app\backend) =>  heroku logs --source app --tail
2019-09-06T08:42:32.087184+00:00 app[api]: Initial release by user pbdivyesh@tutanota.com
2019-09-06T08:42:32.236628+00:00 app[api]: Release v2 created by user pbdivyesh@tutanota.com
2019-09-06T08:42:32.236628+00:00 app[api]: Enable Logplex by user pbdivyesh@tutanota.com
2019-09-06T08:42:32.087184+00:00 app[api]: Release v1 created by user pbdivyesh@tutanota.com
2019-09-06T08:46:32.000000+00:00 app[api]: Build started by user pbdivyesh@tutanota.com
2019-09-06T08:48:57.711043+00:00 app[api]: Release v3 created by user pbdivyesh@tutanota.com
2019-09-06T08:48:57.729372+00:00 app[api]: Scaled to web@1:Free by user pbdivyesh@tutanota.com
2019-09-06T08:48:57.711043+00:00 app[api]: Deploy 0a60359b by user pbdivyesh@tutanota.com
2019-09-06T08:49:03.399074+00:00 app[web.1]: bash: gunicorn: command not found
2019-09-06T08:49:07.000000+00:00 app[api]: Build succeeded
2019-09-06T08:49:09.353550+00:00 app[web.1]: bash: gunicorn: command not found

still gives the same error

unborn terrace
#

@sacred perch did you commit and push the requirements.txt ? Do you also have the Python buildpack added to the project ?

sacred perch
#

yes I did and pushed it

unborn terrace
#

Show the buildlog

sacred perch
#

what is buildpack

unborn terrace
sacred perch
#

no I didn't do that

#

let me remove this app and create a new one

vagrant adder
#

It sounds like you need a buildpack @sacred perch

#

What does your Procfile look like?

sacred perch
#

procfile has this

web: gunicorn deploy:app
#

okay so now I have created the app with build pack as mentioend on that link

#

but the app is still crashed so which logs should I show you?

vagrant adder
#

What does your app structure look like

sacred perch
#

app structure is this

vagrant adder
#

Ah

#

Well, deploy is not needed then

#

web: gunicorn app:app

#

After you change that, push it to a heroku repo

#

git push heroku master

sacred perch
#

yes wait I'm doing it

#

still the app is crashed

vagrant adder
#

Logs?

sacred perch
#
 (D:\practice\pizza_app\backend) =>  heroku logs --source app --tail
2019-09-06T09:04:22.463461+00:00 app[api]: Initial release by user pbdivyesh@tutanota.com
2019-09-06T09:04:22.463461+00:00 app[api]: Release v1 created by user pbdivyesh@tutanota.com
2019-09-06T09:04:23.223197+00:00 app[api]: Enable Logplex by user pbdivyesh@tutanota.com
2019-09-06T09:04:23.223197+00:00 app[api]: Release v2 created by user pbdivyesh@tutanota.com
2019-09-06T09:09:36.000000+00:00 app[api]: Build started by user pbdivyesh@tutanota.com
2019-09-06T09:10:18.483059+00:00 app[api]: Release v3 created by user pbdivyesh@tutanota.com
2019-09-06T09:10:18.483059+00:00 app[api]: Deploy 0a60359b by user pbdivyesh@tutanota.com
2019-09-06T09:10:18.494295+00:00 app[api]: Scaled to web@1:Free by user pbdivyesh@tutanota.com
2019-09-06T09:10:23.541168+00:00 app[web.1]: bash: gunicorn: command not found
2019-09-06T09:10:28.000000+00:00 app[api]: Build succeeded
2019-09-06T09:10:29.409448+00:00 app[web.1]: bash: gunicorn: command not found
2019-09-06T09:13:48.000000+00:00 app[api]: Build started by user pbdivyesh@tutanota.com
2019-09-06T09:14:04.404948+00:00 app[api]: Deploy 164f837e by user pbdivyesh@tutanota.com
2019-09-06T09:14:04.404948+00:00 app[api]: Release v4 created by user pbdivyesh@tutanota.com
2019-09-06T09:14:09.821815+00:00 app[web.1]: bash: gunicorn: command not found
2019-09-06T09:14:14.000000+00:00 app[api]: Build succeeded
vagrant adder
#

Hmm

sacred perch
#

should I install gunicorn again?

vagrant adder
#

Does it work when you try to visit website?

#

Even better, delete that project and make new

sacred perch
#

no its not working online on heroku

#

hmm okay I made this new one

vagrant adder
#

Okay, delete that heroku instance

sacred perch
#

yes deleting the app from heroku

vagrant adder
#

And create a new one and specify buildpack then

sacred perch
#

okay what comands should I run

heroku create myapp --buildpack heroku/python
#

this one right?

vagrant adder
#

Hold up

#

I think that's it

sacred perch
#

okay things are happening wait I have just done git push heroku master after this one

vagrant adder
#

:+1:

marsh canyon
#

how often is css flex box used

sacred perch
#

it still crashes

#
(D:\practice\pizza_app\backend) =>  heroku logs --source app --tail
2019-09-06T09:20:37.505578+00:00 app[api]: Release v2 created by user pbdivyesh@tutanota.com
2019-09-06T09:20:37.505578+00:00 app[api]: Enable Logplex by user pbdivyesh@tutanota.com
2019-09-06T09:20:37.362214+00:00 app[api]: Initial release by user pbdivyesh@tutanota.com
2019-09-06T09:20:37.362214+00:00 app[api]: Release v1 created by user pbdivyesh@tutanota.com
2019-09-06T09:21:25.000000+00:00 app[api]: Build started by user pbdivyesh@tutanota.com
2019-09-06T09:25:06.885811+00:00 app[api]: Release v3 created by user pbdivyesh@tutanota.com
2019-09-06T09:25:06.905045+00:00 app[api]: Scaled to web@1:Free by user pbdivyesh@tutanota.com
2019-09-06T09:25:06.885811+00:00 app[api]: Deploy 164f837e by user pbdivyesh@tutanota.com
2019-09-06T09:25:12.736862+00:00 app[web.1]: bash: gunicorn: command not found
2019-09-06T09:25:16.000000+00:00 app[api]: Build succeeded
2019-09-06T09:25:17.997424+00:00 app[web.1]: bash: gunicorn: command not found
#

@marsh canyon flexbox is used quite extensively

vagrant adder
#

What does your requirements.txt looks like

#

@marsh canyon
A lot man

marsh canyon
#

okay

sacred perch
#
flask
flask-cors
flask-pymongo
gunicorn
jsonify

this is requirements.txt

marsh canyon
#

is css flex box and css grid used for same purpus?

#

or do they have different functionality?

sacred perch
#

@marsh canyon yes bro they are both for laying out your UI

marsh canyon
#

are they used together or alternatives to each other?

sacred perch
#

yes you can use them separately or together

marsh canyon
#

i will check it out, thanks

#

oki

sacred perch
#

gird is used when you have a layout already specified and flex is something you use for your smaller componennt but still its your design choise

vagrant adder
#

Hmm

#

Try googling it

#

I don't get how it doesn't have gunicorn installed

sacred perch
#

I installed it via pip

#

how do I write versions for each dependencies in requirements.txt

#

is there any other easier way to deploy Python Flask app online? for free?

native root
#

pip install -r requirements.txt is the command

#

otherwise it's expecting a package-version pair, pip==19.0.1 for example

sacred perch
#

yup just figured and did it

#

please suggest any other alternative to deploy things online

native root
#

"gunicorn not found"

#

Apparently you're heroku setup is not installing gunicorn

sacred perch
#

yes it was mostly not able to find gunicorn

unborn terrace
#

@sacred perch show release/build log

#

Ah that's sorted out, cool 😄

sacred perch
#

yeah basically the CLI is shit and this new way of handling repo directly from our personal youtube worked out

vagrant adder
#

their cli isn't even that bad

#

their VPS management is bad

sacred perch
#

what is VPS?

marsh canyon
#

heroku is not that bad, good for starting with

native tide
#

guys how can i render a list of tuples on the template, i'm using django framework btw

#
    def post(self, request, *args, **kwargs):
        # get search item from post request
        domain = request.POST.get('domain')
        # get domains from database and check if list is null
        if not db.get_domain(domain):
            #context = {'error': "sorry we aren't able to find this domain in our database"}
            context = {'error': 'cannot find'}  # must have if not goes into error because the render don't have context
            messages.add_message(
                request,
                messages.INFO,
                f'Sorry, {domain} is not our system!',
                extra_tags='danger')
        else:
            ### I want to render a list of tuples but the value which will be visible on the webpage is only the domain not domain_id
            for elem in db.get_domain(domain):
                print(elem)
                (domain_id, domain) = elem
            print(f"id is {domain_id} and domain is{domain}")
            context = {'message': domain}
            print(context)
        return render(request, "data_leak/analyze.html", context=context)
grave latch
#

hi can I run any python script using php exec()
?

vagrant adder
#

Welll

#

I think you can

grave latch
#

@vagrant adder even it contains matplotlib graph

vagrant adder
#

Hm

#

You'll have to have it installed via pip

grave latch
#

@vagrant adder thank u..

#

But I have a question does the webserver I will run my script have python lib installed beforehand or what how does it work @unreal python

#

@vagrant adder

vagrant adder
#

python --v

grave latch
#

I mean do they have matplotlib

vagrant adder
#

Is it linux or windows

grave latch
#

windows

vagrant adder
#

Oh no

#

pip list

#

Then you have to search

#

On your own

#

On linux it's pip list | fgrep -i 'matplotlib'

grave latch
#

I know php & python separely. Never used python on website. I am sorry I need a little bit of explaining.

#

my whole website in php

#

I just need to run 1 python script

#

I searched on internet they said use php exec().

#

What is the thing about linux/windows?

#

I thought websites are websites. DO THEY HAVE OS?

#

@vagrant adder

vagrant adder
#

Websites?

#

Nope

#

Websites are apps that hold conversations with other computers

grave latch
#

So I need a linux /windows server where my python will run?

#

@vagrant adder

vagrant adder
#

Yeah

#

Preferably linux

grave latch
#

How can I get a linux server ? Do I have to buy or is it free

#

?

vagrant adder
#

Heroku offers free small linux servers

grave latch
#

I am completely new to this sever thing. You are being very helpful. I just have few more qestion

vagrant adder
#

Sure

#

Shoot

grave latch
#

how do i connect linux server to my php code.

vagrant adder
#

Well, there goes term deploying

#

Now comes google time

grave latch
#

yeah....... correct

#

can I access database from linux server

vagrant adder
#

Yes

grave latch
#

can I access database from linux server?

vagrant adder
#

Yea, you'll need a program of yours that connects or some other software that acts as a program

#

It depends which database

grave latch
#

do I need to pay for webhosting.

#

I am using a free one. It says exec is disabled

#

@vagrant adder

vagrant adder
#

Which one

grave latch
vagrant adder
#

Switch to heroku

grave latch
#

ok... I think I can try to do the rest

#

before this I was thinking about learning flask or django

#

@vagrant adder

vagrant adder
#

I am using flask and it's amazing

#

Php is really showing its age

#

I gotta go

grave latch
#

ok

#

thank u

winter flint
#

having an issue with a celery task in flask. Getting the following error:

sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <Page at 0x7efbf75cdc18> is not bound to a Session; lazy load operation of attribute 'listing' cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3)

Basically trying to do something like this:

from app.models import Page
from app import db
from time import sleep

@celery.task(bind=True)
def test_task(self):
    pages = Page.query.all()
    for page in pages:
        #do something with page
        db.session.add(result)
        db.session.commit()
        sleep(100)```
#

but it's failing in the page loop because the pages stuff has expired?

native tide
#

Hi there, I'm encountering an error from trying to import some objects from a module.

#

I'm getting the error ModuleNotFoundError: No module named 'notetaker.web_ui' even though the syntax seems correct... basically I need to go up one directory level, go into another package, and access a module. The full structure is opened on the image on the left. Any bump in the right direction would be appreciated. thank you

native tide
#

and if I change the import line to from ..web_ui.models import Category, Post I get back ValueError: attempted relative import beyond top-level package so I feel kindof stuck on what the solution is

daring pecan
#

Im a total noob with web dev skills and am putting together a hobby project. How can I define my font that I want to use in one place across all my CSS files? It's a pain to change every entry across all my files if I want to modify it

vagrant adder
#

I think you use @import statement

#

Not sure tho

tired hound
#

what is better for website making python or java scriprt

native tide
#

one is a frontend language and the other is a backend language @tired hound

proper hinge
#

Well, you can have JS as a backend too

tired hound
#

in home
return HttpReponse('<h1>Home Page</h1>')
NameError: name 'HttpReponse' is not defined

#

im getting that eror

#

im doing python django

native tide
#

is it imported?

tired hound
#

yes

#

that page is not working

native root
#

HttpResponse

tired hound
#

oh

#

lol

#

ty

native root
#

👍

native tide
#

btw, if you use an IDE like pycharm, it will highlight if your syntax is incorrect

hoary lotus
#

But if you're someone like me, you'll look at the funny squiggly lines and disregard them in favor of running the damn program anyway

#

"whoops, I should pay attention to my IDE more" -- me

native tide
#

pycharm has several levels of highlighting, with escalating levels of seriousness

#

the syntax stuff like this is its own color, while logical errors are another

frigid egret
#

Hi all

#

I need some help figuring out the cause of an error

#

'User' object has no attribute 'get'

#

Problem is, lately I haven't touched User and anything related to it.

#

Tried disabling some connections of User to other objects and it didn't help.

unborn terrace
#

Error is pretty explicit

frigid egret
#

I know. As I'm saying, haven't touched User and anything related to it lately, and I don't see any case where It has this attribute.

unborn terrace
#

We do not know what User is

#

We can't guess it

frigid egret
#

Worse is that log doesn't point me at the file and/or line with the error

unborn terrace
#

We do not know what you are talking about at all

frigid egret
#

Ask

unborn terrace
#

Give information about your problem

frigid egret
#

Ye, I was about to, geez

#

So my user derives from custom AbstractUser class

#
class User(AbstractUser):
    """
    Custom user model.
    """
    phone = models.CharField(max_length=100, unique=True, verbose_name=_('Phone'))
    username = models.CharField(max_length=150, unique=False, blank=True, null=True)
    first_name = models.CharField(max_length=30, verbose_name=pgettext_lazy('User|Name', 'Name'))
    language = models.CharField(max_length=20, choices=settings.LANGUAGES, verbose_name=_('Language'))

    USERNAME_FIELD = 'phone'
    REQUIRED_FIELDS = ['first_name']

    objects = UserManager()

    def __str__(self):
        return self.phone

    @classmethod
    def normalize_phone(cls, phone):
        """
        Remove extra spaces and non-digit chars from phone.
        """
        _normalize_phone = re.compile(r'(\s{2,}|[a-zA-Z]+)').sub
        return _normalize_phone('', phone)
unborn terrace
#

okay so that's Django, tell it next time

frigid egret
#

So that instead of login or email, phone is the required field

#

Sorry

unborn terrace
#

what you are wanting to do is probably User.objects.get

frigid egret
#

Should have said first

#

So, here's the only case where I actually found it. Which, I have to add, have been working before, and for quite some time

#
def profile(request):
    """
    User profile page view.
    """
    template_name = 'shop/profile.html'

    if not User.is_authenticated:
        return redirect(reverse('accounts:login'))

    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('shop-home')
        else:
            messages.error(request, f'Please correct errors {form.errors}.')
    else:
        form = PasswordChangeForm(request.user)

    user = User.objects.get(phone=request.user.phone)
    context = {
        'orders': Order.objects.filter(phone=user.phone),
        'form': form
    }

    return render(request, template_name, context)
unborn terrace
#

@frigid egret User.is_authenticated is a nonsense here

frigid egret
#

It's a view btw

unborn terrace
#

request.user.is_authenticated is probably what you want instead

#

Sure it is

frigid egret
#

This line prevents non logged in users to open this page

#

Ok...

unborn terrace
#

It does not, because you are checking a class attribute here

#

(or property, or whatever)

#

That is, it will always have the same value, in that case it will always satisfy the condition

frigid egret
#

So, I am getting a user object based on their phone field

unborn terrace
#

What you have to check is the is_authenticated property of the user object. And that user object is request.user

frigid egret
#

I get it

unborn terrace
#

also, why are you doing user = User.objects.get(...) ?

#

You are basically saying “give me the user that is that user”

#

Just use request.user, do not query it again

frigid egret
#

hold on a sec

#

This view isn't a problem actually. I've just double checked and it works fine.

#

Maybe there's a better way to write it, as you are saying. But it works nonetheless

unborn terrace
#

Try accessing your view without being logged in, you'll see

#

You will not be redirected to login view

frigid egret
#

Oh, it's a different error

#

'AnonymousUser' object has no attribute 'phone'

unborn terrace
#

Indeed

#

because you are not checking is_authenticated correctly, as I stated in previous messages

frigid egret
#

Ok, 1 sec, let me fix that

#

Now works fine

#

So, back to the get error

#

It happens when I fill up and send an order form.

unborn terrace
#

Show exact error

frigid egret
#

forms.py

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ['phone', 'first_name', 'delivery_date', 'delivery_time', 'address', 'comment']

    def clean(self):
        phone = self.cleaned_data.get('phone')
        digits = set(string.digits)             # To validate phone
        first_name = self.cleaned_data.get('first_name')
        letters = set(string.ascii_letters)     # To validate name
        '''
        name validation
        '''
        if len(first_name) < 2:
            raise forms.ValidationError('Name is too short')
        for i in first_name:
            if i not in letters:
                raise forms.ValidationError('Only letters in name please')
        '''
        phone validation
        '''
        if len(phone) < 2:
            raise forms.ValidationError('Phone is too short')
        for i in phone:
            if i not in digits:
                raise forms.ValidationError('Only digits in phone please')
#

models.py

class Order(models.Model):
    DELIVERY_TIME_CHOICES = [
        ('09-10', '09-10'),
        ('10-11', '10-11'),
        ('11-12', '11-12'),
        ('12-13', '12-13'),
        ('13-14', '13-14'),
        ('14-15', '14-15'),
        ('15-16', '15-16'),
        ('16-17', '16-17'),
        ('17-18', '17-18'),
        ('18-18.30', '18-18.30'),
    ]
    phone = models.CharField(max_length=100, verbose_name=_('Phone'))
    first_name = models.CharField(max_length=100, verbose_name=pgettext_lazy('Order|Name', 'Order'))
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Created at'))
    delivery_date = models.DateField(verbose_name=_('Delivery date'))
    delivery_time = models.CharField(
        max_length=10,
        choices=DELIVERY_TIME_CHOICES,
        verbose_name=_('Delivery time'),
    )
    address = models.CharField(max_length=100, verbose_name=_('Address'))
    comment = models.CharField(max_length=100, verbose_name=_('Comment'), blank=True, null=True)

    @property
    def total_price(self):
        return sum([item.price for item in self.orderitem_set.all()])

    "Property admin panel translation"
    def total_price_admin(self):
        return self.total_price

    total_price_admin.short_description = _('Total price')

    def __str__(self):
        return f""

    class Meta:
        verbose_name = _('Order')
        verbose_name_plural = _('Orders')


pre_save.connect(check_phone, sender=Order)
#

Here's the error

unborn terrace
#

That's the code, not the error

#

Please pase the error as well

frigid egret
#

It's quite long

unborn terrace
#

Copy the text on Pastebin or something like that

#

I can't read these images

frigid egret
#

ok

#

You could also "open original". Very much readable that way.

unborn terrace
#

Images are not well-suited to read code anyway

frigid egret
#

Yea, takes a while with this error

#

It's AnonymousUser this time cause I've logged out.

unborn terrace
#

@frigid egret show template

frigid egret
#
{% extends "shop/base.html" %}
{% load static %}
{% block content %}
    <h1>Order details:</h1>
    <div class="container">
        <form action="/order/" method="POST" id="order-form">
            {% csrf_token %}
            {{ form.as_p }}
            <div>
                <button id="order-submit" class="btn btn-secondary" type="submit">Submit</button>
            </div>
        </form>
    </div>
{% endblock content %}

{% block body_extra %}
    <script type="text/javascript" src="{% static 'shop/js/order.js'%}"></script>
{% endblock body_extra %}
#

Nothing fancy here

#

I can post order.js as well. What it does is it takes data about item user wants to buy and attaches it to the post request.

unborn terrace
#

Do you have the same issue with a logged-in user ?

frigid egret
#

Yep. exactly the same

#

Except User instead of AnonymousUser

unborn terrace
#

That's not the right template

#

Show shop/profile.html

#

Uh no wait

#

No that's right

frigid egret
#

Uh, ok

unborn terrace
#

That's not the right template

#

Your error is caused by another view

#

Not the one you pasted

frigid egret
#

Oh

unborn terrace
#

Because it has been caused by the shop/order.html template

frigid egret
#

I mean it appears when I send this specific form...

unborn terrace
#

Whereas the view you pasted here is not using this template

frigid egret
#

Ok, 1 sec

#
{% extends "shop/base.html" %}
{% load static %}

{% block content %}
    <div class="container mt-5">
    {% if user.is_authenticated %}
        <h1>User profile</h1>
        <p>Phone: {{ user.phone }}</p>
        <p>Name: {{ user.first_name }}</p>
        <div class="spoiler">
            <input type="button" onclick="showSpoiler(this);" value="Change password"/>
            <div class="inner" style="display:none;">
                <form method="post">
                    {% csrf_token %}
                    {{ form.as_p }}
                    <div>
                        <button id="order-submit" class="btn btn-secondary" type="submit">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    {% else %}
        <meta http-equiv="refresh" content="0; URL={% url 'accounts:login' %}"/>
    {% endif %}

    {% for order in orders %}
        <h6>Order {{ order.phone }}, sum: {{ order.total_price }}</h6>
    {% endfor %}
    </div>
{% endblock content %}

{% block body_extra %}
    <script type="text/javascript" src="{% static 'shop/js/profile.js' %}" defer='defer'></script>
{% endblock body_extra %}
unborn terrace
#

Show the associated view

frigid egret
#

Showed it previously. That's the only place where there is a get action

#
def profile(request):
    """
    User profile page view.
    """
    template_name = 'shop/profile.html'

    if not request.user.is_authenticated:
        return redirect(reverse('login'))

    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('shop-home')
        else:
            messages.error(request, f'Please correct errors {form.errors}.')
    else:
        form = PasswordChangeForm(request.user)

    user = User.objects.get(phone=request.user.phone)
    context = {
        'orders': Order.objects.filter(phone=user.phone),
        'form': form
    }

    return render(request, template_name, context)
unborn terrace
#

No, that's not the right view

#

The error you pasted is caused by the shop/order.html template

#

Which is not used by this view

frigid egret
#
def order(request):
    form = OrderForm(request.user, request.POST)
    if request.method == 'POST':
        mutable_request_data = request.POST.copy()
        order_items = json.loads(mutable_request_data.pop('order')[0])
        order_details = OrderForm(mutable_request_data)

        if order_details.is_valid():

            with transaction.atomic():
                order_obj = order_details.save()

                # create object OrderItem item for each item in the order
                for order_item in order_items:
                    item = Pizza.objects.get(id=order_item['id'])
                    params = dict(
                        order=order_obj,
                        item=item,
                        size=order_item['size'],
                        quantity=order_item['quantity'],
                    )
                    OrderItem.objects.create(**params)

    else:
        user = request.user
        form = OrderForm()
        if not user.is_anonymous and user.is_authenticated:
            form = OrderForm(initial={'phone': user.phone, 'first_name': user.first_name})
    return render(request, 'shop/order.html', {'form': form})
#

In post request, alongside form data, there's an additional key "order" which contains a dictionary with items user selected (pizzas in this case)

unborn terrace
#

@frigid egret this form = OrderForm(request.user, request.POST) does not make sense

frigid egret
#

Ok, I have my doubts about this one cause it's something I don't entirely understand

unborn terrace
#

Use this instead

form = OrderForm(data=request.POST, initial={
    'phone': request.user.phone,
    'first_name': request.user.first_name
})
#

Yeah read Django's ModelForm doc

frigid egret
#

Before, I had an error that form gets referenced before assignment

#

So I googled how to do it and got this line from some SO post. But still didn't quite get how it should work

unborn terrace
#

Do not, ever, copy SO's anwsers without fully understanding them

frigid egret
#

I try doing that. But sometimes it's hard to find an actual explanation, especially since i'm still not even a junior, just learning

unborn terrace
#

Still make the effort to understand, that's how you learn, and how you avoid ending-up with code you do not have control over

frigid egret
#

It still doesn't work... let me find the error

#

Ok, now this is really frustrating.

#

haven't seen anything like that before

#

Do you have any idea?

#

Ok wait, that's double weird. Tried it again, and i get the same "'User' object has no attribute 'get'
" error again

remote marsh
#
  File "C:\Program Files\Python36\lib\wsgiref\simple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

probably object is not being created.

frigid egret
#

That error has been happening randomly lately but it doesn't actually break anything. And I couldn't find solution anywhere so I skipped it. Know it's not the right way to do it but I can't really sit and wait forever.

remote marsh
#

status = self.status
print(status)
splitting_status = status.split('
print(splitting_status)

#

that's cool. however you might face troubles later on.

frigid egret
#

wait-wait

remote marsh
#

I wanted to highlight that print statements are the best debuggers

frigid egret
#

Can we get back to that User error again please, cause it's still there?

#

I'll post it again, in case there's something new in log this time

#

@unborn terrace

#

@remote marsh Oh dude, sorry. I thought you're Solon. Didn't read the name 😛

remote marsh
#

humbled that you would think that 🙂 @unborn terrace is pro(grammer).

#

alright, I'll die now 😛

frigid egret
#

Nah, I just continued talking like you were the same person

#

Didn't mean to say I don't want your input

#

Do you have any idea what might be causing this error?

remote marsh
#

somewhere you are adding methods, maybe adding GET to it will work.
methods = ['POST','GET']

frigid egret
#

Good news: no error

#

Bad news: no order either

remote marsh
#

like in flask the syntax is something like this
@app.route('/script',methods=['POST'])
so adding get works when get requests are made

#

sorry, I have just barged in and have no context.

frigid egret
#

You can scroll up, I've posted all the relevant info previously

#

Well, as I'm saying, there's no error now but when I send form, it doesn't create an order object.

remote marsh
#

try debugging it by placing print statements wherever object is initialized, some updation is made, and object is returned. see what kind changes the object is going through. if the final object has relevant values, it is not being given as an input.

#

return render_template('index.html',combined_list=movie_dict) # flask way.
now I can use combined_list using jinja variables.

frigid egret
#

Ok, so it prints me order_items variable

#

But won't print items from for in loop. So it stops before reaching that part for some reason

#

@remote marsh

#
def order(request):
    form = OrderForm(data=request.POST, initial={
        'phone': request.user.phone,
        'first_name': request.user.first_name
    })
    if request.method == 'POST':
        mutable_request_data = request.POST.copy()
        order_items = json.loads(mutable_request_data.pop('order')[0])
        print(order_items)
        order_details = OrderForm(mutable_request_data)

        if order_details.is_valid():

            with transaction.atomic():
                order_obj = order_details.save()

                # create object OrderItem item for each item in the order
                for order_item in order_items:
                    print(order_item)
                    item = Pizza.objects.get(id=order_item['id'])
                    params = dict(
                        order=order_obj,
                        item=item,
                        size=order_item['size'],
                        quantity=order_item['quantity'],
                    )
                    OrderItem.objects.create(**params)

    else:
        user = request.user
        form = OrderForm()
        if not user.is_anonymous and user.is_authenticated:
            form = OrderForm(initial={'phone': user.phone, 'first_name': user.first_name})
    return render(request, 'shop/order.html', {'form': form})
remote marsh
#
def order(request):
    form = OrderForm(data=request.POST, initial={
        'phone': request.user.phone,
        'first_name': request.user.first_name
    })
    if request.method == 'POST':
        mutable_request_data = request.POST.copy()
        order_items = json.loads(mutable_request_data.pop('order')[0])
        print(order_items)
        order_details = OrderForm(mutable_request_data)
    print(order_details)
        if order_details.is_valid():

            with transaction.atomic():
                order_obj = order_details.save()
        print(order_obj)

                # create object OrderItem item for each item in the order
        print(order_items)
                for order_item in order_items:
                    print(order_item)
                    item = Pizza.objects.get(id=order_item['id'])
                    params = dict(
                        order=order_obj,
                        item=item,
                        size=order_item['size'],
                        quantity=order_item['quantity'],
                    )
                    new_order_object = OrderItem.objects.create(**params)
        print(new_order_object)
        for key in new_order_object:
            print(key)

    else:
    print('in else')
        user = request.user
        form = OrderForm()
        if not user.is_anonymous and user.is_authenticated:
            form = OrderForm(initial={'phone': user.phone, 'first_name': user.first_name})
    return render(request, 'shop/order.html', {'form': form})
#

test these print statements first.

#

from models import ProductModel - does this work?

frigid egret
#

Ok, thanks but it was a different thing

#

I've changed time format recently and i thought maybe it makes form data invalid, do it doesn't get past
if order_details.is_valid():

#

@remote marsh Thank you 🙂

#

@native tide can you also post your admin.py?

remote marsh
#

@frigid egret I don't remember much of Django so sorry if you got confused.

frigid egret
#

@native tide Uh. Ok, this is weird, should work

#

LOL

remote marsh
#

let's hop on to the I hate Django too train 😦 although I haven't been doing much web dev recently.
Evem my live projects are on flask xD [ayushxx7.pythonanywhere.com | mangal-seva.herokuapp.com]
But I'd definitely like to revise it. This channel is helping me move in that direction.

frigid egret
#

You should follow some tutorial on that. It's really basis stuff and there's alot of material on that online.

#

@unborn terrace Found the reason why I wasn't using request.user.field. If user is not logged in, It results in errors that AnonymousUser doesn't have that field.

stiff totem
#

Hi guys. I'm doing web application using graphql (ariadne) + Django. Now I want to integrate it with Facebook authentication without using DRF. So I wanted to use jwt. Is there any good practice or suggestions ? Blog post etc,.. ? In graphql + Django what is your tactic to solve authentication?

steel tiger
#

What's the best way to document a flask-restful api?

#

(Asking from not knowing anything about how to document python)

#

Would I just use sphinx or is there a nice extension so I could use docstrings?

vagrant adder
#

i would say sphinx is getting bit finiky but since there isn't any other options, i would say go with sphinx

remote marsh
#

hi, so I was working on a creating a script for printing relevant information to a webpage (zendesk ticket) in form on an html table. The core part of reading information from file and color coding it based on some parameters is done.
However, there are two scenarios that I still need to cover.

  1. I need to attach/show image present in the logs to the webpage somehow.
  2. I need to implement a method which can read multiple file names (such as player.log, player.log.1, Android-Dumpstate.log, Android_1-Dumpstate.log etc.)
    for attachment, I was thinking of using an html image tag, but then what would be the href part of the image?
    for multiple file names, I don't have a definite pathway, I am thinking of using some regex somehow
    example of attachment.
#

I need to do the same, but I need to implement it on my own

#

as in I want to make it somewhat more easier to code and store

jade egret
#

k. my bad looking at the your issue is how to use the api / write a python wrapper for it. and not really webdev...

pure ice
#

Are there advantages to using Flask over Django? I'm learning Django currently and am curious about the difference

autumn bobcat
#

apache isn't redirecting to https properly, it redirects to a different subdomain

#

any ideas

hard moon
#

Hello here

#

How do you hide elements on Bootstrap based on the support?

#

Like hiding side bar when switching to smartphone view.

patent cobalt
#

I have never used Bootstrap, but it probably does something with breakpoints for responsivity and you should be able to use and set those

hard moon
#

I'm using the latest version.

patent cobalt
#

maybe that's not your version, but there should be similar page for your version

hard moon
#

Thanks, i'll take a look.

#

Yeah it works.

#

Thanks.

river sinew
#

Ok guys I have a server (software). A computer in my private network which will be the server (hardware). And I rented a domain. Now, the question is, how do I connect these? Currently my domain simply frame-redirects to my actual server ip, but I want the server to use the domain directly! How can I do that?

gleaming herald
#

Can anyone write a dynamic function

#

which will give the response of API

#

as a dictionary or text

#

in short how to consume a API

vagrant adder
#

from client side or server side

rigid laurel
#

Also asking this here as well as OT. I want to make a full stack CRUD web app just to have something to stick on Github. I've done the backend as a pretty neat and simple Flask API, but I can't be fucked in the slightest to actually make a front end. Does anyone have any suggestions for building a not-ugly React app with relatively minimal effort?

native tide
tardy dawn
#

@rigid laurel you come up with anything that answers that question? I'll be needing similar soon.

rigid laurel
#

All I really know is that the solution is probably React with Redux - but theres a million different guides almost all of which have problems

native tide
#

i need some help with flask
im an absolute beginner
im trying to set up an app where a sum appears and the user needs to input the right answer
i dont know how to do that

gleaming herald
#

@vagrant adder Client Side

vagrant adder
#

Do you want to consume external api or your own

gleaming herald
#

external API

#

That's why I sent you the links of open API

vagrant adder
#

In either way, use axios

gleaming herald
#

Can I write a single function