#web-development

2 messages ยท Page 173 of 1

edgy anvil
#

what

lyric grotto
#

and reinstall

edgy anvil
#

wdym delete aws

lyric grotto
#

just delete it

edgy anvil
#

this thing?

lyric grotto
#

and reinstall

opaque rivet
# edgy anvil

Django in production doesn't serve static files, it's only in development when debug=True, have you accounted for that?

lavish ferry
#

Anychance I can get a hand here, no matter what I do this validation always fails:

class Cipher147Form(FlaskForm):
    encrypt = SubmitField('encrypt', validators=[Optional()])
    decrypt = SubmitField('decrypt', validators=[Optional()])
    nonce_options=["hybrid", "random", "time"]
    encoding_options=["base85", "base64", "base32", "base16"]
    key = StringField('key', validators=[InputRequired()])
    text = TextAreaField('text', validators=[InputRequired()])
    nonce = SelectField('nounce', validators=[InputRequired()], choices=nonce_options)
    encoding = SelectField('encoding', validators=[InputRequired()], choices=encoding_options)

@app.route("/encryption/147cipher", methods=['GET', 'POST'])
def cipher147():
    form = Cipher147Form()
    if request.method == "POST":
        if form.validate_on_submit():
            key = form.key.data
            text = form.text.data
            nonce = form.nonce.data
            encoding = form.encoding.data
            if form.encrypt.data:
                output = encrypt_147(key, text, encoding, nonce)
            elif form.decrypt.data:
                output = decrypt_147(key, text, encoding)
            data = [key, text, encoding, nonce, output]
            return render_template('encryption/147cipher.html', title="147Cipher", form=form, data=data)
    else:
        return render_template('encryption/147cipher.html', title="147Cipher", form=None)
#

Here are my imports:

from flask import Flask, render_template, send_from_directory, request
from flask_wtf import FlaskForm
from wtforms import form, StringField, TextAreaField, SelectField ,SubmitField
from wtforms.validators import InputRequired, Optional, length
#

Here is the HTML bit:

<form method="POST">
    {{ form.csrf_token }}
#

And I do set the key:

# Pull secret key.
app.config['SECRET_KEY'] = os.getenv('CSRF_KEY')
opaque rivet
lavish ferry
#

No I don't know how to get that to print somewhere

lavish ferry
opaque rivet
#

print(form.errors)

lavish ferry
#

I did try that and it didn't print...

opaque rivet
#

show code

#

btw, if request.method == "POST": is irrelevant, form.validate_on_submit(): checks that the request method is POST iirc

lavish ferry
#

Oh nice

#

Thanks

#

I tried this and I get no print in the terminal

#
@app.route("/encryption/147cipher", methods=['GET', 'POST'])
def cipher147():
    form = Cipher147Form()
    if request.method == "POST":
        if form.validate_on_submit():
            key = form.key.data
            text = form.text.data
            nonce = form.nonce.data
            encoding = form.encoding.data
            if form.encrypt.data:
                output = encrypt_147(key, text, encoding, nonce)
            elif form.decrypt.data:
                output = decrypt_147(key, text, encoding)
            data = [key, text, encoding, nonce, output]
            return render_template('encryption/147cipher.html', title="147Cipher", form=form, data=data)
        print(form.errors)
    else:
        return render_template('encryption/147cipher.html', title="147Cipher", form=None)
#

does errors need imported?

edgy anvil
opaque rivet
lavish ferry
#

I removed the if POST, though yeah I still don't know how to actually print the errors

edgy anvil
opaque rivet
#

see if that gets anything in your console

lavish ferry
#

Without the else returning the rendered_template, I can't render the template to test if with inputs in the form.

#

One sec...

#

Oh weird

#

It thinks the token is missing

#
{'csrf_token': ['The CSRF token is missing.']}
opaque rivet
#

did you set your env variable CSRF_KEY?

#

os.getenv('CSRF_KEY')

lavish ferry
#

Yes

#
# Pull secret key.
app.config['SECRET_KEY'] = os.getenv('CSRF_KEY')
opaque rivet
#

that's retrieving the env variable, did you actually set it?

lavish ferry
#

Yes CSRF_KEY=key

#

That isn't the actual key but you get it

#

in the .env

opaque rivet
#

hmmm... inspect the page source and see if there's a hidden field with the csrf key

lavish ferry
#

I am not sure how to do that

#

Though I can try...

opaque rivet
# lavish ferry Though I can try...

right click on the page in the browser, inspect element, check the html code for your form. see if there is a hidden input for your csrf key

lavish ferry
#

Oh

#

Well there is a gap where the key should be...

<form method="POST">
    
    <div class="card">
        <div class="card-body">
            <div class="row">
#

This is what should be there:

    {{ form.csrf_token }}
#

Yes, localhost

#

There is this weird thing called wtx-context everywhere

#

Also a weird dashlane thing... which is odd.

opaque rivet
#

hmm, I don't use flask so it's hard to say, but if you don't see any hidden inputs for your CSRF token in the form that's the problem...
are there no errors in your flask server?
might want to check that the SECRET_KEY is actually populated

lavish ferry
#

To be fair I have no idea what I am looking for when it comes to hidden inputs

#

How would I check it is populated

opaque rivet
#

it'll be something like:
<input type="hidden" name="CSRF_TOKEN" value="csrf_token_here"></input>

opaque rivet
lavish ferry
#

Printing it says it is none

#

Fixed it

#

Needed this right before the </form>

<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
#

Also needed this at the start:

#
csrf = CSRFProtect()
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('CSRF_KEY')
csrf.init_app(app)
#

What a nightmare lol

#

Thanks for your help Nicky, I was going crazy. Glad you were here to talk me through where I should focus, was a massive help.

#

๐Ÿ™‚

desert estuary
#

hey everyone

@app.route('/user',methods=["GET","POST"])
def user():
   if "student" in session:
      current_student=Students.query.get(session['student'])
      form=Uploading()
      ext={'.jpg', '.png', '.pdf','.txt'}
      if form.validate_on_submit() and request.method=="POST":
         file=request.files['uploadfile']
         if pathlib.Path(file.filename).suffix.lower() in ext :
            current_path = os.getcwd()
            
            if not os.path.exists(current_path+"/Flaskiproject/static/fileupload",current_student.fullname):
               print(current_path)
               os.mkdir(os.path.join(current_path + "/Flaskiproject/static/fileupload",current_student.fullname))
               uploaded_file=secure_filename(file.filename)
               file.save(os.path.join(current_path + f"/Flaskiproject/static/fileupload/{current_student}",uploaded_file))
            else:
               uploaded_file=secure_filename(file.filename)
               file.save(os.path.join(current_path + f"/Flaskiproject/static/fileupload{current_student}",uploaded_file))
         else:
            flash(" we don't allow this file extension ")
         return redirect(url_for('user'))
   else:
      return redirect(url_for("login"))
   return render_template("User/Homepage.html",student=current_student,form=form)
```py
#

this getting kinda ugly somehow a lot of code and stuff but anyway
im struggling to make this code cleaner anyone please

native tide
#

what would cause a request body to be formatted like this in my packet sniffer

raw compass
wicked pier
#

can someone help me figure out why this is suddenly happening when I try to run using uvicorn main:app?

...
File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
ValueError: source code string cannot contain null bytes
stark tartan
#

Any Javascript library to filers and cropping the video that is uploaded

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @inland copper until 2021-07-18 06:35 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

tardy path
#

How to pass multiple headers in webclient ?

knotty musk
#

Hello

lavish ferry
#

When is it ok for a csrf_token not to expire with a wtf_form

#

Since it disappears with session end anyway.

knotty musk
#

I'm building a simple API using the Flask module, does anyone know how to add an image to it?

lavish ferry
#

Hello!

knotty musk
#

Hi!

lavish ferry
#

You will need to elaborate on what you mean by add an image to it

knotty musk
#

im gonna send the code

#

`import time
import tkinter
import flask
from flask import Flask
from flask import request, jsonify
import flask

app = flask.Flask(name)

app.config["DEBUG"] = False

@app.route('/')
def home():
return "<font color='#00ff00'><h1>Hi baba</h1></font><marquee><font color='#00fa9a'><p>I hope you become better!</p></font></marquee><p>If you viewed this click this button</p><button><a href='http://192.168.100.2:5000/hello'>Click this!</a></button>"

@app.route('/hello')
def hello():
return "<font color='#00ff00'<h2>I hope you get well soon!</h></font><button><a href='http://192.168.100.2:5000/p3'</a></src></button>"

@app.route('/p3')
defp3():
return '3rd page lol'

app.run(host='0.0.0.0')` So basically i want the "p3" to return the code for an image to be displayed on http://192.168.100.2:5000/p3

#

Im pretty new lol

lavish ferry
#

Do this around your code:

knotty musk
#

ok thank you!

lavish ferry
#

When showing it on Discord I should add

#

As far as returning an image, could just add it to the html to my knowledge. Also probably nicer if you use render_template()

knotty musk
#

ok tysm

native tide
#

Hey guys, I have a form in Django and I want to redirect the user to the newly created object after submission, but I get this error:

The view hrm.views.volunteer_create_view didn't return an HttpResponse object. It returned None instead.
Here is my code:

def volunteer_create_view(request):
    form = VolunteerCreateForm(request.POST or None)
    if form.is_valid():
        new_vol = form.save()
        messages.success(request, 'Volunteer created sucessfully')
        return HttpResponseRedirect(reverse('hrm:person', args=(new_vol.id)))
uneven mango
#

I have learned python

#

Now i wanna start

#

Web development

#

So which one will be good

#

Flask or django

#

I know difference between flask and django but i just cant get myself to decide

versed python
versed python
#

Just choose one and go

#

You'll probably end up learning both

native tide
uneven mango
versed python
obsidian steeple
uneven mango
#

Oh ok

knotty musk
#

I installed Django but when i want to start a project it says that the command "django-admin startproject mysite" is unknown

mint siren
#

you have to make a virtualevnviroment

mint siren
mint siren
uneven mango
#

I see ok

#

Thanks

mint siren
#

i'd suggest flask for apis tho

elder nebula
#

Why is this starting week on wednesday? Appointment(date__week_day=date.weekday())

glossy scroll
#

Using django 3.2
should i do this or not?

#

or should i just pass my object in the view logic as context

elder nebula
#

You should do as much on views.py as you can

glossy scroll
#

Any reasons besides readability

#

Not to sound ignorant but is there any hits on performance ?

elder nebula
#

Django is designed in a way on purpose that you have to do most of the stuff on views.py because it makes the app more secure

#

Templates are served for everyone so it's more vunerable

glossy scroll
#

oh

#

so how much flexibility do i have with the request object in the template context

elder nebula
#

you have all the same request things that template has

glossy scroll
#

i cant understand what you're trying to say

next comet
#

He means that its better to put that thing in the context so the template doesn't involve the logic to call it

#

I guess

elder nebula
#

Yes, because html templates are unsecure and views.py is made to do the logic for you

glossy scroll
#

oh i get it now

#

thanks

hardy laurel
#

Hello. I'm using Wagtail and I want to create a page with custom parametrized route

#

Like /something/4

#

currently I do this :

def Success(request, year):
    name = {
                'resp': year,
            }
    return render(request,"response/response_page.html",name)

#

With

urlpatterns = [
    path('resp/<int:year>', views.Success),
]
#

which works, shows the page but doesn't show the wagtail page with content modified from the CMS, just an empty HTML

#

because the Slug is equal to resp in wagtail

dusk portal
#
def login(request):
    if request.method=='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        user=authenticate(username=username,password=password)
        if user is not None:
            return HttpResponseRedirect('/')
        else:
            return render(request,'users/login.html')
    return render (request,'users/login.html')``` idk why but when i'm using the login panel and enter correct password (of any user ) so it  do not works but if i enter id password of admin there that works
#
from django.contrib.auth import authenticate
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User 
``` ig error can be in 1st import cez idk authenticate
#

umm

opaque rivet
#

@dusk portal are your users stored in the User model?

#

@glossy scroll just for readability sake, keep most if not all of the logic in the view.

glossy scroll
#

so its only readability?

opaque rivet
#

Yeah - whether you're accessing data from the request in the view then passing it to your template or accessing request directly from the template, there is no difference. It's just readability, and to debug an issue it helps having it all in one place

#

It's not "more vunerable" as someone said.

compact glacier
#

hello guys, working on Django project and sending to template dict that have 1 item - list of dicts, trying to parse it in template and get info but nothing works (

how i send to template:

    # db_worker.write_to_db()
    data = db_worker.read_db(1)
    dic = {'data': data}
    return render(request, 'main/blocks.html', dic)```

what contains *data*:
```[{"hash":"384f3e42b8e26443bc1087a0387827146a41f9d3ef663a7d7eda82c927e78bf2","height":"315012","timestamp":"1624372128","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"bcf54ece598e7def8fedfea23c2f4cce7bd2d1ec35351fe9f4d8523ac2fa26de","height":"315011","timestamp":"1624372016","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"aef7e142303e54c08f885965877199f6af6ee4da8687eed8505e6a4fb41ef446","height":"315010","timestamp":"1624371920","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"50ca063a86f434ce08e7e8537808662a0e782935eb5e72bdb506c5e32b5a3391","height":"315009","timestamp":"1624371808","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"f592d181a1bec34566509152d1e0e5ac8531ae23b5a91e6bec27ade3001e69bf","height":"315008","timestamp":"1624371648","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"}]```

part of HTML template:
```<table>
        <tr>
            <th>height</th>
            <th>hash</th>
            <th>timestamp</th>
            <th>miner</th>
            <th>transactionsCount</th>
        </tr>
        {% for val in dic.data %}
            {% for i in val.values %}
                <tr>
                    {{height}}
                </tr>
                <tr class="even">
                    {{hash}}
                </tr>
                <tr>
                    {{timestamp}}
                </tr>
                <tr class="even">
                    {{miner}}
                </tr>
                <tr>
                    {{transactioncount}}
                </tr>
            {% empty %}
                <li>Sorry</li>>
            {% endfor %}
        {% endfor %}
    </table>```
#

but it not work

#

tried couple of methods

opaque rivet
compact glacier
opaque rivet
#

well that's not the only thing you have to change, your logic here is incorrect, try to fix it:

{% for i in val.values %}
                <tr>
                    {{height}}
                </tr>
                <tr class="even">
                    {{hash}}
                </tr>
                <tr>
                    {{timestamp}}
                </tr>
                <tr class="even">
                    {{miner}}
                </tr>
                <tr>
                    {{transactioncount}}
                </tr>
compact glacier
opaque rivet
#

syntax and logic

compact glacier
#

im pretty new in thes sphere

opaque rivet
# compact glacier im pretty new in thes sphere

Ok you're looping through each value in the dictionary:
{% for i in val.values %}
but then you're trying to access variables that were never defined?

<tr class="even">
                    {{hash}}
                </tr>
                <tr>
                    {{timestamp}}
                </tr>
                <tr class="even">
                    {{miner}}
                </tr>
                <tr>
                    {{transactioncount}}
                </tr>
compact glacier
#

{{hash}} for example isnt key that im just call ?

opaque rivet
#

If you simply want to loop through the values:

{% for i in val.values %}
  <tr>
    {{i}}
  </tr>
{% endfor %}
opaque rivet
#

also, how can you even access keys? You're looping through val.values, which are the values not the keys of the dict

compact glacier
#
    try:
        info = api_requests.req_info()
        return render(request, 'main/index.html', info)
    except:
        return HttpResponse("Something went wrong")```


```    <ul><h3>
        <a href="/admin" ><h1>Admin page</h1></a>
        <a href="/blocks" ><h1>Blocks page</h1></a>
        <br><br>
        <li>height: {{height}}</li>
        <li>supply: {{supply}}</li>
        <li>circulatingSupply: {{circulatingSupply}}</li>
        <li>netStakeWeight: {{netStakeWeight}}</li>
        <li>feeRate: {{feeRate}}</li>
        <li>dgpInfo: {{dgpInfo}}</li>
    </h3></ul>```

Here im not defining anything, just sending dict and then pulling keys
compact glacier
opaque rivet
compact glacier
compact glacier
#

thats why im really confused, why it not works

opaque rivet
#

does that work?

compact glacier
#

but in that case im sending only the dict as JSON

sudden gulch
#

hey i have a questio
django default db is sqlite and all its authentication tables uses it so if i change my db to mongo can i still able use default authentication tables

compact glacier
#

and made model

    hash = models.CharField(max_length=100)
    height = models.CharField(max_length=9)
    timestamp = models.CharField(max_length=50)
    miner = models.CharField(max_length=100)
    transactioncount = models.CharField(max_length=3)```
sudden gulch
opaque rivet
#

Ok, I'll explain why:

With the code that works, you're passing the context info, let's say it's this:

info = {
  height: x,
  supply: y,
  circulatingSupply: z
}```

In your template, when you do `{{height}}` you are accessing the key `height` in your context, so that will work. It will show `x` in the template.

In your non-working code, your context is now this:

```py
{
  data: {
    height: x,
    supply: y
  }
}```

so doing `{{height}}` is no longer valid. You have to do `{{data['height']}}`
compact glacier
#

then pulling and pushing with these code:

from . import api_requests
import json


def write_to_db():
    blocks = api_requests.req_block()
    conn = None
    try:
        conn = psycopg2.connect(host="localhost", database="crypto", user="postgres", password="admin")
        cur = conn.cursor()
        for element in blocks:
            cur.execute(f"INSERT INTO main_block (hash, height, timestamp, miner, transactioncount) VALUES"
                        f" ('{element['hash']}', '{element['height']}', {element['timestamp']},"
                        f" '{element['miner']}', '{element['transactionCount']}');")
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()


def read_db(offset):
    conn = None
    try:
        conn = psycopg2.connect(host="localhost", database="crypto", user="postgres", password="admin")
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

        cur.execute(f'SELECT * FROM main_block OFFSET {offset} LIMIT 5;')
        fetch = cur.fetchall()
        dic = {}
        data = []
        for i in fetch:
            dic['hash'] = i['hash']
            dic['height'] = i['height']
            dic['timestamp'] = i['timestamp']
            dic['miner'] = i['miner']
            dic['transactioncount'] = i['transactioncount']
            data.append(dic.copy())

        return data

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
sudden gulch
#

modelforms

#

all the things work same?

opaque rivet
compact glacier
sudden gulch
opaque rivet
# compact glacier in my case its ``` {'smth': data} data: [{...}, {...}] ```

I know... I'm telling you why this doesn't work, you can change it so it starts to work. I'm not trying to give too many hints here...

{% for val in data %}
            <tr>
                {{height}}
            </tr>
            <tr class="even">
                {{hash}}
            </tr>
            <tr>
                {{timestamp}}
            </tr>
            <tr class="even">
                {{miner}}
            </tr>
            <tr>
                {{transactioncount}}
            </tr>
        {% endfor %}
opaque rivet
sudden gulch
opaque rivet
opaque rivet
#

Ok, so you just need to change it so you're accessing the height key of each item. Here's an example:

{% for key, value in data.items() %}
            <tr>
                {{key}}: {{value}}
            </tr>
compact glacier
#
            <tr>
                {{data['height']}}```

tried this one, and got error
```django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['height']' from 'data['height']'
#

oh

#

with {% for val in data %} <tr> {{val['height']}} </tr>
these one not same

compact glacier
#

got error

#
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '["height"]' from 'val["height"]'```
opaque rivet
#

what is your context again?

compact glacier
#

the thing is that even when im trying just to print val it shows nothing

compact glacier
opaque rivet
#

yeah, so what is the context you are passing to your template?

compact glacier
#

[{"hash":"384f3e42b8e26443bc1087a0387827146a41f9d3ef663a7d7eda82c927e78bf2","height":"315012","timestamp":"1624372128","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"bcf54ece598e7def8fedfea23c2f4cce7bd2d1ec35351fe9f4d8523ac2fa26de","height":"315011","timestamp":"1624372016","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"aef7e142303e54c08f885965877199f6af6ee4da8687eed8505e6a4fb41ef446","height":"315010","timestamp":"1624371920","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"50ca063a86f434ce08e7e8537808662a0e782935eb5e72bdb506c5e32b5a3391","height":"315009","timestamp":"1624371808","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"},{"hash":"f592d181a1bec34566509152d1e0e5ac8531ae23b5a91e6bec27ade3001e69bf","height":"315008","timestamp":"1624371648","miner":"BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az","transactioncount":"2"}] list of dicts

compact glacier
#

and all this stuff is packed in a dictionary

#

Maybe theres some easier methods to send this stuff to page instead as one of params of render

#

but i dont know

opaque rivet
#

well you can try:

{% for item in data %}
  {% for value in item.values() %}
    <tr> {{ value }} </tr>
  {% endfor %}
{% endfor %}

the previous example should work, print the type of your data to ensure it's a list and not str

opaque rivet
#

ok, try above example

compact glacier
#
            {% for value in item.values %}
                <tr>
                    {{value}}
                </tr>
                <tr class="even">
                    {{value}}
                </tr>
                <tr>
                    {{value}}
                </tr>
                <tr class="even">
                    {{value}}
                </tr>
                <tr>
                    {{value}}
                </tr>
            {% endfor %}}
        {% endfor %}```
#

made this one, not shows anything

opaque rivet
compact glacier
#

Keep in mind that for the dot operator, dictionary key lookup takes precedence over method lookup. Therefore if the data dictionary contains a key named 'items', data.items will return data['items'] instead of data.items(). Avoid adding keys that are named like dictionary methods if you want to use those methods in a template (items, values, keys, etc.). Read more about the lookup order of the dot operator in the documentation of template variables.

https://docs.djangoproject.com/en/3.2/ref/templates/builtins/

#

from official documentation

opaque rivet
#

ah ok

#

weird... that should work.
maybe just list what's in your data key?

{% for item in data %}
  {{ item}} 
{% endfor %}
opaque rivet
compact glacier
#

well found an mistake

#

and fixed it

#
    data = db_worker.read_db(1)
    sdata = {'first': data}
    return render(request, 'main/blocks.html', sdata)```

i was changing name of key in dict, so the screenshot above is the result of this code:

     ```   {% for item in first %}
            {{item}}
         {% endfor %}```
near bison
#

I am trying to implement a system where i have a FastApi backend. And It's needs to perform some operation outside the request response process.

Ex :

  • I have an endpoint that accepts some data
  • I need to add that data into some list (persistent)
  • As long as the queue is not empty i need a particular process to run (separate thread?). This process may also contain websockets to update the front_end with what is going on
  • if the list gets empty the process should stop, but should start running again if anything gets added to list

How do i implement this in a uvicorn and fasapi compatible way ?
Thank you

compact glacier
wooden ruin
#

anyone know if there's a difference between using UUID or just autoincrement for storing table ID's?

sinful narwhal
#

how much python do i need to do to start django

compact glacier
sinful narwhal
#

any video series

#

i know it

#

but cant really understand stuff such as decorators

#

and stuff

#

and poli

split steeple
#

The one by Corey Schafer is a good starting point

#

It's the one I used to get my start

compact glacier
lavish prismBOT
#

@fleet drum Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!

split steeple
next comet
gray tree
cerulean mortar
#

can docker be used to send commands between containers? I'm developing a deep learning web app that processes videos and i need to figure out a way to kickstart the deep learning algorithm once the user has uploaded their files on the front end

opaque rivet
#

@cerulean mortar they can send http requests to eachother, so yes in that sense

#

@cerulean mortar you using CNNs?

compact glacier
gentle kestrel
#

pls help this error when i type django-admin and

compact glacier
gentle kestrel
compact glacier
#

like django-admin startproject projectname

gentle kestrel
compact glacier
#

did u installed django via pip?

gentle kestrel
#

yeah

compact glacier
#

python version?

gentle kestrel
#

3.4

compact glacier
#

try to upgrade to 3.6 and later

#

it may cause the problem

gentle kestrel
compact glacier
#

@opaque rivet thanks a lot for your help.

I changed a bit code. Now it looks like that:

        <tr>
            <th>height</th>
            <th>hash</th>
            <th>timestamp</th>
            <th>miner</th>
            <th>transactionsCount</th>
        </tr>

        {% for item in first %}
                <tr>
                    <td>{{item.height}}</td>
                    <td>{{item.hash}}</td>
                    <td>{{item.timestamp}}</td>
                    <td>{{item.miner}}</td>
                    <td>{{item.transactioncount}}</td>
                </tr>
        {% endfor %}
    </table>```

and it works.
next comet
#

ffs is there any way that i can make forms.RadioSelect widget to appear as checkbox and not that ugly circular buttons?

whole crow
next comet
#

yeah didn't think of that, but my problem is that I have a images, that have a category, but i can't make an image have a more than one category and have to work with only 1 category per image, so my idea was to use a widget and appear as checkbox

whole crow
#

you want it to work like a radio button, so why not present it as a radio button?

next comet
#

i can make it work with checkboxes if i override the CheckboxSelectMultiple but it will be buggy af probably

#

well best case is if I can make an image have 1 or more categories and be able to choose this in the form when posting the image

whole crow
#

you haven't said why you want it to look like a checkbox

next comet
#

well i like it better, but if we put that aside, i just wanna learn if there is any way I can make it to look

whole crow
#

sorry, i don't know if there's a way

next comet
#

it's okay

opaque rivet
# next comet it's okay

you can apply custom classes to it, to modify its look. Generally though when using premade modules from django you don't get a lot of customization. It's best to DIY.

ivory bolt
#

hey everyone! Been a while and I'm back with another problem!!

#
class Poll(models.Model):
  question = models.CharField(max_length=250)
  creator = models.CharField(max_length=100)
  pub_date = models.DateTimeField(auto_now_add=True)
  description = models.CharField(max_length=120)
  #options --> point to options database table
  #option_votes --> point to options database table

  def recent(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  

  def __str__(self):
    return self.question

  def get_absolute_url(self):
      return reverse("polls:poll-detail", kwargs={"pk": self.id})

class Choice(models.Model):
  poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
  option = models.CharField(max_length=200)
  option_votes = models.IntegerField(default=0)

  def __str__(self):
    return self.option

Seeing that each question, or, Poll object has a choice_set, I want to order the results for any object by option_votes

#

I've been trying to do this directly via the template, but it doesn't work.

storm roost
meager anchor
native tide
#

Not sure if this is the right place to ask but does anyone have any recommendations for web hosts?

Just looking for something I can host a personal site as well as python projects reliably and affordably.

meager anchor
#

netcup is very cheap and reliable for me, i would recommend it. digitalocean is rather pricy, i've also heard good things about Hetzner

native tide
#

@meager anchor thanks for that, i don't have much experience with hosting

real rapids
#

did flask built a new security

#

cause its asking for crsl

#

or something like that

thorn igloo
stable coral
#

is it possible that app.root_path could be giving me the path to a similarly named directory?

#

i mean that doesn't even make sense but idk whats up with my code

#

i have a blog that i'm creating by following a tutorial, and a separate blog, and in my separate blog its selecting a profile pic thats in the directory of my first blog

#

both profile pic directories have the same name but I don't why that should matter

#

since each blog is in a completely different folder

real rapids
near bison
#

what type of file is it ?

tropic vault
#

Hi all, for structuring Django projects, anyone know what should be in the "Service" folder?

shell turtle
#

Can anyone tell me how can I replace email with phone number in django custom user model??

terse vapor
#

can someone explain how I can get the amount user that register the website in each month with flask?

lavish prismBOT
#

Hey @ivory bolt!

It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.

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

#

Hey @ivory bolt!

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

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

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

https://paste.pythondiscord.com

native tide
#

how do i debug HTTP ERROR 500

inland oak
#

in order to receive more detailer error

buoyant shore
#

Hey how do i deal with python django UserCreationFrom not showing a validation error

mental veldt
#

guys quick question. Can a website developed with django channels on backend and react on frontend have a maximum number of clients it can handle simultaneously? If so what could be the maximum?

thorn igloo
near bison
thorn igloo
thorn igloo
thorn igloo
fathom rampart
#

Hi there. I am not sure if this is directly related to web dev, but it's worth a shot asking.

I'm making a Django website for people to bulk OCR apps, So They can have multiple OCR "Jobs" which is the task of OCRing a folder contaning documents. An user can have multiple OCRs together too. Now, I have a file which does python3 ocr.py <folder-path> and I need to run it as another task whenever any user asks for it.

My questions are,

  1. How to I spawn a new process to run it everytime whenever user makes a new task from the website?
  2. How do I control each separate task as needed, such as kill, stop or restart whenever the user clicks on those buttons on the website
  3. How do I get the logs from the process and display to the user on the site?
  4. How do I keep a bound on max number of tasks that can be created in total?

Please guide me, I'm really confused about these, but I want to make this to help people do bulk OCR easily through a Intuitive web UI. Here's a image of code for the Job model for django that I made. I need to initiate tasks, control them, get logs as needed and display on website.

real rapids
sturdy sapphire
#

@paper vigil you need to do this to your settings file in django

#

by adding the middleware t o your existing ones

#
MIDDLEWARE = [
    # SecurityMiddleware must be listed before other middleware
    'django.middleware.security.SecurityMiddleware',
    # ...
]

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
dusk portal
#

anyone's up

#

so i'm making a e-commerce store and i want to give user option to add thier own products if they r logged in (as a a user) so how know which user added a new product to shop

#

and if i use OneToOneField with user , so when user will add thier own product it show's profile of all the User's in the site (as i saw in django admin ) so for example my user is xyz but when i click on add product i can access all 5 user's option and the particular i choose will be rendered

#

umm very complex

sage bluff
#

guys i am trying to import the css file from static folder in flask but its not working. someone please help me

surreal portal
#

I have a problem with my DRF ListSerializers:

AssertionError at /api/v1/countydata
`child` is a required argument.
#

Here's how my serializer looks like

#
class CountySerializer(geo_serializers.GeoFeatureModelListSerializer):
    index = serializers.IntegerField()

    class Meta:
        model = County
        geo_field = "geometry"
        fields = "__all__"
#

And Idgi. On other geo serializers it does it correctly but not this one for some reason

mint siren
thorn igloo
#

not sure if it's double or a single curly bracket

finite ledge
#

Hi

#

I'm trying to create plugin for Django CMS that having views function but unfortunately I don't know how can point my views function with plugin

#

I'm trying to call my views function with the help of plugin

#

But it not working

finite ledge
#

<@&787816728474288181>

jagged lark
#

Hello, please do not ping random role to ask for help

finite ledge
#

Sorry

#

Can u please me help regarding this

opaque rivet
#

@finite ledge well you'll have to ask your question with some technical detail for us to be able to help

hardy laurel
#

Is there any localstorage i can use in Django

#

I'm not using render(request,...)

#

User navigates to raw URL

#

But I need to retrieve data from previous view

dusk portal
#
so i'm making a e-commerce store and i want to give user option to add thier own products if they r logged in (as a a user) so how know which user added a new product to shop
and if i use OneToOneField with user , so when user will add thier own product it show's profile of all the User's in the site  (as i saw in django admin ) so for example my user is xyz but when i click on add product i can access all 5 user's option and the particular i choose will be rendered
#

noone replied

#

@opaque rivet

opaque rivet
#

@hardy laurel http requests are meant to be stateless, so they should contain all of the information required within the request without relying on any previous requests.

Data can be transferred as cookies, e.g.:
You can save the user's token in a cookie, then use that to retrieve account information.

You can also save formdata within the body of the request.

You can also include data within the query string of the URL.

#

"Local storage" is clientside only

dense slate
opaque rivet
#

@dusk portal a OneToMany relationship is probably better... so one user can make multiple products

dusk portal
#

without any reference

#

i have to apply some stuff in this like

#

search bar with searches in whole models ( all models all types )

terse vapor
dense slate
#

This in Django?

terse vapor
#

flask

dense slate
#

Not sure what the query looks like in Flask, but basically just get all users, filtering for anything beyond the specific date.

terse vapor
#

ok ok

lavish prismBOT
#

Hey @knotty musk!

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

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

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

https://paste.pythondiscord.com

knotty musk
#

everytime i do "python manage.py runserver this comes up, and main.urls does have patterns btw, so what could be the issue?

#

this is django btw

#

help

#

pls

#

pls

#

help

dense slate
knotty musk
#

ok

lavish prismBOT
dense slate
#

just the urls part

knotty musk
#

from django.urls import path

from . import views

urlpatters = [
path("", views.index, name="index"),
]

#

here

#

im new so keeping stuff simple lol

dense slate
#

Are you following a tutorial?

knotty musk
#

yeah

dense slate
#

that says urlpatters btw

#

instead of patterns

knotty musk
#

OH XD thank you lmaoooo

#

hahaha

#

thank you

dense slate
#

welcome

next comet
#

guys do you have any idea why media queries using css doesn't apply ? is there any problem django rendering them

#

weird thing is i made it work just as i want and then just added an mt-4 class from bootstrap and now it doesn't render im talking specifically about the column-count: 1; css property, not being read correctly

#

any insight will be helpful

thorn igloo
next comet
#

yes in static file with .css extension

thorn igloo
next comet
#

I have 3 columns with pictures in some fancy grid display for desktop and when it's for little screens like 480 i want to make it display only 1 column

#

i mean i have other css as well but i think this is what doesn't display

#

im not sure if its a cache problem, even though i have disabled it

thorn igloo
next comet
#

yeah i have a template that is using the bootstrap but i think mainly it uses the custom css

#

idk how can i show you the css code in here ? if i put it in `` will it show it as a code

#

im new to this discord thingy ๐Ÿ˜„

thorn igloo
#

bootsrap uses css grid and flexbox for their layouts. basically they have their own set of properties you can use to change how content is structured. column-count doesn't really affect that

violet briar
#

what's the difference between WebRTC and Websockets? and why did discord choose webRTC? and when it is better to use webRTC for a chat app?

next comet
finite ledge
#
from django.conf import settings
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.urls import include, path
from django.urls.conf import re_path

admin.autodiscover()

urlpatterns = [
    path("sitemap.xml", sitemap, {"sitemaps": {"cmspages": CMSSitemap}}),
    re_path("meri/", include("merger.urls"))
]


urlpatterns += i18n_patterns(path("admin/", admin.site.urls), path("", include("cms.urls")))

# This is only needed when using runserver.
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)```
#

This is template render with the help of plugin

faint aspen
#

whats the best web framework if i wanted asp.net like class controller?

finite ledge
#

But here is some issue how can I call views function from plugin

#

@opaque rivet

native tide
#

Does anyone know why i can only chat numbers and not letters anymore?```php
<?php
include "/connect/db.php";
session_start();

$text = $_POST['text'];

if(isset($_SESSION['username'])){
if (strlen($_POST['text'] == 0)){
//$_SESSION['error'] = "title is emtpy!";
echo 'Please enter text!';
die();
}
else{
$text_message = "<div class='msgln'><span class='chat-time'>".date("g:i A")."</span> <b class='user-name'>".$_SESSION['username']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
}
?>```

sharp basin
#

I am trying to learn CSS and HTML can anybody be of any help?

next comet
#

guys do you have any good resources for django signals, im trying to understand the flow mainly pre_save and post_save how do they work and so on

split steeple
sharp basin
#

@split steeple

#

thank you for getting back to me : )

sharp basin
#

anyway i am looking to learn the basics and later advance HTML and CSS for website building

#

currently i have figma templates and i have to export them

#

and i have 0 knowledge of HTML or CSS

#

and i have a 10 day deadline

inland oak
#

a bit nuts

inland oak
#

literally from zero... you would have to walk really fast though

sharp basin
#

Thanks

#

anyway what about figma exportation?

inland oak
#

what about it? ๐Ÿ˜‰ I saw figma only from afar

#

I think you can export pictures out of it

#

and font styles

sharp basin
#

ok

#

and is there a diffrence in coding or learning material

#

or does the book cover it all

inland oak
#

not clear question

sharp basin
#

elaborate

inland oak
#

rephrase your question in a more meaningful one

sharp basin
#

Understood

broken mulch
#
@app.route("/db")
def webdb():
  ip_address = request.remote_addr

would this give me their requesting IP address or do I have to write

def webdb(request):
broken mulch
sharp basin
#

If i were to understand and grasp the knowledge to which that materialized confinment of knowledge (a book) witholds will i face any difficulty exporting a figma (or should i say ligma joe_maverick ) webite template.

#

@inland oak

broken mulch
#

btw what are cookies?

#

i don't understand why people need it

inland oak
sharp basin
#

@broken mulch a cookie file is saved to your PC, Mac, phone or tablet. It stores the website's name, and also a unique ID that represents you as a user. That way, if you go back to that website again, the website knows you've already been there before.

#

@inland oak

sharp basin
#

how am i to grasp said skill

opaque rivet
#

Pretty sure figma gives you the css for what you've created, you just need to sort out the html then copy/paste

split steeple
inland oak
#

It makes things much easier if it is so

sharp basin
#

Thanks @opaque rivet @split steeple @inland oak for your input, and assitance it is very much appreciated :))))))

inland oak
sharp basin
#

ok thanks

broken mulch
#

TypeError: home() missing 1 required positional argument: 'request'

inland oak
broken mulch
opaque rivet
#

Iirc with flask request is accessible in the function due to the decorator, it's not required as a arg

broken mulch
#

but the IP address doesn't match

opaque rivet
#

What's the issue again?

inland oak
#

oh yeah

broken mulch
#

im trying to fetch request.remote_addr

inland oak
#

request is not needed in function args

broken mulch
#

but it's the same every time

inland oak
#
from flask import request

is used instead

broken mulch
#

i request the website

#

im trying to return 429

opaque rivet
#

@broken mulch google is your best friend

broken mulch
#

when an ip address reached their limit

#

ok

#

does anyone know if I can connect to my website DNS using flask

#

or do I have to use django

opaque rivet
#

This is probably another moment where google is your best friend...

untold hull
#

can someone help me get set up with flask? i installed it and made the starter code but "flask run" says could not locate a flask application

stable coral
#

nvm could you just send your code

untold hull
stable coral
#

Yes @untold hull

untold hull
#

then on the console "set FLASK_APP=hello.py" and "flask run"

#

but it won't run

#

says "could not locate Flask application" anyone know the fix?

elder nebula
#

how do I change from django.utils import timezone to my timezone? I've added my local timezone in the settings.py, but still it shows time in UTC. in Django

#

oww....

bitter thunder
#

hey guys hows it going I was wondering if anyone has experience with flask-appbuilder and if I can pick their brain about it

#

for context I need to extend their security model to make a custom authentication function and I can't seem to find the right way to do it in the docs

ember adder
#

Django: What's the proper way to hash imported passwords with Django-import-export? I'm trying to use make_password, but it says Invalid password format or unknown hashing algorithm.

mortal mango
#

I'm getting this error in Django.

Internal Server Error: /app/oauth2/login/redirect
Traceback (most recent call last):
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Internet\Desktop\Programming\Discord\exo_website\website\exo_dashboard\dashboard\home\views.py", line 188, in discord_login_redirect
    return redirect("/app")
  File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 126, in login
    request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
AttributeError: 'QuerySet' object has no attribute '_meta'
[19/Jul/2021 14:20:18] "GET /app/oauth2/login/redirect?code=code HTTP/1.1" 500 79016

This is the code

def discord_login_redirect(request, *args, **kwargs):
    code = request.GET.get("code")
    exchange_user = exchange_code(code)
    discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user)
    login(request, discord_user_auth)
    return redirect("/app")

I believe the error is originating from login(request, discord_user_auth). Does anyone know what this error means?

next comet
#

login takes as a 2nd parameter the user

#

try with login(request, request.user)

mortal mango
#

discord_user_auth is the user

next comet
#

ah sorry idk the Backends yet

mortal mango
#

I have a custom authentication backend so instead of request.user I have to use discord_user_auth

next comet
#

sorry i cant be of any help ;/

#

unless could it be something from the redirect()

split steeple
#

that's what i'm thinking too

#

that or GET.get could be GET.filter

untold hull
#

"could not locate Flask application" anyone know the fix? i tried FLASK_APP=hello and flask run

bitter thunder
untold hull
#

that's the only file in the folder

bitter thunder
#

if its set up right you might be able to get away with python ./hello.py I guess

untold hull
#

what's weird is i got it working a moment ago

#

restarted the ide and back to square one

bitter thunder
#

can you show what is in the file

dusk portal
#

anyone's up

native tide
#

Hi, hope I'm not disturbing but I'm trying to put some logo credits under some details and summaries tags to be used on github readme profile but for some reason the summary doesn't end up being the summary and then it gets linked to an a tag up top

untold hull
#
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "<p>This is the homepage.</p>"

@bitter thunder

dusk portal
#

any django dev i mean

native tide
dusk portal
native tide
#

thanks

native tide
#

Right now the preview for my github readme looks like this

dusk portal
#

umm

native tide
#

but I want "icons sources" to be in the place of "details" as expected but it became a bullet point

dusk portal
#

ohh

#

umm name doens't matter btw

native tide
#
<!--- A tag with the link --->

<a href="https://www.youtube.com/channel/UC" target="_blank"><img align="center" alt="Youtube" width="48px" src="https://img.icons8.com/color/48/000000/youtube-play.png" />
</p>

<details>
  <summary>Icons sources</summary>
  <ul>
   <li><a href="https://icons8.com/icon/13441/python">Python icon by Icons8</a></li>
   <li><a href="https://icons8.com/icon/20909/html-5">Html 5 icon by Icons8</a></li>
   <li><a href="https://icons8.com/icon/21278/css3">CSS3 icon by Icons8</a></li>
   <li><a href="https://icons8.com/icon/108784/javascript">JavaScript icon by Icons8</a></li>
   <li><a href="https://icons8.com/icon/20906/git">Git icon by Icons8</a></li>
   <li><a href="https://icons8.com/icon/9OGIyU8hrxW5/- visual-studio-code-2019">Visual Studio Code 2019 icon by Icons8</a></li>
   <li><a href="https://upload.wikimedia.org/wikipedia/commons/4/4f/Icon-Vim.svg">Wikipedia</a></li>
   <li><a href="https://icons8.com/icon/19318/youtube-play-button">YouTube Play Button icon by Icons8</a></li>
   <li><a href="https://icons8.com/icon/63807/website">Website icon by Icons8</a></li>
  </ul>
</details>
native tide
native tide
#

No idea why

dusk portal
#

drom all the places

#

simple

#

oh

native tide
#

Yeah I tried that

#

But then

#

it's no longer a toggle thing

#

it just becomes bullet points

#

So I need the detail I think

#

If I remove all the a tags though that links to my youtube channel, or other websites, then it works fine

#

But then I'll only be left with the sources ofc :/

opaque rivet
# native tide
<li><a href="https://icons8.com/icon/13441/python">Python icon by Icons8</a></li>

This creates a bullet point, and the anchor tag will redirect the user to the href link... isn't that expected behavior?

native tide
native tide
#

Icon sources is not the title of the toggle thing

opaque rivet
#

toggle thing?

native tide
#

and what happens is that it will grab the most bottom a tag that contains a link

dusk portal
native tide
#

This is the full preview rn

#

So rn, icon sources which is the summary

opaque rivet
#

hmmm... I'm not really sure, is it possible to build your .md file solely with html?

native tide
#

will be linked to my youtube channel and if I remove the youtube icon + the youtube a tag then it'll be the website

bitter thunder
#

the default for flask is app.py

native tide
#

I thought it was only markdown

untold hull
# bitter thunder checking 1 sec

yeah i knew that, but the problem was vscode was using powershell rather than cmd, i figured it out when i tried it on cmd and it worked, i switched vscode's terminal to cmd and now it works, thanks

native tide
#

But it seems to support html

opaque rivet
#

maybe get rid of the <details>/<summary> tags?

native tide
#

like I added it so that if someone wants to use those icon

#

They can just toggle the button beside "details" and see the icons

#

rather than have it in plain sight

dusk portal
#
def register(request):
    if request.method=='POST':
        first_name=request.POST.get('first_name')
        last_name=request.POST.get('last_name')
        email=request.POST.get('email')
        username=request.POST.get('username')
        password1=request.POST.get('password1')
        password2=request.POST.get('password2')
        if password1==password2:
            if User.objects.filter(username=username).exists() and User.objects.filter(email=email).exists():
                print('Already taken')
            new_user=User(first_name=first_name,last_name=last_name,email=email,username=username,password=password1)
            new_user.save()
            return HttpResponseRedirect('/')
    return render(request,'users/register.html')``` this is my register  which saves to the user model (register) so when i'm filling form from html so when i saw user which i created by html so it was saved but when i focussed on the difference if  i add any user directly by django admin so it's login is working fine but the other which i render by html in that i noticed ```Invalid password format or unknown hashing algorithm.
Raw passwords are not stored, so there is no way to see this userโ€™s password, but you can change the password using this form.

Personal info```
dusk portal
#

it's saving to user db but while im doing login so it's not working but when i create user by django admin and then do login

#

it's workin

#

issh

#

my mind

#

explodes !

opaque rivet
#

well, print what the password is and inspect its format

dusk portal
#

ohh

dusk portal
#

print(password1)
print(type(password1))

cerulean dock
#

hello, i'm having a issue in my django app:

``python
from django.contrib.auth import get_user_model
user = get_user_model()
user.objects.get(user="toto")

``
it throws this error : TypeError: all() missing 1 required positional argument: 'self'

dusk portal
#

when im doing from admin it's working

#

it shows

#

problem is in

#
def register(request):
    if request.method=='POST':
        first_name=request.POST.get('first_name')
        last_name=request.POST.get('last_name')
        email=request.POST.get('email')
        username=request.POST.get('username')
        password1=request.POST.get('password1')
        print(password1)
        print(type(password1))
        password2=request.POST.get('password2')
        if password1==password2:
            if User.objects.filter(username=username).exists() and User.objects.filter(email=email).exists():
                print('Already taken')
            new_user=User(first_name=first_name,last_name=last_name,email=email,username=username,password=password1)
            new_user.save()
            return HttpResponseRedirect('/')
    return render(request,'users/register.html')``` here
#

or html

opaque rivet
#

have you googled your error

dusk portal
#

yes

#

ofc ihave

untold hull
#

for backend web, should i go for nodejs instead of python?

calm plume
#

Both are great options

untold hull
calm plume
#

Not really

#

A bunch of really big companies use Netflix for their backends, such as Instagram and Netflix

untold hull
#

do they use flask or django?

calm plume
#

And I've heard that Python web dev jobs are rising, but it depends on your location

calm plume
untold hull
#

it probably is but it's still noticeably lower than its peers

calm plume
#

But I doubt Netflix uses Flask

royal musk
#

Hi, I'm trying to do something with django and ran into a problem ... I can't fire up my local server ...
https://pastebin.com/8VSXztZS
I do everything according to https://docs.djangoproject.com/en/3.2/intro/tutorial01/ and the nth time I check everything and I don't see an error anywhere ...

ember adder
# untold hull i heard python isn't great for employment regarding webdev

In the end for programming jobs, companies look for people able to learn things. Yes specific positions will ask for specific stack, but I've often seen companies hiring people for their talent and willing to pay you to learn technologies (like a senior I know who was hired for a Kubernetes architect, but never did kubernetes but they know he could learn it and pay very well)

compact glacier
#

hey guys, working on django project,
in db(postgresql) i need to sync with api(), and im calling to 5000 objects in api, then adding to db.

So, what i need, compare last item in db (row in special column) with parsed items in json, OR
maybe other ways to do it by built-in methods.

#

i tried this:

    query = requests.get(f'https://bcschain.info/api/recent-blocks?count=3')
    checkedQuery = compareItems(query.json())
    for i in range(len(checkedQuery)):
        objects = Block.objects.create(height=checkedQuery[i]['height'],
                                       hash=checkedQuery[i]['hash'],
                                       timestamp=checkedQuery[i]['timestamp'],
                                       miner=checkedQuery[i]['miner'],
                                       transactioncount=checkedQuery[i]['transactionCount'],
                                       interval=checkedQuery[i]['interval'],
                                       size=checkedQuery[i]['size'],
                                       reward=checkedQuery[i]['reward'])


def compareItems(obj):
    try:
        last = str(Block.objects.latest('height'))
        for i in obj:
            if i['height'] == last:
                return obj[i:]
        return obj
    except:
        return obj```

but `last` is `Block object (333413)` and when comparing with `i['height']` `str(333413)` it shows FALSE.

what contains `query`
```[{'hash': 'a0642ba14658fc50a093450b2f149a1d589cd3df76414b5661fd8cb08f6727d9', 'height': 333420, 'timestamp': 1626727600, 'interval': 80, 'size': 2283, 'transactionCoun
t': 2, 'miner': 'BTJi34JG4dmL5GbTYgDdp8Nyb7Mhpsd1az', 'reward': '50000000000'}]```
meager anchor
royal musk
meager anchor
#

๐Ÿ‘

royal musk
#

tysm

#

โค๏ธ

bitter thunder
#

anyone a big brain flask-appbuilder user?

bright nimbus
#

any1 have any tips on making a skill tree in html/css/js?
Im thinking of just making an image of arrows and using divs for the tree leaves

sharp basin
#

Does anybody know a website, or source where i can learn more about HTML and CSS, website building, figma exportation.

#

i have little to no experience in HTML or CSS, and i am willing to learn

#

currently i have a figma template to which i am to format it into an actual website

#

can anybody help me?

opaque rivet
bright nimbus
#

yeah i just broke another roadblock i depend on bootstrap for basically 90% of everything though

#

i recommend just using react or some npm way to install the stuff

proud night
#

so im working with quart and discord ipc to make a dashboard for my bot

#

im getting this weird error where it says the key is missing but the key is clearly there

#

Im on the part where im getting the guilds

This is my bot code:

@ipc.server.route()
async def get_guild(data):
    guild = bot.get_guild(data.guild_id)
    if guild is None: return None

    guild_data = {
        "name": guild.name,
        "id": guild.id,
        "prefix" : "?"
    }

    return guild_data

This is my webserver code:

@app.route("/dashboard/<int:guild_id>")
async def dashboard_server(guild_id):
    if not await discord.authorized:
        return redirect(url_for("login")) 

    guild_data = await ipc_client.request("get_guild", guild_id=guild_id)
    if guild_data is None:
        return redirect(f'https://discord.com/oauth2/authorize?&client_id={app.config["DISCORD_CLIENT_ID"]}&scope=bot&permissions=8&guild_id={guild_id}&response_type=code&redirect_uri={app.config["DISCORD_REDIRECT_URI"]}')
    return guild_data["name"]```
This is my error:

``` File "C:\Users\jacob\AppData\Local\Programs\Python\Python39\lib\site-packages\quart\app.py", line 1933, in dispatch_request
    return await handler(**request_.view_args)
  File "c:\Users\jacob\OneDrive\Documents\GitHub\scpinfosite\app.py", line 50, in dashboard_server
    return guild_data["name"]
KeyError: 'name'```
#

I think the dict is returning as null

terse vapor
#

If I delete a certain user or an object by using flask admin, how would I be able to add that action into the daily log(This action will be written into a .txt file)?

#

Like if I deleted someone with flask admin, and hoping to see this action like "user" got deleted by the admin message

glass lance
#

I have this file but the JS wont work

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Haha, STOOPID!</title>
</head>
<body onmouseover="openWin()">
    <h1> Enable POP UPS </h1>
    <p> ^</p>
    <p> ^</p>
    <p> ^</p>
</body>
<style>
    body {
        background-color: black;
        color: red;
    }
</style>
<script>
    function openWin() {
        myTab=tab.open("","","width=800,height=300");
        myWindow.document.write("<p>You are an idiot!'</p>");
    }
</script>
</html>
```Did I do something wrong?
icy wagon
#

OK\

edgy anvil
#

guys im new to flask and im trying to run my flask website but its not showing anything

#

@errant oyster

#

thats all that happens

#

lol

errant oyster
#

idk huhu

edgy anvil
errant oyster
#

u need check step by step again @@

#

i know a little web

#

because i lean data analyst

edgy anvil
#

ij

#

ok

elder rover
#

hi.. any idea build calendar time slot.. i plan to build booking appointment.

hasty crystal
#

any1 wanna work on a project that can make us money?

cerulean badge
#

(context django) i have 2 fields price and discount_price, how can i filter discount_price and if it is null then use price value for filtering?
for example, to filter with discount_price__lte but if discount_price is null then filter with price__lte?

real crest
#

hi i am new to flask and python

#

i have written this code form my flask server

#

from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
return "i am on"

def run():
app.run(host='0.0.0.0', port=8080)

def keep_alive():
t = Thread(target=run)
t.start()

#

and i want to link a html file to this server

#

but also keeping the discordbot connected to it

#

but i cant find a way to do so

#

if anyone can help it will be so nice

native tide
#
                <?php
                while($row = mysql_fetch_array($query)){
                echo '
                 <tr class="entry">
                     <tr>
                     <td style="width: 60px;" class="text-center">'.$row['id'].'</td>
                     <td style="width: 270px;"><a style="color: red; font-weight: bold;" href="/user" target="_blank">'.$row['username'].'</a></td>
                     <td style="width: 90px;" class="text-center">0</td>
                     <td class="text-center">0</td>
                     <td class="text-center" title="Not Done">Today</td>
                 </tr>
                ';
                }
                ?>
``` does anyone know why this isnt showing anything
hollow minnow
#

@native tide you can try to do it like this:

                <?php
                while($row = mysql_fetch_array($query)) { ?>
                 <tr class="entry">
                     <tr>
                     <td style="width: 60px;" class="text-center">'.$row['id'].'</td>
                     <td style="width: 270px;"><a style="color: red; font-weight: bold;" href="/user" target="_blank">'.$row['username'].'</a></td>
                     <td style="width: 90px;" class="text-center">0</td>
                     <td class="text-center">0</td>
                     <td class="text-center" title="Not Done">Today</td>
                 </tr>
                <?php } ?>
native tide
hollow minnow
#

check the page source if uyou have any weird stuff maybe?

native tide
#

nothing weird

#

and console has no errors

hollow minnow
#

errors won't show in the console, that's only for javascript errors

#

Can you check the page source on the place where you'd expect the php stuff?

native tide
#
            <table class="table table-striped table-hover">
                <thead>
                <h6>All Users</h6>
                        <th class="text-center">ID</th>
                        <th>Username</th>
                        <th class="text-center">Pastes</th>
                        <th class="text-center">Comments</th>
                        <th class="text-center">Joined</th>
                                            </tr>
                </thead>
                <tbody>

                
                </tbody>
            </table>
        </div>
        
    </div>
    <div align="center">
    <p>Showing 100 (of 14 total) users</p>
        <br>
        <a href="#">Back to top</a>
        <br><br>```
#

tbody is where the php is

real crest
#

can someone pls help me with my discord bot

#

i am a student

#

pls

#

help

inland oak
minor island
#

Hi, I am learning Django. And I create my own model for users(based on models.Model), I have password field, I encrypt it. And I tried to use check_password(). Idk why, but it always returns False. How to fix it? If you understand Russian language, here is StackOverFlow : https://ru.stackoverflow.com/questions/1306410/ะะต-ั€ะฐะฑะพั‚ะฐะตั‚-django-contrib-auth-hashers-check-password-ะฒัะตะณะดะฐ-ะฒะพะทะฒั€ะฐั‰ะฐะตั‚-false.
views.py :

    error = ''
    objec = users.objects.all()
    for i in objec:
        if request.COOKIES.get('profile_session_id') == i.session_id:
            return redirect('profile')
    if request.method == "POST":
        form = LogInForm(request.POST)
        post = request.POST
        error = 'ะคะพั€ะผะฐ ะทะฐะฟะพะปะฝะตะฝะฐ ะฝะต ะฒะตั€ะฝะพ'
        if form.is_valid():
            error = 'ะะตะฒะตั€ะฝั‹ะน ะปะพะณะธะฝ ะธะปะธ ะฟะฐั€ะพะปัŒ'
            is_session = True
            while is_session:
                session = random.randint(1000000000000000, 10000000000000000)
                is_session = False
                for i in objec:
                    if session == i.session_id:
                        is_session = True
            response = redirect('profile')
            user = None
            if '@' in post['login']:
                for i in objec:
                    if i.email == post['login']:
                        user = i
            else:
                for i in objec:
                    if i.username == post['login']:
                        user = i
                        print(check_password(post['password'], user.password), post['password'])
                        print(user.password)
            if user != None and check_password(post['password'], user.password):
                user.session_id = session
                user.save() 
                response.set_cookie('profile_session_id', session, secure=True, max_age=31536000)
                return response
            else:
                return render(request, 'main/login.html', {'form' : form, "error" : error}) 
    form = LogInForm()
    return render(request, 'main/login.html', {'form' : form, "error" : error})```

Form:

class LogInForm(Form):
login = CharField(widget=TextInput(attrs={
'placeholder' : "Email ะธะปะธ ะปะพะณะธะฝ",
"class" : "form_elem textinput",
'required' : True
}))
password = CharField(widget=PasswordInput(attrs={
'placeholder' : "ะŸะฐั€ะพะปัŒ",
"class" : "form_elem textinput",
'required' : True
}))


Model:

class users(models.Model):

username = models.CharField('ะ˜ะผั', max_length=250)
email = models.EmailField('Email')
discord = models.CharField('ะ”ะธัะบะพั€ะด', max_length=250)
session_id = models.CharField('ะกะตัะธั', max_length=250)
password = models.CharField('ะŸะฐั€ะพะปัŒ', max_length=250)

def __str__(self):
    return self.username

class Meta:
    verbose_name = 'ะŸะพะปัŒะทะพะฒะฐั‚ะตะปัŒ'
    verbose_name_plural = 'ะŸะพะปัŒะทะพะฒะฐั‚ะตะปะธ'

Registration :https://pastebin.com/VtwBrU2V

PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', )

Thanks!
next comet
#

i think you should use the form.cleaned_data['password'] instead of post['password']

vernal moat
chilly mesa
#

hi lads!!

#

for the post request i couldnt find the form-data in the chrome developer tools . you guys got any idea??

#

im stuck in this for a long time

lean sentinel
#

hello

#

may i ask somethin?

#

what i should do with this?

vernal moat
versed python
lean sentinel
versed python
lean sentinel
trail pebble
#

Hey guys

#

how do you take input from a html form and save the data in mysql database using django?

versed python
trail pebble
versed python
trail pebble
elder rover
elder rover
dense niche
#

I'm having a hard time to come up with a catch-all function for my containerized Flask server. I've got React in another container. When I have React and server running on the same system I can go with:

@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path)
    return send_from_directory(app.static_folder, "index.html")

but ^ this is useless if my front-end is running in separate container. The app is docker-compose-managed.
Any suggestions ?

trail pebble
vernal moat
#

Hi

#

how could i center text in html?

#

<p align="center" >Paragraph_1 Explained</p >

#

like this?

#

or with <center><p>Paragraph_1 Explained</p ><center>

trail pebble
vernal moat
#

Okay ty

trail pebble
#

i think "<center>" tag was removed from html in an update

vernal moat
#

Ah okay

thorn igloo
dense niche
gritty cloud
dusk portal
#
def search(request):
    if request.method=='POST':
        searched=request.POST.get('searched')
        x1=Product.objects.filter(title__contains=searched)
    return render(request,'index/search.html',{'x1':x1,'searched':searched})``` this works fine it works when it contains anything but i want to add more filters
#

like

#

startswith

vernal moat
#
    <nav>
        <ul>
            <li><a href="index.html">Home</a></li>
            <li><a href="skills.html">Skills</a></li>
        </ul>
    </nav>
#

Could someone please help?

#

When i go normally to the main link, i dont have /filename.html

#

any1`?

#

bruh

dense slate
#

Anyone had success deploying a React and Django app to production?

#

I'm just looking for some advice in what things to look out for when doing so, how to structure the project, etc.

chilly mesa
dense slate
#

Seems that some people use django as the root where others prefer React as the root.

gritty cloud
dense slate
#

@dusk portal You can chain filters.

#

objects.filter(user=user).filter(email=email).order_by('created_date') etc.

opaque rivet
#

@dense slate I use django as root with the react app in a dir called frontend. Django apps are microservices

minor island
opaque rivet
#

And for the frontend I use next.js to be able to do SSR

dense slate
#

@opaque rivet Why did you decide to have Django as the root instead of React? Since React has a build process, it feels like that should take precendence.

#

I have an app with django as a subfolder of Next.js.

#

Does it really matter in the end?

opaque rivet
#

@dense slate Don't think it matters. In my mind, the django app takes precendence because it has to render a page, so having that page in a frontend folder just makes sense...

#

Probably the least of your worries though

elder nebula
#

How do I make toggle between weeks and years in django urls. When no more weeks in a year, switch to another year ect.
my url patterns looks like this: path('<int:year>/<int:week_num>/', Index, name="index"),.

opaque rivet
#

I can't design frontend I'm so unimaginative

dreamy anvil
#

Has anyone here succeeded in getting a pymc3 installation to work recently? Tearing my hair out here

elder nebula
dense slate
#

Hmm, interesting. Since the browser hits the front end first, and the front end just need information from teh backend, that was my reasoning.

dense slate
#

Yea, I'm configuring the entire app.

elder nebula
#

Cool!

#

I do serverside and backend, also html and css, but never really learned react or any frontend framework

opaque rivet
#

@dense slate yeah just a matter of perspective

#

How you handling design?

elder nebula
#

me?

opaque rivet
#

Ive been using figma for some components

#

It's decent

elder nebula
#

I use adobe xd and figma

#

gimp or figma if I am on linux

#

I like adobe xd over figma idk why

minor island
dense slate
#

Yea, I love the whole process.

#

Plus if you want to make your own software, you need to do it all.

#

I do prefer the front-end though.

#

@opaque rivet Design in what sense?

worn hatch
#

How to unite different queries results from pandas?

elder nebula
#

I have not ever needed to use react, but what's the benefits of using react as frontend?

dense slate
#

I think mainly it is for separation of development, making it easier to have a front-end team and backend team.

#

But I use Next.js and some other libraries for even more benefit, like SEO, caching, etc.

#

Really focusing on site speed.

elder nebula
#

Can you do some extra css / element tricks with react that can't be done without?

dense slate
#

I don't know about tricks, but it's very easy to make a component and then reuse it everywhere.

#

That really helps.

cedar tree
#

hi does some know about trio python ?

opaque rivet
#

@dense slate design in the sense of UX and the visuals of the site

#

I prefer the technical side

thorn igloo
#

dude

#

it's displaying them alphabetically,it doesn't even affect anything

#

idk

#

isn't this something you are defining yourself?

#

you don't need to specify it if it's a primary key, it will auto increment when you insert the data

terse vapor
#

why is my datepicker results not saving into the sql db?

#

i set it to DateTime column in models

dense slate
#

@opaque rivet I'm just creating components and styling them manually to reduce any bloat in the material side of things.

#

It really doesn't take that much time and I feel like I have a lot more control from the beginning this way.

opaque rivet
#

Hmm, mainly color schemes I struggle with. I'll send some designs later maybe

dense slate
#

There are some good sites that basically come up with schemes for you.

#

Like combinations of colors that go well together.

lyric mason
#

Im new at web dev so does anybody recommend a good course that I can use to get started?

dense slate
#

What do you want to do?

#

Learning Flask or Django is your best first step.

jovial cloud
jovial cloud
dense slate
#

What are you learning in Flask that you don't get starting with Django?

#

@jovial cloud

violet briar
#

what is the best db system for a graphQL api (graphene) based on your experience?

jovial cloud
lyric mason
dense slate
#

@violet briar I think that's more a question about what kind of DB you want/need for your project. I don't think it matters much which one you choose from a graphene perspective.

violet briar
next comet
#

what ide do you use for django development

#

or prefer*

dense slate
#

One vote for VS Code here.

sharp basin
#

Hello everyone, today i have switched from webstorm [ a jetbrains application ] to visual studio code, i am a web developer and am need of your assitsance. What extensions should i get, any suggestions?

#

for html and css

terse vapor
#
@app.route("/login-admin")
def login_admin():
    auth = request.authorization 
    admin1 = db.session.query(Admin.password) 
    if auth and auth.password == admin1: 
        token = jwt.encode({'user' : 'admin'}, app.config['SECRET_KEY'])
        toknen = jsonify({'token' : token.decode('UTF-8')})
        return redirect(url_for('add_doctor', token=token))

    return make_response('Invalid!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})```
I'm trying to use the admin password to login to jwt auth, since, I wanted the admin can change their password when ever they want in frontend, however, after running the code, when I submit the input, it redirect me back to the same page, like it just refreshed it. So is there any where i did wrong? ๐Ÿ˜…
dense slate
#

What's the form look like on the frontend?

terse vapor
#

its like a littly pop-up window that vallow me to enter username and password

ruby turtle
#

hello guys
i have a problem

#

i can't import speedtest

#

any can u help me ๐Ÿ˜„

inner badge
#
pip install speedtest-cli
ruby turtle
#

i don't know how install it

inner badge
ruby turtle
#

look

terse vapor
#

no

#

type "pip install speedtest-cli" in terminal

#

like behind the >

terse vapor
dense slate
#

Was asking you to share the code.

#

Is there javascript involved?

terse vapor
#

no java script involved

#
def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.args.get('token') 

        if not token:
            return jsonify({'message' : 'Token is missing!'}), 403

        try: 
            data = jwt.decode(token, app.config['SECRET_KEY'])
        except:
            return jsonify({'message' : 'Token is invalid!'}), 403

        return f(*args, **kwargs)

    return decorated
#

this is all the code for the jwt auth

dense slate
#

Where is your frontend code.

#

The actual form on the site.

terse vapor
#

I dont have a frontend code for this

#

I inputed the link address and this is what came up to me

#

so the only front end is for the admin model which transfer its data from a flask form than to route.py and too database

next comet
# sharp basin for html and css

"live server" i think it was called, also activate auto save, "prettier" (for formatting the code but its just visual stuff and personal preference); also learn the shortcuts like div.somename will make div tag with class='somename' or ul > li * 3 will make ul tag with 3 li inside it

dusk portal
#

oh

native tide
#

does anyone know how to do somehting like this

#

with

#

<select>
<option> aaa bb c </option>
</select>

#

aka have "subsections" of each option element

thorn igloo
native tide
#

would the column-count property go in select or option? and how would i use it?

thorn igloo
#

i'm not familiar with grid but i'll show you an idea of how you can achieve it with flexbox

#

actually, option wont work for this

#

that's not how it works

#

that will only produce a drop down list

native tide
#

?

#

i got my current html to look like this

thorn igloo
native tide
#

but want it to be like this

#

is there no way?

thorn igloo
#

let me check something

native tide
#

Hello so I did a post request using js and the post works just fine

function deleteApplication(application) {
    fetch("/deleteapp", {
        method: "POST", 
        body: JSON.stringify(application)
      }).then(res => {
        console.log("Request complete! response:", res, application);
      });
}```
but I am struggling to get it on the python side I am trying to get rid of the b'' surrounding it when printing
```py
@app.route("/deleteapp", methods = ['POST'])
async def deleteapp():
    text = await request.get_data()
    print(text)
    return text```
Console: `b'"TEST"'`
I am using quart for the web development.
#

No errors I just need to get rid of the b''

#

what do I need to do?

thorn igloo
native tide
#

try a text.decode("utf-8")

#

aight

thorn igloo
#

so you'll have a structure like this:

<option>
  <div class="options">
      <span>a</span>
      <span>b</span>
      <span>c</span>
  </div>
</option>

then in your css

.options {
  display: flex;
  flex-direction: row:
  justify-content: space-between;
}
native tide
#

iirc you can't put extra tags in <opion> tags

thorn igloo
#

i tested it and the extra tags worked

native tide
#

hmm let me test

#
<style>
.options {
  display: flex;
  flex-direction: row:
  justify-content: space-between;
}
</style>

<select multiple="" size="20" style="width: 300px">
    <option>
        <div class="options">
            <span>a</span>
            <span>b</span>
            <span>c</span>
        </div>
    </option>
</select>```
#

when i copy/paste this into the browser i get

#
<html><head><style>
.options {
  display: flex;
  flex-direction: row:
  justify-content: space-between;
}
</style>

</head><body><select multiple="" size="20" style="width: 300px">
    <option>
        
            a
            b
            c
        
    </option>
</select>
</body></html>```
#

completely removing the inner tags :I

thorn igloo
#

right, just saw it

#

i guess it's impossible

native tide
#

yh rip

thorn igloo
#

to do it that way

native tide
#

well thanks for helping

opaque rivet
#

anyone hiring

mint folio
foggy bramble
#

Hello

#
<script>
  function myFunction(id) {
    if (document.contains(document.getElementById("newForm"))) {
      document.getElementById("newForm").remove();
    }

    var d1 = document.getElementById(id);
    d1.insertAdjacentHTML('afterend',
      '<form id="newForm" action="/blog/add_reply/'+ id +'/{{d_blog.id}}/" method="POST">\
                {% csrf_token %}\
                <div class="d-flex flex-row add-comment-section mt-4 mb-4">\
                  {% if request.user.profile.profile_photo %}\
                    <img class="img-fluid img-responsive rounded-circle mr-2" src="/media/{{request.user.profile.profile_photo}}" width="38">\
                  {% endif %}\
                  {{form.media}}\
                  {{form}}\
                  <button class="btn btn-primary" type="submit">Comment</button>\
                </div>\
              </form>\
              ');

    //document.querySelector('#id_parentt [value="' + id + '"]').selected = true;
  }
</script>

form variable here doesn't get loaded, what can i do?

opaque rivet
mint folio
opaque rivet
#

sure, I'll DM you

mint folio
#

But we don't use django.

potent birch
#

Hey guys, I already know basic python, and now I want to get into Backend programming. Can I use python with postgreSQL?

native tide
#

ok so new question

#

let's say i have a <div style="overflow:auto;width:50px;height:50px"></div>

#

how would i make it so

#

when adding a new element to this div (with javascript)

#

the scroll will 'sticky' to the bottom

#

unless it's scrolled

native tide
#

ok nvm i figured out how with javascript

#

i just checked the scroll top and div height with the total scrollheight with js

stiff briar
#

!e

print("Hello")
lavish prismBOT
#

@stiff briar :white_check_mark: Your eval job has completed with return code 0.

Hello
stiff briar
#

@lavish prism hello

foggy bramble
dusk portal
#

anyone's up

vernal moat
#

Hi
how can i set a gradient background?
<style>
.my_bg {
height: 100%;
background-color: blue; /* For browsers that do not support gradients */
background-image: linear-gradient(45deg, #FFFFFF, rgb(0, 157, 255));
}
</style>
I tried this
im not sure what to do to show it as the background
<div class="my_bg"></div>

opaque rivet
#

hey guys, was reading a blog and came across this:

A queryset in Django represents a number of rows in the database, optionally filtered by a query. For example, the following code represents all people in the database whose first name is โ€˜Daveโ€™:

person_set = Person.objects.filter(first_name="Dave")

The above code doesnโ€™t run any database queries. You can can take the person_set and apply additional filters, or pass it to a function, and nothing will be sent to the database.

How does that code not run any database queries? Doesn't this run something like this in SQL under the hood?

SELECT * FROM Person
WHERE first_name = 'Dave';
inland oak
opaque rivet
#

oh cool - that will come in handy. But then doesn't that contradict the statement "The above code doesnโ€™t run any database queries"?

#

I'm unsure what's meant by that.

inland oak
#

when you just write
Person.objects.filter(first_name="Dave") it is not running query immediately
because it allows you to chain your ORM code in this way
Person.objects.filter(first_name="Dave").filter(second_name="Lalala").filter(third_param="lalala")

#

only when the phrase is finished

#

then it runs

#

combining all functions you requested in chain into one SQL query

opaque rivet
#

oh... I misread, well then it does run a database query once its called

inland oak
#

well yeah

gaunt charm
#

is someone here good at django? i need help

versed python
opaque rivet
dusk portal
#

anyone's up

#

ohk im stuck

dusk portal
#

@opaque rivet hey

#
def search(request):
    if request.method=='POST':
        searched=request.POST.get('searched')
        x1=Product.objects.filter(title__icontains=searched)
        if not x1:
            x2=User.objects.get(username__icontains=searched)  
    return render(request,'index/search.html',{'searched':searched,'x1':x1,'x2':x2})```
#
{% if searched %}
<center>
<p>You searched {{searched}}..</p>
</center>
{% else %}
<p> U didn't searched anything..</p>
{% endif %}```
#
{% if x1 %}
#all the stuff
{% else %}
<p> No result found for {{searched}}</p>
{% endif %}```
#
{% if x2 %}
<strong>Users</strong>
<ul>
  <li>{{x2.username}}</li>
</ul>
{% endif %}```
#

so here i want that it should search by title and if not any post come by that title and if any User is with that related username (like a restuarent have named as pizza hut so when i write pizza , so item pizza also comes + the restuarent (username)

#

so i want to filter that

#

so my user function is working fine

#

by 1 my product is SPACE

#

works fine!!!

#

so i have item called space and i wanted to render it it comes

#

when i enter xyz (with is not in both user and title)

dense slate
#

So what's your question.

#

Btw I would probably instead pass each variable individually to the function and just use them as you need them. Something like:

def search(request, **kwargs):
  if request.method=='POST':
    if kwargs['title']:
      result=Product.objects.filter(title__icontains=title)
    else if kwargs['username']:
      result=Product.objects.filter(username__icontains=username)
  
  return render(request,'index/search.html',{'result': result})
#

there's probably an even more efficient way

#

or else you'll have a separate context returned for each condition which can get messy quickly. @dusk portal

jagged ermine
#

help

placid jolt
#

helpppp

placid jolt
# placid jolt helpppp

Hello guys. I badly need help, I need to do a webscraping. To give you details, They gave me a zip folder to extract a file, inside that extracted file was 3 folders with python codes, they told me to use beautifulsoup and pip. so after extracting it, I dont know the next thing to do. here is the screenshot. the notepad was the extracted file with codes then the other side is a jupyter notebook which I prefer to use. Unfortunately, it is not working

dense slate
#

From the error, you need run_Geofence in your environment.

#

I don't know if it's a library or just another file.

#

What's get_services look like?

dusk portal
#

what u said i dont got it @dense slate

#

r u free so i can show whole issue

dense slate
#

Just share it here. I'm not sure what your question was.

drifting surge
#

anyone good with html / javascript

calm plume
signal nova
#

i hope i can ask questions here about html/css because on servers dedicated to the topic, people werent very helpful,
soo i want to create a vertical navigation bar using a google font (i dont yet know if google font is relevant or not) and the list items do not have the padding ive set and i also couldnt adjust the font size.
here is my css and html:

.verticalnav{
    background-color: darkblue;
    font-family: 'Ubuntu', sans-serif; 
    font-size: 15;
    text-align: right;
}

div.verticalnav{
    position: fixed;
    top: 0;
    left: 0;
    width: 30vw;
    height: 100%;
    padding: 5%;
    margin: 0;
}

.verticalnav ul{
    list-style-type: none;
    margin: 0;
    padding: 0;
}

.verticalnav li{
    display: block;
    float: right;
    padding: 10 0;
    margin: 0;
    width: 25vw;
}

.verticalnav li a{
    color: white;
    text-decoration: none;
}
<!DOCTYPE html>
<html>
<head>
    <title>Try xWater</title>
    <link rel="stylesheet" href="waterlanding.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght@500&display=swap" rel="stylesheet"> 
    <meta charset="UTF-8">
    <meta name="description" content="A demo landing page to promote a glass of water">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
    <div class=verticalnav>
        <ul>
            <li><a href="#AbW">About xWater</a></li>
            <li><a href="#WhyW">Why xWater?</a></li>
            <li><a href="#JTM">Join The Millions</a></li>
        </ul>
    </div>
</body>
</html>

pls someone help me find a solution

dusk portal
#

ohh

#

anyone's up

#
@login_required
def order(request):
    if request.method=='POST':
        name=request.POST.get('name')
        email=request.POST.get('email')
        author=request.user
        phone_no=request.POST.get('phone_no')
        address=request.POST.get('address')
        zipcode=request.POST.get('zipcode')
        entry=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
        entry.save()
    return render(request,'index/order.html')```
#
class Order(models.Model):
    name=models.CharField(max_length=50)
    email=models.EmailField()
    author=models.OneToOneField(User,on_delete=models.CASCADE)
    phone_no=models.IntegerField(default=0)
    address=models.CharField(max_length=100)
    zipcode=models.IntegerField(default=0)

    def __str__(self):
        return  self.name``` am i going correct?
#

how can i render that user on html umm

gentle jasper
opaque rivet
next comet
#

im not sure if thats what you are looking for but, at first look that is what is missing in your order view

opaque rivet
#

also:

name=request.POST.get('name')
        email=request.POST.get('email')
        author=request.user
        phone_no=request.POST.get('phone_no')
        address=request.POST.get('address')
        zipcode=request.POST.get('zipcode')
        entry=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)

all of this can be simplified into

entry=Order(**request.POST)
#

@dusk portal

dense slate
#

does the ** just apply all the variables?

#

like ...rest or ...props in js?

outer apex
# dense slate does the ** just apply all the variables?

Similar! JS's spread operator works for almost all iterable objects. Python however has two unpacking keywords: * and **. The latter is for dict whereas the former is for non-dict iterable of objects (e.g. lists, sets).
https://realpython.com/python-kwargs-and-args/

In this step-by-step tutorial, you'll learn how to use args and kwargs in Python to add more flexibility to your functions. You'll also take a closer look at the single and double-asterisk unpacking operators, which you can use to unpack any iterable object in Python.

dense slate
#

Nice thanks!

mint hedge
#

so.....i am working on porting my desktop GUI apps over to web apps. right now i am just building my design but am starting to look at frameworks. I am looking at Django and flask. any others i should look at?

background: I have done some flask work but it always seems unintuitive to have it served in a production level. I have mainly written scripts and desktop gui apps in python, but, due to some circumstances (thanks COVID), so many remote working people has caused my pyinstaller'd apps to take WAY too long to open (30+ minutes). I am also working on consolidating m apps so you only have to go to one site to get to all of my apps.

Queston: What framework would you recommend?

eternal blade
#

I would recommend Django logo_django2

#

It may be hard at first but it will become easier as you use it

dusk portal
#
        author=request.user
``` why this and this is not using post request
#

@opaque rivet

eternal blade
#

It returns the logged in user who is making the request

real crest
deft shore
#

how can I generate html forms from the admin panel? I want to be able to add custom fields and things like that.

late creek
barren pagoda
#

hey everyone i'm new to django and i'm trying to wrap my head around the apps business

#

i get that each app is sort of meant to be a delegate for one business domain or context

#

but i'm not sure i understand how it's meant to be used in practice

#

because, as far as i googled, you can't start django and have multiple apps running simultaneously

#

so i'm very confused how you're supposed to manage this

late creek
#

You can, you need to use gunicorn and preferably for me nginx for the reverse proxy to Django, then you can specify multiple domains that point to different apps in nginx

barren pagoda
#

i was given a small spec of a project with two apps and they want me to run each app as its own microservice, each on a particular port. initially i just worked on each app individually and made sure they work, now i'm struggling to find how i can run them both since one app's model contains a foreign key for the other app's model

barren pagoda
#

thanks

late creek
#

here maybe this will help

native tide
#

Hey, im having problem with the Static folder. i always get errros like "Not found" or "HTTP 404 "

next comet
#

do you load static in your html

#

and have you put the STATICFILES_DIRS = ['BASE_DIR / 'static'] in your settings

#

also you need to load it with the {% load static %} in your html template and in the <link> tag the href should look like this {% static %}

#

and the url to the file you want to load from the static folder

next comet
wise igloo
#

How do I build a button that on click sends data to my Postgres database? This is after the page has received a POST Form with a url that is used to scrape a certain website

#

I would rather not use a second (hidden) form or ajax/jquery for this, as these seem a bit hacky approaches

#

I wrote this question more extensively in #help-coconut but the channel was closed before someone could answer my question

versed python
wise igloo
#

but this would make for a second post request on the same page

#

and I already have an if request == POST section in this particular view for the scraping part

versed python
#

Do exactly that inside the function

wise igloo
#

but would this be a js function?

versed python
#

Yeah

#

Can't be done without

wise igloo
#

Ok

versed python
#

Since you want non browser behavior

wise igloo
#

So then I have to connect to my database from both Python and JavaScript in this project

versed python
#

That sounds like a bad idea

wise igloo
#

That's what I thought

versed python
#

If your backend already connects to the database, send the request there

#

And the backend can do the rest

wise igloo
#

yeah but this is where I'm stuck

#

How do I do that in the backend then

versed python
#

What is your backend?

#

Django?

wise igloo
#

Django

#

I know how to add data to my db from Django

versed python
#

Create a new function to handle this

wise igloo
#

but not in this particular case

#

how would I call that function?

versed python
#

I meant

#

Just create a view

#

An api view

#

And send a request using window.fetch in the Javascript part

wise igloo
#

Hm

#

Ok that sounds like a new approach, I'll take a look into that

#

Thank you very much!

mint hedge
dusk portal
#
@login_required
def order(request):
    if request.method=='POST':
        name=request.POST.get('name')
        email=request.POST.get('email')
        author=request.user
        phone_no=request.POST.get('phone_no')
        address=request.POST.get('address')
        zipcode=request.POST.get('zipcode')
        entry=Order(name=name,email=email,author=author,phone_no=phone_no,address=address,zipcode=zipcode)
        if Order.objects.filter(email=email).exists():
            error_message='Email already exists'
            return render(request,'index/order.html',{'error_message':error_message})
        else:
            entry.save()
            return render(request,'users/order_history.html')
    return render(request,'index/order.html')```
#

its not showing any error

#

but it's not saving info to db

#

@opaque rivet umm

dusk portal
#

and i a function called orderhistory so how can i render there order history of only and only user that is logged in for example i'm logged in as admin so it should show me order history of admin not all the users