#web-development

2 messages · Page 141 of 1

worn mural
#

what do you need ?

#

But if you dont have previous experience with dynamic web sites and js

#

Django is your way to this app

wicked elbow
#

im just trying to resize images but keep proportions using it

#

and the docs dont explain it

worn mural
#

Are you resizing

#

with proportion

#

to the original size ?

#

Or are you just setting a height or width ?

quiet ridge
#

Well I m making a community for programmers and other innovative people. But I need to work on it at a high speed so do someone want to contribute ?

wicked elbow
# worn mural Are you resizing

trying to proportionally resize uploaded images. could be any size. or horizontal or vertical like if i resize a vertical image to 100,50 then it wont be vertical anymore. you get what im saying.

wicked elbow
#

finally found the things i needed reading the source code, im gonna mess around with it just to see what happens

cedar cedar
#

use implicit waiting feauture (google it)

inland copper
#

use global variable for that request['Files']

eternal blade
#

I fixed it by adding this ```py
from django_filters import CharFilter

title = CharFilter(field_name="title", lookup_expr="icontains")``` To my filter class

elfin gorge
#

I just found this regarding my situation:
This is a restriction of HTTP that POST data cannot go with redirects.

#

Using sessions with files is also not a good idea, I think I will have to redesign backend because of that..

native tide
#

anyone have a solution?

#

nvm I am stupid

native tide
frank pawn
#

my image is not showing in website

<svg width="400" height="140" xmlns="http://www.w3.org/2000/svg" style="border-radius:160px"><image src="twice.jpg" alt="Twice" height="200" width="70%" ><title>Placeholder</title></svg>```
 this is code
frank pawn
#

also how to make a round image in html ?

inland copper
#

if u are then it won't work like that

#

u will have to set up static files

#

it is a simple process

elfin gorge
#

oh no [Errno 13] Permission denied: 'media/media/'
django

eternal blade
#

Hi, this is my code for my contact form ```py
def contact_view(request):
# I have aldeady imported send_mail and settings above
form = ContactForm()

if request.method == 'POST':
    form = ContactForm(request.POST)
    if form.is_valid():
        contact_name = form.cleaned_data.get('contact_name')
        contact_email = form.cleaned_data.get('contact_email')
        form_content = form.cleaned_data.get('content')

        context = {
            'contact_name': contact_name,
            'contact_email': contact_email,
            'form_content': form_content,
        }
   
        send_mail(f"Message from {context['contact_name']}",
            context['form_content'],
            context['contact_email'],
            ['my_mail@gmail.com'],
            fail_silently=False
        )
        # return HttpResponse("Sent!")

return render(request, "contact_view.html", {"form":form})
eternal blade
snow wadi
#

hello

#

can i ask something about html?

#
<video width="1000" height="600" controls>
  <source src="" type="video/mp4">
  <source src="" type="video/ogg">
</video>
#

what should i write at mp4 and what a ogg

native tide
#

in which website can I download my webapp

#

upload*

stiff ferry
#

what's up with this error?

TypeError at /food/register/
type object argument after ** must be a mapping, not set
Request Method:    POST
Request URL:    http://127.0.0.1:8000/food/register/
Django Version:    2.2.5
Exception Type:    TypeError
Exception Value:    
type object argument after ** must be a mapping, not set
Exception Location:    E:\Anaconda\lib\site-packages\django\contrib\auth\password_validation.py in get_password_validators, line 30
Python Executable:    E:\Anaconda\python.exe
Python Version:    3.8.3
Python Path:    
['E:\\Shrish\\SHRISH PROJECT\\Project-2-College\\HotelManagement',
 'E:\\Anaconda\\python38.zip',
 'E:\\Anaconda\\DLLs',
 'E:\\Anaconda\\lib',
 'E:\\Anaconda',
 'E:\\Anaconda\\lib\\site-packages',
 'E:\\Anaconda\\lib\\site-packages\\pyzmail-1.0.3-py3.8.egg',
 'E:\\Anaconda\\lib\\site-packages\\distribute-0.7.3-py3.8.egg',
 'E:\\Anaconda\\lib\\site-packages\\win32',
 'E:\\Anaconda\\lib\\site-packages\\win32\\lib',
 'E:\\Anaconda\\lib\\site-packages\\Pythonwin']
#

error seems to be here but what should i do?

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            print(user.password)
            user.set_password(user.password)
            user.save()
royal tendon
native tide
#

thx

tired parrot
stiff ferry
#

nvm i found the probelm and i just removed it lol

#
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {'min_length', 8}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

I added that options there and that was the problem

uncut spade
#

Hi, I'm struggling with associating a Video DB to a User. I tried but when you upload a video, it runs public and not only for you, everyone who creates an account can see what everyone uploads. this isn't what i want to do. Anyone for some help? Here are my main files.

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Videos


class UserRegisterForm(UserCreationForm):
    class Meta:
        model=User
        fields=['username','password1','password2']


class AuthenticationForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'username','placeholder':''}),
        label='Utilisateur')
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':''}),
        label='Mot de Passe')

    class Meta:
        model=User
        fields = ['username', 'password']


class Video_Form(forms.ModelForm):
    class Meta:
        model=Videos
        fields=('caption','Video')```
forms.py
#
def Profile(request):
    all_Vid=Videos.objects.all()
    if request.method=='POST':
        form=Video_Form(data=request.POST,files=request.FILES)
        if form.is_valid():
            form.save()
    else:
        form=Video_Form()
    return render(request,'Utilisateurs/Profile.html',{'form':form,'all':all_Vid})

def Delete_Video(request,pk):
    Vd=Videos.objects.get(id=pk)
    if request.method=='POST':
        Vd.delete()
        return redirect('/profile')
    return render(request,'Utilisateurs/Delete.html',)```

view.py (but only the main fuctions)
#
from .validation_taille import Taille
# Create your models here.
class Videos(models.Model):
    caption=models.CharField(max_length=100)
    Video=models.FileField(upload_to='video/%y',validators=[Taille])
    def __str__(self):
        return self.caption```
stiff ferry
#

have u tried one to many association between user and video

uncut spade
#

wdym?

stiff ferry
#

add a user field in Videos model

#

and associate the videos that way

uncut spade
#

how?

#

add a class in it?

stiff ferry
#

a user has many videos right?

uncut spade
#

yes

stiff ferry
#

and videos are specific to the user right?

uncut spade
#

yes

stiff ferry
#

ur reporter will be user and video will be article

#

no need to worry about the meta there

uncut spade
#

Okay thanks!

#

So I have to create an other class User ? Sorry for wasting your time I'm new to django 😅

stiff ferry
uncut spade
#

Yes

stiff ferry
#

u can associate with them

#

u need to some calls

#

imports*

uncut spade
#

And AuthenticationForm allows you to connect

stiff ferry
#

from django.contrib.auth.models import User

uncut spade
#

Done

stiff ferry
uncut spade
#

Yes

#

I creataed my own one

#

Instead of using the implemented package with login

#
    if request.method == 'POST':
        form = AuthenticationForm(data = request.POST)
        if form.is_valid():
            username = request.POST['username']
            password = request.POST['password']
            user = django_authenticate(username=username, password=password)
            if user is not None and user.is_active:
                django_login(request,user)
                return redirect('MonProfile')
            if user==None:
                messages.error(request,"Le nom d'utilisateur ou le mot de passe n'est pas bon")
    else:

        form = AuthenticationForm()
    return render(request,'Utilisateurs/Connexion.html',{'form':form})```
#

Here's the login fucntion

stiff ferry
#

why check for user == NONE

#

just do if user

#

and else

uncut spade
#

Ok

stiff ferry
#
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model = User
        fields = ('username', 'email', 'password')
#

u can do something like this too

#

that's from the code i'm writing right now though lol

uncut spade
#

I see

stiff ferry
uncut spade
#

Adding a Meta class ?

stiff ferry
#

ye

#

meta will do the things u were trying there probably

uncut spade
#
    caption=models.CharField(max_length=100)
    Video=models.FileField(upload_to='video/%y',validators=[Taille])
    def __str__(self):
        return self.caption
    class Meta:
        model=User```
stiff ferry
#

try once

uncut spade
#

would it work like this?

stiff ferry
#

user = models.ForeignKey(User, on_delete=models.CASCADE)

#

no need to use meta

uncut spade
#
    all_Vid=Videos.objects.all()
    if request.method=='POST':
        form=Video_Form(data=request.POST,files=request.FILES)
        if form.is_valid():
            form.save()
    else:
        form=Video_Form()
    return render(request,'Utilisateurs/Profile.html',{'form':form,'all':all_Vid})```
#

It makes something wiered with this func, i think because it's no longer Videos.objects but User.Videos.objects ? @stiff ferry

wicked elbow
#

that would be something like

# APP
import routes
#routes
import app

look for something similar

uncut spade
#
Utilisateurs_videos.user_id```
wicked elbow
#

look for that pattern. where you have 2 files importing from each other. dont know what else to tell you.

uncut spade
# stiff ferry migrations maybe?

I migrated and here's the new error : return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: Utilisateurs_videos.user_id

#

When I asked to make migrations , It said that:```You are trying to add a non-nullable field 'user' to videos without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:

  1. Provide a one-off default now (will be set on all existing rows with a null value for this column)
  2. Quit, and let me add a default in models.py```
#

I chose option 1

#

and entered 0

stiff ferry
#

u have some data right?

wicked elbow
#

dont know how flask works for sure, look at the docs

wicked elbow
uncut spade
#

How can I go back ?

wicked elbow
#

just open your db up and change it. thats, just better db patterns.

stiff ferry
#

when i faced that problem i emptied my database, the error is because u are adding a new non empty type of field in the database where the previous one didnt have that

#

from what i understood that is

wicked elbow
#

if you add a field that you said cant be empty and already have database data, you have to set a default. otherwise the rows you already have will not pass the NOT NULL constraint. so usually when you add fields, just add blank=True and itll work. then you can remove blank=True after you migrate

stiff ferry
#

yes that works too

#

u can easily add the foreignkey values from django admin than any other new fields too

quiet ridge
#

Issue : https://github.com/sc0op-creator/Programming-Community

Language(s)/Framework (s) : HTML, CSS , JS and Flask (python framework)

Description : I am making a programming community web app and I want someone to contribute and work with me because alone I cannot work at high speed DM me for more.

vestal dove
#

I'm not sure where should I ask that but how do I get the avatar of a user who logged in? I'm using Flask for that btw

@app.route("/@me")
def me():
    code = request.args.get("code")

    at = Oauth.get_access_token(code)
    session["token"] = at

    user = Oauth.get_user_json(at)
    user_name = user.get("username")
    user_discriminator = user.get("discriminator")
    user_id = user.get("id")
    user_avatar = user.get("avatar")

    with open('bal.json', 'r') as f:
        load = json.load(f)

    money = load[str(user_id)]["Money"]
    username = load[str(user_id)]["Username"]

    return render_template("my.html", money=money, username=username, avatar=user_avatar)
frigid pawn
#

Hello everyone. I have this code enrolled_courses = user.students.filter(is_trial=False).order_by('-id') remaining_courses = list(Course.objects.filter( active=True, is_trial=False, hidden=False ).exclude( id__in=enrolled_courses.values_list("id", flat=True) ).order_by('-id')) courses = list(enrolled_courses) courses.extend(remaining_courses) I was thinking if is it possible to replace the courses.extend part with chain of itertools. If so will it improve the performance?

frigid pawn
frigid pawn
#

can you post the key: value for the avatar from json file?

honest current
#

Anyone here developing with Odoo?

cyan siren
#

HElllo world

#

anyone here use django? i need a little help

honest current
vestal dove
#
@staticmethod
    def get_user_json(access_token):
        url = f"{Oauth.discord_api_url}/users/@me"
        headers = {"Authorization": f"Bearer {access_token}"}

        user_object = requests.get(url=url, headers=headers).json()
        return user_object
#

and right here in my html code i need the card to have a circle with the user avatar

<body>

    <div class="card"></div>
    <div class="pfp"></div>

</body>

<style>
    body {
        background-color: cadetblue;
    }
    
    .pfp {
        height: 25vh;
        width: 25vh;
        border-radius: 50%;
        border-style: solid;
        border-color: darkred;
        background-color: #555;
        position: absolute;
        top: 3vh;
        left: 87vh;
        background-image: url({{avatar}});
    }
#

and i get it right here using this

    code = request.args.get("code")

    at = Oauth.get_access_token(code)
    session["token"] = at

    user = Oauth.get_user_json(at)
    user_name = user.get("username")
    user_discriminator = user.get("discriminator")
    user_id = user.get("id")
    user_avatar = user.get("avatar_url")
#

@frigid pawn

elfin gorge
#

how can I get file type in django ?

stable hemlock
#

If there are any folks who are experts at Python Flask forms and can help me with the issue described in my stackoverflow post linked here, I would be very grateful. https://stackoverflow.com/questions/66630554/cannot-access-form-responses-in-dynamic-flask-form-python

buoyant shuttle
#

what div bg color goes well with blue bg color?

native tide
#

Hey. I have a big problem. I want to make a Bot and for this i need to login into WhatsApp web. I want it to make verify automated so i don't need to use my phone. Is there a way to do it with a automation or with a emulator?

wicked elbow
spare iris
#

nah that's 100% against ToS

wicked elbow
buoyant shuttle
wicked elbow
#

pretty much yea

#

https://htmlcolorcodes.com/ to find what colors work well together

HTML Color Codes

Easily find HTML color codes for your website using our color picker, color chart and HTML color names with Hex color codes, RGB and HSL values.

buoyant shuttle
#

Good utilities i could use

#

Awesome Job

#

Only one default export allowed per module? I cant have 2 components in react?

#

in the same file?

light gale
#

hey guys, I'm pretty happy with a flask app I built, but struggling with consistent template 'control' - should I consider a frontend framework, and what do you recommend?

#

I'm quite happy with some designs I made on Figma, but unsure how to go from there.

buoyant shuttle
#

Congrats on the app

opaque rivet
buoyant shuttle
#

so its just normal export?

opaque rivet
#
export const exampleComponent = (props) => ...

^ This is a named export, you import it like this:

import {exampleComponent} from ...

When you do a default export export default exampleComponent you are setting the default export of that file, there can only be one. To import you do:

import exampleComponent from ...
#

@buoyant shuttle

buoyant shuttle
#

makes sesnse now

#

thanks

clear musk
#

Hey! I forgot to git pull before adding new features in the code. When I git push now, will it overwrite the changes that my co-worker made on GitHub? Or will it somehow merge those? I don't want those things to be lost. Is there any way to do this easily?

opaque rivet
# clear musk Hey! I forgot to `git pull` before adding new features in the code. When I `git ...

I think you will run into a conflict:
https://stackoverflow.com/questions/54278883/forgot-to-git-pull-before-working-and-now-i-cant-git-push

I wish I could help more, I'm a beginner to git (my random guess is that the branches aren't synced so you'll run into an error).

sonic badge
#

I'm working on a simple page that will allow users to make posts for their profiles, and the handling will be done through a standard api. I'm wondering what is the most standard way to format an endpoint for something like this? If a post has 3 main parts, a set of images, a caption, and a description, how should the API accept this data? Base64 encoding the image in a JSON body or some multipart request?

bold imp
#

@clear musk Look into pull with rebase

#

And good luck, git is still such a complicated thing to me

proud vortex
#

so I would like to listen for webhooks from the monday.com api but they require that I send a challenge key back to them for the webhook. I would need to set up like a flask/django webserver for this, right?

native tide
#

How to do that

#

please

#

css

buoyant shuttle
#

do what exactly?

#

oh move the line

native tide
#

ye

buoyant shuttle
#

is this a table?

native tide
#

yes

buoyant shuttle
#

pase the code

#

alternativaly what you could do is play with the td(table data) width

native tide
#
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 50%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
  width: 166px; height: 30px;
}

tr:nth-child(even) {
  height: 23px;
  background-color: #dddddd;
}
</style>
</head>
<body>

<table class="center">
  <tr>
    <td>Current session</td>
    <td>csgo</td>
  </tr>
  <tr>
    <td>Players ready</td>
    <td>stuff</td>
  </tr>
  <tr>
    <td>Max players</td>
    <td>5</td>
  </tr>
</table>```
#

code

#

@buoyant shuttle

buoyant shuttle
#

alright so each row has a td right? so your going to have to style the td so give it a class name, like firsRow, for td in the first row, control the width,

native tide
#

ahhh

#

i have no brain cells for that

#

i mean, its 3am

buoyant shuttle
#

its 5am im about to head to bed, been up working

#

lol

#

but ill give you a snipper and tell you where to go from there

#

@native tide what i used to do is download Microsoft Web expression

#

its a GUI for html. I use it for tables cause it comes extremely useful, instead of coding

#
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 50%;
}
table .row1{
  width:"Play with this, it determines the widht od the line. ideally keep it decrease the number to decrease the width";
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
  width: 166px; height: 30px;
}
tr:nth-child(even) {
  height: 23px;
  background-color: #dddddd;
}
</style>
</head>
<body>

<table class="center">
  <tr>
    <td class="row1">Current session</td>
    <td>csgo</td>
  </tr>
  <tr>
    <td class="row1">Players ready</td>
    <td>stuff</td>
  </tr>
  <tr>
    <td class="row1">Max players</td>
    <td>5</td>
  </tr>
</table>
#

here is the wikipedia to webexpression

#

but its helpful to save tins of energy coding

native tide
#

thanks!

stable hemlock
#

Can anyone here help me figure out how to access data from a FieldList on WTforms? I have a FieldList of SelectFields where items are added Dynamically on initialization, and when I submit the form I always get none as the value regardless of what I choose. Full code is here: https://stackoverflow.com/questions/66630554/cannot-access-form-responses-in-dynamic-flask-form-python

eternal blade
#

How can I change the position of an element without effecting other elements using CSS?

toxic flame
#

position absolute positions the item based on the width of the display staticly

vestal hound
#

position: relative

#

absolute or fixed if you want to pull it out of the flow entirely

#

(depending on whether you want it relative to container or viewport)

sage hornet
#

Can anyone pleaseee help me with a few things if so dm me
i really need help

scenic belfry
#

Need help with Django channels ERROR:-ValueError: No application configured for scope type 'websocket'

swift wren
#

can somone help me attributes to UserCreationForm forms because i want to use bootstrap for the fields but its not being applied and adding widget hash map isnt wrking as well

#

i also want to add a placeholder but again the widget dict isnt working or applying any changes

hallow perch
#

Hello their! I have this error when i launch my flask app. Any idea?

wispy sedge
#

End of file? Sounds like an unclosed quote or bracket or something

hallow perch
# wispy sedge End of file? Sounds like an unclosed quote or bracket or something

That my code, i don't where can be the error ?

discord = DiscordOAuth2Session(app)


HYPERLINK = '<a href="{}"><span>Connection</span></a>'


@app.route('/')
def home():
    return f"""
        {HYPERLINK.format(discord.create_session())}
        """
    return render_template('jonque_home.html')


# Launch app.
partial_run = partial(app.run, host='127.0.0.1', port=50879)

t = Thread(target=partial_run)
t.start()

# Launch DevBot.

TOKEN = os.getenv('TOKEN')
DevBot.run(TOKEN)

Can you help me?

wispy sedge
#

Why the two returns? And no I personally don't really know how to start investigating this

hallow perch
#

Okay i see, i don't know it's for add session to a button in another html file.

inland copper
#

pip install django-bootstrap4

swift wren
#

and how would that solve my issue

inland copper
#

in the templates

swift wren
#

i mean it seems fair but how would i impliment it

#

oh what?

inland copper
#

u should add {% load bootstrap4 %}

#

THEN HOW ARE U CALLING THE FORM?

#

{{ form.as_p }}?

swift wren
#

nah im having to do a for loop and just write the for loop name

inland copper
#

but u mentioned a usercreationform

swift wren
#

yeah

#

in my views, the view function is calling the form thn being passed as a context into the html

inland copper
#

okay can u show the template?

swift wren
#

my forms are created from UserCreationForm

inland copper
#

okay

#

just show that pic

swift wren
#
<html>
    <head>
        <title>
            Simple Form Application
        </title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    </head>
    <body style="text-align: center; background: #DF2B4F">
        
        <div class='container' style="text-align:center;">
            <div class='card' style='margin-top:30px;' width='20rem;'>
                <div class='card-body'>
                <a href="/"style=" float:left;"> <img src="static/icons/back.svg"> </a>
                    <br><h2 class="card-title">Register</h2>
                    <form method="post" class='form-group'>
                    
                        {% csrf_token %}
    
                        {% for field in form %}
                            <div style=" text-align:center; color:black; margin-left:-500px "><h4> {{ field.label_tag }}</h4></div><br>
                            <div style="margin-top: -30px; " class='float-middle'>{{ field }}</div><br>

                            <p style=" color: #FC4445;">{{ field.errors }}</p>

                        {% endfor %}                
                    
                        <a href="/reg"><button class='btn btn-success' style='margin-top:10px;'>Register</button></a>
                    </form>
                    <p> if you have a account please <a href="/login">login</a></p><br>
        </div>
    </body>
</html>
#
{% csrf_token %}
    
                        {% for field in form %}
                            <div style=" text-align:center; color:black; margin-left:-500px "><h4> {{ field.label_tag }}</h4></div><br>
                            <div style="margin-top: -30px; " class='float-middle'>{{ field }}</div><br>

                            <p style=" color: #FC4445;">{{ field.errors }}</p>

                        {% endfor %}                
inland copper
#

hmmm

#

this is such a bad practice

#

why not {{ form.as_p }}

#

it does all of this in a line

swift wren
#

because if i write form on its own its going to polute the page with the "help texts"

#

nah tbh, im rethinking everything

inland copper
#

okay u need bootstrap for this?

swift wren
#

yea

#

but ive imported it through css

#

the only reason that im using this shit is because of another issue which was solved after implimenting this

#

so its not important but if you can find a way for me to be able ot have bootstrap forms

#

that would save me so much time

inland copper
#

there isn't any straight solution for this

swift wren
#
class UserRegisterForm(UserCreationForm):
    
    class meta:
        model = User
        Fields = ['username', 'email', 'password','password2']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter Email'}),
            'password': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Password'}),
            'password2': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Confirm Password'}),
        }
    def __init__(self, *args, **kwargs):
        super(UserRegisterForm, self).__init__(*args, **kwargs)

        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'

        self.fields['username'].widget.attrs['placeholder'] =  ''
        self.fields['password1'].widget.attrs['placeholder'] = ''
        self.fields['password2'].widget.attrs['placeholder'] = ''
#

yeah ik

#

its fucked

#

i need to make my own form and just make sure that i save the user to the abstract model and not a completely different model

inland copper
#

omg

#

why do u need all this?

#

why not use the defalt

swift wren
#

i was trying my hardest to see if there was anyway that this shitty class could have any way for me to allow some passthrough but no it is what you get

inland copper
#

exactly

swift wren
#

nah ill just make my own template ive realised what i need to do

inland copper
#

ya

buoyant shuttle
#

for django restframework, which one do you guys prefer

#

functional based API views, or class based API views

proven carbon
#

hello

#

i want run code python when click on link

#

@timid obsidian

late gale
#

is it possible to convert all js files to typescript in Django ?

#

and thanks

proven carbon
late gale
#

if you're not using either of them u can use ajax

#

Example :

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>
#

u can use <a> tags instead of input if u want a hyperlink text and add the onclick property and It'll work as above

#

@proven carbon

proven carbon
late gale
stiff ferry
#

what's the best method to add a payment option in your django application
it will have cash on delivery, what i want is to add online payment too

past cipher
#

probably stripe or paypal @stiff ferry

quick cargo
#

Mhmm

#

stripe will cover pretty much all the credit card stuff

#

except paypal

#

but both stripe and paypal have pre-made DJango intergrations

tribal pewter
#

yeah I just like to throw everything on stripe so I don't have to worry about all the other stuff

#

especially security wise

stiff ferry
#

i more question
is there a way to make a qr code specific to a certain organization (say here my django project which will have multiple different objects under it)

manic frost
stiff ferry
quick cargo
#

My go to's are Stripe, or Braintree

buoyant shuttle
#

is it possible to use django ctx in jsx react

#

that way i wont have to be making bunch of http calls

quick cargo
#

not really

buoyant shuttle
#

damn, was hoping so

#

ill give it a try

#

yeah it didnt work what a bummer

#

jinja templating wont work either

quick cargo
#

using ss rending and client side rendering is generally a bad idea

#

pick one or the other

buoyant shuttle
#

I just renamed my model, but my terminal says its deleted.

#

looks like i look all the data

copper juniper
#
def index(request):
    UA = request.META['HTTP_USER_AGENT']
    IP = get_client_ip(request)
    return render(request, 'index.html'), UA, IP```  Am I passing the UA and IP variables correctly? (django)
plush slate
#

can anybody here tell me (or give a link to a tutorial) how to make a sticky navbar onscroll using css and javascript? 😅

hallow perch
#

Hello! Do you know how to change Login text in span with a var like user.name ?
That my code:

<a href="{{ 'login' }}"><span>Login</span></a>
@app.route('/')
def home():
    if not discord.authorized:
        return render_template('jonque_home.html', login=login())

    print("CONNECTED!")
    user = discord.fetch_user()
    return render_template('jonque_home.html')
buoyant shuttle
native tide
#

anyone work with d.js?

buoyant shuttle
#

as in discord.js?

proper carbon
#

what i need to learn to create a website with django?

buoyant shuttle
#

html and css

#

to create a basic website,m after learn js, to create a functional website

#

also python lol

native tide
# proper carbon what i need to learn to create a website with django?

There are many free tutorials on YouTube that will teach you the basics to what is needed to create a website with Django. But if you are unsure where you start on youtube or prefer reading sources, I would recommend you understand some basic core concepts:

  1. Use the Django Documentation. https://docs.djangoproject.com/en/dev/
  2. Have a basic understanding of the following programming languages.
    a. Python
    b. HTML
    c. CSS (unless you are using bootstrap)
  3. Lastly, if you are wanting to store data, understanding SQL is a major bonus.

Two video series I would recommend for the very basics are:

https://www.youtube.com/watch?v=Z4D3M-NSN58&list=PLzMcBGfZo4-kQkZp-j9PNyKq7Yw5VYjq9

or

More in depth
https://www.youtube.com/watch?v=B40bteAMM_M&list=PLCC34OHNcOtr025c1kHSPrnP18YPB-NFi

Welcome to the first python django tutorial on my channel. Django is a full stack web framework that allows for rapid development of websites. In this tutorial I will be showing how to setup and install django and talk about how to navigate between different pages.

Source Code: https://techwithtim.net/tutorials/django/setup/

Playlist: https://...

â–¶ Play video

How to Build a Simple Blog with Python and Django. Creating a blog with Django his pretty easy! In this video series I'll walk you through it step by step.

In this video we'll set up our development environment, create our Django Project and add a blog app to it. We'll create a Django SuperUser for the Admin Area, and then configure our data...

â–¶ Play video
buoyant shuttle
#

My favourite is the one by Justin

#

But he uses django 2, even now, so wouldnt reccomemend.

#

the one in freecodecamp. which is justins own uses django 2. django 3 has been out for some time now

proper carbon
native tide
# proper carbon tysm, i hope i can pay you one day.

It's my absolute pleasure to help you.

The greatest thing about programming in my honest opinion is that we are always trying to learn more, while I am by no means close to even being "good" with Django, I am happy to help out where I can, since I have received so much help in the past and I will be needing more help in the future as well.

native tide
#

Hi! I am having a heck of a time with FastAPI getting Sagger to show the parameter descriptions. For example,

@fastApi.get("/run/get/{run_id}", status_code=status.HTTP_200_OK, name="Get Run By Id", description="Gets a run by its run id (it's name generated).")
async def run_get_by_id(run_id: str = Query(..., title="Run ID", description="The run ID/name that we are requesting", example='20210315T135404_fname_lname'),
                        user: User = Depends(loginManager)):
    """
    Gets a run by its run id (aka name).
    :param user: The user credentials to know who is getting the run.
    :type user: The user that is getting the run.
    :param run_id: The run id to get.
    :type run_id: str
    :return: The run found (rendered to JSON), or an error JSON.
    :rtype: Union[dict,DocumentRun]
    """

The "description=" never shows up in swagger, but the rest does?

native tide
#

Hi, anybody available for chat?

stable hemlock
#

Can anyone here help me with rendering multi-widget forms in Django? this code <form method = "post", action = ''> {% csrf_token %} <div> Form should be here. {{form.category}} {{form.widgets}} renders them like this: Form should be here. <django.forms.fields.ChoiceField object at 0x7fd29f0362e0> [<django.forms.fields.ChoiceField object at 0x7fd29e6f3af0>, <django.forms.fields.ChoiceField object at 0x7fd29e6f3640>]

lavish prismBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

hushed kernel
#

And pass in user or whatever to the template

last patio
#
    class RenameContentType(migrations.RunPython):
AttributeError: module 'django.db.migrations' has no attribute 'RunPython'``` I get this when I try to migrate
#

does anyone know how I would fix this?

strong torrent
#

For what ever reason I am getting this error:
cross-origin resource sharing error header disallowed preflight response
I am using nginx. Does anyone know the solution?

late gale
# proper carbon tysm, i hope i can pay you one day.

I highly agree with what @native tide told you but I also wanted you to take a look at corey schafer
https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p
or Dennis Ivy (( He's been uploading videos about django until now and it's very useful ))
both are supportive

#

and my HUGE advice to you is not to learn bootstrap for responsiveness only use it for time, I don't use it myself , Vanilla CSS is much powerful and you've fully responsive using Flexbox or Grid

#

and I also recommend learning Sass which is better than CSS , it's the same CSS syntax but much organized and powerful if u want to stick with CSS it's fine CSS is still cool too just take a look at Sass

#

And Learn Typescript instead of Javascript much easier and more powerful

late gale
buoyant shuttle
#

can typescript run on runtime

#

Guys is it a good idea, to keep constantly writing to my models

#

like each time my server is up 24/7 writting to db

late gale
buoyant shuttle
#

hmm

#

Maybe i should learn typescript

late gale
#

i already switched all my js files to ts

buoyant shuttle
#

oof

#

does react work with ts

late gale
#

ofc

#

let me give u a youtube link

buoyant shuttle
#

lol thats my queue

#

Codemy.com youtuber, is making a new serires with django

#

it would include more concepts

late gale
#

Learn how to use React and TypeScript to create a quiz app project. You will also learn how to use Styled-Components with React.

🔗 What you will make: https://tender-mcnulty-a4a646.netlify.app/
💻 Code: https://github.com/weibenfalk/react-quiz

🎥 Course from Thomas Weibenfalk. Check out his YouTube channel: https://www.youtube.com/user/Weibenfal...

â–¶ Play video
buoyant shuttle
#

nice

#

lol Ben awad

late gale
#

a lot more of tutorials

#

typescript is the future of javascript

#

believe me

#

it's like javascript but much easier and powerful

strong torrent
#

For what ever reason I am getting this error:
cross-origin resource sharing error header disallowed preflight response
I am using nginx. Does anyone know the solution?

late gale
#

All it does u write in ts and it compiles and generates the code into js file so u can add this js file to html or something

buoyant shuttle
#

microsoft out did themselves

late gale
buoyant shuttle
#

is it similar to js? or has some extra concepts involoved

strong torrent
late gale
late gale
buoyant shuttle
#

it seems with vanilla Typsescript i can get things done, i dont even need to use react or vue

late gale
#

simple as that

strong torrent
buoyant shuttle
late gale
strong torrent
#

No

#

I am having trouble with nginx settings

buoyant shuttle
late gale
#

oh so idk the error maybe u can wait someone to help you

strong torrent
#

So basically I need a flask webpage which recieves the webhook fires from the website, but something with CORS is blocking it from recieving it.

late gale
#

oh so you're at the right place , Apologizes wish I could help you but I don't have any knowledge about flask, I know Django

strong torrent
#

Ok thats ok

#

Il wait for someone elese

late gale
viscid citrus
#

Is

#

apache

#

worth

#

learning

#

or

#

should

#

I

#

stick

#

to

#

node

#

js

crisp wind
#

is anyone here familiar with web scraping

#

i have a quick question

buoyant shuttle
#

Guys i need help

#
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
``` What does it mean int argument cant be a string
native tide
#

How to show matplotlib on webstite with flask?

rough lintel
#

If you all are asking who would answer?

buoyant shuttle
opaque rivet
#

you'd be better off using a JS library for graphs, especially since they are interactive - arguably more "useful" than an image.

opaque rivet
strong torrent
opaque rivet
strong torrent
#

I just opened it completely up

#

And it worked

opaque rivet
#

What did you open up?

native tide
#

made by for loop

#

constantly changing

#

what about that?

opaque rivet
native tide
#

ye

opaque rivet
#

Save your graph images, have a list of the graph locations, pass that to your frontend, then have a for loop in your jinja2 template to render the images

native tide
opaque rivet
#

plt.savefig(image_name)

native tide
#

and with for loop? because the names cant be same

opaque rivet
#

Yep, generate unique names for each.

native tide
opaque rivet
#

I'm sure you can make that decision for yourself

wicked elbow
#

when users upload files, im just leaving them the same name they are when they get uploaded. im sorting based on user so it doesnt matter quite as much as because most people dont have photos with the same name anyways

#

but graphs are a different story, lmao i should read the whole message.

wicked elbow
#

maybe this is a dumb question, but can you write from reverse relations. like if i add a row, can i also add a row from the foreign key relation. for example:

Model1:
  groud_id: 10
  user1: user1
  user2: user2

Model2:
  groud_ref: ForeignKey(Model1)
  other_fields: ...

if i create Model1 and set it to that, can i also do a create for Model2 at the same time from the same request?

haughty turtle
opaque rivet
last patio
#

Trying to migrate to add a field called balance but it says it's column doesn't exist

#
LINE 1: ...hter"."nationality", "fighters_fighter"."season", "fighters_...```
wicked elbow
#

i know i can pull from the reverse, but can i create from the reverse.

haughty turtle
wicked elbow
#

im thinking something like this:

class AddGroupAndMessageSerializer(serializers.ModelSerializer):
    message_group = ReverseMessageSerializer(many=False)

    class Meta:
        model = MessageGroups
        fields = ('user1', 'user2', 'unique_key', 'message_group')

    def create(self, validated_data):
        if validated_data['user1'].id < validated_data['user2'].id:
            user1 = validated_data['user1']
            user2 = validated_data['user2']
        else:
            user1 = validated_data['user2']
            user2 = validated_data['user1']

        user_contains = f'id{user1.id}, id{user2.id}'

        group_create = MessageGroups.objects.create(
            user1=user1,
            user2=user2,
            unique_key=user_contains,
        )
        message_create = Messages.objects.create(
            sender=validated_data['sender'],
            recipient=validated_data['recipient'],
            message=validated_data['message'],
            msg_group=group_create
        )
        return group_create
``` and the serializer should pull it, right?
haughty turtle
#

In your one API call you can do as much as you want in your views as you need to.

wicked elbow
#

its 2 separate tables, and in Rest framework, you use serializers. so on post, it deserializes the json, creates the item, then serializes. and im not sure if itll pull the correct serializer for the post.

haughty turtle
#

Ah I havent used the REST framework. I mean outside of the REST framework recreating it seems pretty simple.

wicked elbow
#

thats the tricky issue. im running into problems on my frontend, because this all runs through a websocket. and parsed into react. its not the same as making posts and gets. the changes are passed through the socket. and when i go to a users profile, i want to check if message group exists, just send the message, otherwise create the group and send the message. making 2 api calls and waiting for the response is really counter intuitive and makes something simple take much longer

#

but if you just click on a send a message and dont send a message, i dont want to create a group because it appears in the chat section for no reason.

manic frost
#

@native tide We don't allow requests for paid work here. You might want to check out any freelance platform if you need work done.

late gale
#

try to google it it's not hard or simply ask how to do it we can help rather than paid

native tide
#

hey, I'm trying to make a background behind my text like this

#

I just simply used <a style="background-color: #3d444a">, but how can I make the "light bar" go beyond the text so they're all the same width? rooThink

silk trellis
#

I think you'd use a table but there might be a better way

#
<table>
  <tr>
    <td class="x" >In collectie sinds: {{ date }}</td>
  </tr>
  <tr>
    <td class="y">Uitgespeeld op: {{ other_date }}</td>
  </tr>
  <tr>
    <td class="x">Local multiplayer: {{ tttt }}</td>
  </tr>
</table>
#

and style either the row (<tr>) or the cell (<td>) and they should all be the same width

native tide
sleek sable
#

was making a portfolio app using django. The CSS is not loading,even after it is there in the project. Also not showing any error. What could be the problem?

#

`{% load static %}
<!--
<link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}">

<h1>Hello World</h1>

<img src="{% static 'images/profile.jpg' %}">
-->

<!DOCTYPE html>
<html>
<head>
<title>NETRANJIT BORGOHAIN</title>
<link href="{% static 'css/main.css' %}" rel="stylesheet" type="text/css" >
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>

<body>
<br>
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="card-body"> </div>
</div>
<div class="col-md-9">
<div class="card-body"> </div>
</div>
</div>

    <br>
    <div class="row">
        <div class="col-md-6">
            <div class="card-body">    </div>
        </div>
        <div class="col-md-6">
            <div class="card-body">    </div>
        </div>
    </div>

    <br>
    <div class="row">
        <div class="col-md-6">
            <div class="card-body">    </div>
        </div>
        <div class="col-md-9">
            <div class="card-body">    </div>
        </div>
    </div>
    <br>
</div>

</body>
</html>`

#

My home.html

inland copper
#

i have lot of projects

crisp wind
#

I had some questions based off of some syntax and stuff

inland copper
#

in python?

crisp wind
#

Upon python web scraping lol

inland copper
#

okay u use selenuim or bs?

crisp wind
#

Python

inland copper
#

bs*

crisp wind
#

I’m just kinda confused with selection part of it

#

What is bs 🥲

inland copper
#

beautiful soup

crisp wind
#

Yeah I’m using it

inland copper
#

tell me your use case and i will suggest accordingly

crisp wind
#

And request

inland copper
#

i would suggest selenium

#

it is actually better

crisp wind
#

Sure

#

How come

inland copper
#

what are u using it for?

crisp wind
#

Haven’t heard of it before lol

inland copper
#

what kind of project

crisp wind
#

It was a school work assignment

inland copper
#

i know a youtuber who has a course which is really good

crisp wind
#

To grad all the reviews from a website

inland copper
#

This selenium tutorial is designed for beginners to learn how to use the python selenium module to perform web scraping, web testing and create website bots. Selenium is an automation framework that allows you to interact with websites using something called a web driver.

How to Fix Pip: https://www.youtube.com/watch?v=AdUZArA-kZw
Chrome Web-dr...

â–¶ Play video
inland copper
#

then selenium will be good

crisp wind
#

Grab*

inland copper
#

do u want to use it in a web app or just a python program

crisp wind
#

We r only allowed to use bs

inland copper
#

okay then no prob

#

bs is good too

crisp wind
#

But I’ll be down for learn another library

inland copper
#

ya selenium is very helpful

crisp wind
#

Twt! Everyone’s first choice learning programming stuff

inland copper
#

i have used it for many websites

crisp wind
#

I’ll check that out

#

What kind of projects did u build with web scraping

#

I actually just started to learn it from last week

inland copper
crisp wind
#

Just being curious

inland copper
#

this is a simple project made with selenium

crisp wind
#

Oh wow. That’s rly cool!

inland copper
#

thanks

#

this was made using requests

crisp wind
#

Nice nice

inland copper
#

thanks

crisp wind
#

How many websites did u scrape from

#

Approximately lol

inland copper
#

just one

#

and some other projects used APIs

crisp wind
#

Got u got u

inland copper
#

ur project shld be easy

#

if u know the syntax

crisp wind
#

I was so lost for the syntax

#

Whether i was supposed to find tag or class to target what I need to grab

inland copper
#

okay i understand

crisp wind
#

I’ll check this out too

#

Thx man

#

Will that be cool if I ask u any random questions? Some questions that are not speci googleable or checked on stackoverflow lol

#

Maybe not tonight

tulip beacon
#

guys, I want the message box on the right to be shown when I click the home button on the left by react router

#

what should I do for that?

tulip beacon
#

anyone?

tulip beacon
#

@ HELPERS ?

eternal blade
#

Hi, I am using django and this is my code for the edit profile view ```py
def edit_profile(request):
context = {}
creator_profile_form = CreatorProfileForm(instance=request.user.creatorprofile)
context["creator_profile_form"] = creator_profile_form

if request.method == 'POST':
    creator_profile_form = CreatorProfileForm(request.POST)

    if creator_profile_form.is_valid():
        creator_profile_form.creator = request.user
        profile = creator_profile_form.save(commit=False)
        profile.creator = request.user
        profile.save()
        messages.success(request, "Updated profile")
        return redirect("edit-profile")

return render(request, "registration/edit_profile.html", context)
But when I submit the form I get this error ```powershell
IntegrityError at /accounts/edit-profile/
UNIQUE constraint failed: base_creatorprofile.creator_id```
Thanks
past cipher
#

does anyone know how to do a case sensitive SQL query with SQLAlchemy ?

#

For example I want make a query for the name TEST. I want to return the results with TEST only and not test or Test

silk trellis
past cipher
#

Thanks @silk trellis , just what I needed

topaz sierra
#

FastAPI or Flask?

dapper tusk
#

do you want a full website or just an api, and do you want to use react/vue/sth similar for the frontend

topaz sierra
#

Frontend-rendering and api

dapper tusk
#

then fastAPI may be easier

topaz sierra
#

I thought that fastapi can do everything what flask can do... But async...

tribal sedge
#

Is it possible to make a website entirely out of Python and it's libraries. (Not only just for the back end, but for the front end as well.)

native tide
#

I do not think so, python can only be used on the server side, you cant run python on the client's computer.

dapper tusk
#

in theory yes, but in practice using html and JS is much easier

native tide
#

really? even a gui?

dapper tusk
#

you can run python on the client side, but it is a bad idea and highly untested

native tide
#

WOAH

topaz sierra
native tide
#

had no clue that was possible

topaz sierra
#

But I dont think that you should use it.

silk trellis
topaz sierra
neon pasture
#

How to do (with the math module) to create a program that knows when the square root of a number is impossible to calculate?

versed python
#

For some reason, the highlighted element (it says Hello but only the H is visible) doesn't show completely, even though it has z-index of 9999. What am I doing wrong?

neon pasture
#

on voit r

#

ah oui dsl personne est francais ici wsh

native tide
#

hey

#

is python good for html 5 developing

toxic flame
#

hi guys i have a question, has anyone tried something of "compressing" an image before rendering it out?

#

i could compress before saving the file, but I already have alot of file uploaded

pulsar pulsar
#

Anyone played around streaming using SRT technology?

covert prism
#

idk about django and flask so anyone give me suggestion which one is best django or flask

covert prism
proper tree
#

?: (urls.E004) Your URL pattern [<URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.

i am facing to this error after i made a media url and media root in settings.py
settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py :
static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT),

distant trout
#

when a react component has a change in state, lets say a <p> tag inside a header component, will it re-render the entire header component or just the <p> tag?

opaque rivet
opaque rivet
opaque rivet
opaque rivet
toxic flame
opaque rivet
#

you can add it within your clean method (if you're uploading via form) to compress it before uploading/saving to database

proper tree
#

?: (urls.E004) Your URL pattern [<URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.

i am facing to this error after i made a media url and media root in settings.py in django

settings.py :
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py :
static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT),

opaque rivet
native tide
#

hello

#

I have a general question

#

I get that we need html and css to make a website

#

but is it optional to use JavaScript?

#

like what if i only use Flask?

proper tree
opaque rivet
native tide
#

I created a small site using html css and flask to route pages, it's very simple

#

Interactivity meaning? hovering arrow over certain element kinda of thing?

native tide
#

can flask not be used to do what js does? like making websites more modern/fance?

opaque rivet
proper tree
#

a dir

opaque rivet
# native tide interactivity?

with HTML / CSS you have no client-side logic it's all server-side, with JS you have React, Vue, jQuery etc, they give the user more ability to interact with your site.

opaque rivet
native tide
#

wait i get it

#

Is this the right section to ask about a crypto trading bot?

#

python is only installed on server, while each and every device has JavaScript!!!

opaque rivet
native tide
#

Ah ok nice

#

Im a newbie sort of

#

So im having issues finding only the price of BTCUSDT

#

but javascript is so annoying, i hate learning it

opaque rivet
native tide
#

JS is must.. i didn't know that. i thought it was related to java and i don't ever want to learn java

opaque rivet
#

At a higher level, you'll start having JS frontends (e.g. React) which communicate with your Flask backend. (backends can also be in JS - I like Django too much to change though)

opaque rivet
#

If you want JS for the web, learn React (does require knowing a bit of JS before-hand).

native tide
#

i understand that now

opaque rivet
native tide
#

Its not that

#

Im using bybit API

#

And i am parsing the orderbook

#

But it has so much information

#

And i only need price

#

1 question, is it possible to make dynamic webpages like that of reddit or imgur, using flask but not using javascript???

#

i think answer is no.. right?

opaque rivet
#

make the API call, serialize json -> dict:
response = requests.get(your_url).json()
then you can find the 'price' key (or whatever it may be) by parsing through:

for key, value in response.items():
  if key == "price":
    price = value

I also had to parse data, it's not fun but the API shouldn't be so complicated.

opaque rivet
native tide
#

then

#

print(price)

#

well i never liked a language with curly brackets ..... but i guess there's no choice for JS. i have to start learning it properly now

opaque rivet
celest torrent
#

Sorry to interupt. If anyone is able to help with my django migrations issue I've asked in #help-grapes.

native tide
#

damn bro @opaque rivet . i was trying to avoid it. Thanks for clearing. i guess it will grow on me eventually

#

any suggestions on how to proceed?

opaque rivet
#

it will... I literally remember going into this discord to say how much I hated to learn other things :D, haha.

native tide
#

right now i understand the basics, but i haven't designed anything

opaque rivet
# native tide any suggestions on how to proceed?

I learnt a bit off codecademy - I joined the Reactiflux discord then just started to do my own projects. I got the hang of it pretty quick. If you already know python then JS is not much different (just a bit different syntax for things).

native tide
#

@opaque rivet so how should i obtain only price?

opaque rivet
native tide
#

Do i need to include some library?

#

Also, are there any softwares out there that would make web designing process more easy??

#

like i don't want to start from scratch,

opaque rivet
# native tide

I don't know the structure of the JSON response you're getting. I wouldn't know how to parse the data from such limited info.

native tide
#
     "topic": "orderBookL2_25.BTCUSDT",
     "type": "snapshot",
     "data": [
        {
            "price": "2999.00",
            "symbol": "BTCUSDT",
            "id": 29990000,
            "side": "Buy",
            "size": 9
        },
        {
            "price": "3001.00",
            "symbol": "BTCUSDT",
            "id": 30010000,
            "side": "Sell",
            "size": 10
        }
     ],
     "cross_seq": 11518,
     "timestamp_e6": 1555647164875373
}```
#

And i only want it to print out "price"

native tide
#

like wix?

opaque rivet
# native tide https://bybit-exchange.github.io/docs/linear/#t-websocketorderbook25

it's cool that you're using websockets. I might have the move to bybit. wow! real-time updates huh? I was just getting JSON data from an API and it wasn't even in-sync that well 😂

anyways, you have your data. You can access the "price" key with:
price = your_data_dict["data"][0]["price"]

you have two events, a buy and a sell, the code above just selects the first one.

opaque rivet
native tide
#

By my data directory

#

You mean

native tide
opaque rivet
native tide
#

okay good tip,

native tide
#

This is wrong @opaque rivet

#

What did i do wrong here?

noble hare
#

hello, I am looking for help on building pdf to audio converter web app as a final year project

native tide
#

right now i feel am way back in my journey, i need to learn a lot more

opaque rivet
native tide
#

dict as in

#

directory?

opaque rivet
#

dictionary

native tide
#

thank you for the advice @opaque rivet

#

Im so confused sorry im not that good

toxic flame
opaque rivet
noble hare
native tide
opaque rivet
#

can you print it?

native tide
#

Yes

#

Data is what i showed you

#

This is data

opaque rivet
# native tide

if this is data, then data["data"][0]["price"] should work.

native tide
#

It doesnt 😦

opaque rivet
#

if not try data["data"], see what that gives you, and continue

native tide
opaque rivet
#

then I don't think data is the dictionary you showed me. data is a list (from the error), you showed me a dict.

toxic flame
#

Maybe turn it into json by dumping it first

native tide
#

It is

toxic flame
#

It could be json format

#

But python doesn't know that

#

so i would say its safer to turn it into json ( just for the sake of it ) before querying any of them

opaque rivet
# native tide

it's not in this format. data is something else (and I do not have a clear idea of what the structure is from the pictures you sent me)

#

your error implies that data is a list.

native tide
native tide
#

How would i go about doing that?

toxic flame
#

import json
var = json.dumps(thelist)

#

Then use the var["data"]

native tide
#

Where would it dump it

#

Because i have this

toxic flame
#
while True:
  data = ws.get_data(...)
  data = json.dumps(data)
  #what continues here
toxic flame
# native tide

Then u can just use the data["data"] without this error popping up

native tide
#

So this is what i have right now

toxic flame
#

ok

#

What did you want to print / use?

#

Price?

native tide
#

Yes

#

I want to use/print price

#

This is the API

toxic flame
toxic flame
# native tide

If the file is like this, it will be a different case.

native tide
#

Same issue

toxic flame
#

1 moment I'm on my.phone

native tide
#

Alright

toxic flame
native tide
#
     "topic": "orderBookL2_25.BTCUSDT",
     "type": "snapshot",
     "data": [
        {
            "price": "2999.00",
            "symbol": "BTCUSDT",
            "id": 29990000,
            "side": "Buy",
            "size": 9
        },
        {
            "price": "3001.00",
            "symbol": "BTCUSDT",
            "id": 30010000,
            "side": "Sell",
            "size": 10
        }
     ],
     "cross_seq": 11518,
     "timestamp_e6": 1555647164875373
}```
toxic flame
#

Give me a min

native tide
#

No worries, no need to rush

glacial musk
#

hi

#

i got an question can someone help me

#

how do i backspace this is my code from selenium import webdriver
from time import sleep
driver = webdriver.Chrome(executable_path="/Users/Tollie Bonker/Downloads/chromedriver")
driver.get("https://www.instagram.com/")
sleep(4)
driver.find_element_by_xpath("//input[@name="username"]")
.send_keys("usrr")
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys("pass")
driver.find_element_by_xpath('//button[@type="submit"]')
.click()

toxic flame
#

its such pain typing code in phone

glacial musk
native tide
toxic flame
toxic flame
native tide
#
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
                    api_key=None, api_secret=None)

ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
    data = ws.get_data("orderBookL2_25.BTCUSDT")
    data = json.loads(data)
    ##price = data["data"][0]["price"]
    if data:
        print(data["data"]["price"])```
glacial musk
#

ye rip

native tide
glacial musk
toxic flame
#
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
                    api_key=None, api_secret=None)

ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
    data = str(ws.get_data("orderBookL2_25.BTCUSDT"))
    data = json.loads(data)
    ##price = data["data"][0]["price"]
    if data:
        print(data["data"]["price"]) 
#

here ya go try this

toxic flame
glacial musk
#

this is my code

#

from selenium import webdriver
from time import sleep
driver = webdriver.Chrome(executable_path="/Users/Tollie Bonker/Downloads/chromedriver")
driver.get("https://www.instagram.com/")
sleep(4)
driver.find_element_by_xpath("//input[@name="username"]")
.send_keys("usrr")
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys("pass")
driver.find_element_by_xpath('//button[@type="submit"]')
.click()

#

but if the pass is wrong i want to backspace it

native tide
#

Now all these errors

toxic flame
#

oof

toxic flame
glacial musk
#

i just started python like a week

#

how do i get better?

toxic flame
toxic flame
#

If you're trying some malicious stuff you should look into apis instead

glacial musk
#

but thanks

native tide
#

Do you know how to fix my error true?

toxic flame
#

Lets see

toxic flame
toxic flame
native tide
#

Yes

toxic flame
#

1 moment then

#
ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
                    api_key=None, api_secret=None)

ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
    data = str(ws.get_data("orderBookL2_25.BTCUSDT"))
    data = json.loads(json.dumps(data))
    ##price = data["data"][0]["price"]
    if data:
        print(data["data"]["price"]) 
#

@native tide

native tide
#

Hey

toxic flame
#

if this doesnt work

#

Try this

ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime_public",
                    api_key=None, api_secret=None)

ws.subscribe_orderBookL2(symbol="BTCUSDT")
while True:
    data = ws.get_data("orderBookL2_25.BTCUSDT")
    data = json.loads(json.dumps(data))
    ##price = data["data"][0]["price"]
    if data:
        print(data["data"]["price"]) 
native tide
#

For first one

#

For second one

toxic flame
#

i would do more testing if I was on my desktop with that data

#

but sadly i cant

native tide
#

Can i add your discord

#

And you message me back

#

When on PC?

toxic flame
#

I'm sure when I'm on pc you'll already finish this problem, but sure

glacial musk
#

driver.find_element_by_xpath("//input[@name="password"]")
.send_keys("pass")

#

how can i make its doing it from an txt

opaque rivet
# native tide

your errors are because your data is the wrong datatype. If it is JSON, you have to parse it into a dict and then access the keys of that dict. If you don't know how to do that, you should do a python-based course.

proper tree
#

from django.contrib import admin
class articlesAdmin(admin.ModelAdmin) :
list_display = ('title','describtion')
i want title and describtion from model be shown in the admin panel but it doesn't work

opaque rivet
opaque rivet
#

can you show us that line of code?

proper tree
#

from django.contrib import admin
from .models import articles

Register your models here.

class articlesAdmin(admin.ModelAdmin) :
list_display = ('title','describtion')
admin.site.register(articles)

#

the full code

#

ow i didn't put articlesadmin in the register()

native tide
#

When i do it

#

Some of them are []

#

Some of them are the data

#

How would I clear a shopping cart when payment is authorised? I'm using flask sessions

shadow python
#

can someone help me with something?

#

when i click on genres i can see the list

#

but when i go somewhere else and click again it says #

#

`<li class="">
<a href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
GENRES
</a>

                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                                            {% for cat in  category %}

                                            <li class="col-lg-2 col-md-4 "><a class="dropdown-item" href="/genre/{{cat.category}}">{{cat.category}}</a></li>

                                            {% endfor %}
                                        </ul>
                                    </li> `
glacial musk
#

if driver.find_element_by_class_name("_2Lks6"):
sleep(4)
driver.find_element_by_xpath("//input[@name="password"]")
.send_keys()

how can i backspace at the send keys??

strong torrent
#

How would I add an authorization header for nginx. I need it for a website

native tide
#

how to use flask as backend of react?

woeful atlas
#

Hi, I do a google search with image:

import json
import time
import requests
import urllib

link_list = []
filePath = "/home/pi/Projet/vilian/image.jpeg"
searchUrl = 'http://www.google.hr/searchbyimage/upload'
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
response = requests.post(searchUrl, files=multipart, allow_redirects=False)
fetchUrl = response.headers['Location']

print(fetchUrl)```
She return a valid url <http://www.google.hr/search?tbs=sbi:AMhZZitnm6Iw1J7QYE5YhyOKmqFuKDQcYl0CUyzb4leuaS9OrtJSm4f613UthjD9tV3vsCbjOOY0XRFFMobEU1WDrgJRKS3OFNIibNGd5UV_17jlozB5NOGr_1dqWKhKq-e6tJCLHUbPHCckgPdmRXI-kKgTzQSFW3SDPMqWBPi-WLmHq6N2kcVlTPzdSVrHrxQo7lQHBXWMe3GNHnNslv3KiKdgL2oa0kMsvhOqc38FwKHil57ccYAQz1lGlfeTenjVBq_16H7CvwtJUHjsQy5GHulMGBVweYk1eQl-dKs-L81z2B4JQLms_1EMredscyagQzPgfloTyjIV>

```py
response=urllib.request.urlopen(fetchUrl)
html = response.read()
print(html)```


But when I download the page (for see resutl), she don't return the corect result. You know how I can get the right elements?
opaque rivet
native tide
#

anyone know anything about using selenium and 2capcha that can help me with a project. I’m not asking just to ask but I don’t know anyone that really knows much about it so yk 🙂

lavish canopy
#

If someone can and has the time — can anyone help me get Django + VueJS installed? I've tried doing things through NPM in the past, but for whatever reason it broke literally ALL my other Django projects..... I'm pretty bummed about it and have not touched it since. I just got asked to do something and I need to make sure I'm able to get this installed

toxic flame
#

Is it all done?

#

You can just have a sub dir /api/ for the django site

lavish canopy
#

I haven't even been able to get Vue going to do all that yet

#

I need to at least get the library installed

toxic flame
#

Is the site done?

lavish canopy
#

I can do whatever else from there

#

The Django install is and it has its environment

#

I don't have Vue in and connected to it though

toxic flame
#

maybe set django onto another domain / subdomain / subdir

#

subdomain is a good idea

lavish canopy
#

For Vue?

distant trout
#

does someone know how does react link works? it's redirect without refreshing page, but how does that happen? it makes no requests at all...

lavish canopy
#

Don't we need them installed and configured in the JSON?

distant trout
#

import { Link } from 'react-router-dom' this thing

lavish canopy
#

This is the part that's messing me up

#

Vue is going to handle the responsive stuff as well as the shopping cart

#

If push comes to shove, I'll just stick with jQuery. I just don't like using it anymore

toxic flame
#

no

#

you have the vue on yoyr main site since I assume it has everything ready ( link, router, etc )

#

then you will have Vue fetch the stuff and get post requests to your django backend

#

which will be hosted on another domain, sub domain, sub directory, etc.

pallid cove
#

hey there. I've been running into an issue with Flask while following up a book on building REST APIs with Flask and all of that. The issue is: TypeError: 'method' object is not iterable, and I just do not understand it, been reading up and down the whole code to try and see something, been looking over search results, stackoverflow, nothing really on that, and as I'm trying to learn about it, I can't get exactly what the error means...

so, if somebody would be likely to help me, I ask you to not only give me an answer, but also to tell me why and how xD

here's the endpoint code for the get method (which I believe is related only because of the word 'method' right there, if needed full code, I can send it tho)


@app.route('/authors', methods = ['GET'])
def index():
    get_authors = Author.query.all
    author_schema = AuthorSchema(many=True)
    authors, error = author_schema.dump(get_authors)
    return make_response(jsonify({'authors': authors}))

if __name__ == '__main__':
    app.run(debug=True)

#

oh! and please, the discord is full of spamming messages, tag me up if you're trying to help me, please

fallen spoke
#

is it a bad idea to deploy my api backend when im still developing/ working on the front end?

wooden ruin
#

@fallen spoke if you have an ssl certificate you would ideally want to deploy an external app once its ready and secure, then work on the backend to avoid the hassle of switching from http to https or ws to wss etc, but be sure the api is secure

#

Ideally you want your front-end app to be served the backend to avoid configuring subdomains etc, do this only once everything is done tho, when developing its best to have the 2 run independently

fallen spoke
#

@wooden ruin thank you, I was thinking of deploying the backend on api.mydomain.com and the frontend on mydomain.com since I am not sure how to serve a react project using django. is this a bad idea/ is it hard to set up subdomains? also, where do I get an ssl certificate? I have seen a few websites like cloudflare and godaddy but some of them have tiers and idk which one I need

wooden ruin
#

Its easy to configure subdomains, but it depends on whether you want your api to be public and used by others, or only accessed when you say so (i.e. fetch, axios, etc). Also, you can compile your app to be served from anywhere, simply by loading the html file. On vue this command is npm run build, but it may vary. Find the option that best suits your needs and work from there

native tide
#

im running into a few issues with django. would anyone mind me pm'ing them for help?

spare iris
#

Or you can just ask the question

native tide
#

why is my template not showing up, why is my css file not showing up, why is my url pathing giving me weird results?

#
    <link href="./bootstrap.css" rel="stylesheet">

Not sure how to get the file location when the html template is in the same directory as the css file, which all the combinations I've tried didn't work.

#

the url patterns and views are as follow (this is app urls, not root):

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name=''),
    path('about/', views.about, name='about'),
]

now root urls:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('Blog.urls')),
    path('about/', include('Blog.urls')),
]

and my views:

from django.shortcuts import render


def home(request):
    return render(request, 'Blog/base.html')


def about(request):
    return render(request, 'Blog/base_about.html')
#

i can see two about pages and only one index and one admin, which is weird because i would assume if im getting two abouts, i should get two indexes. (the '') but when i try to actually view them i get errors

#

also no template loading up

lavish canopy
#

c44g

outer pier
#

what is the best way to implement single string match search in django

#

when I googled I got to know about haystack . but for the server what is the best one , whoosh or elastic search .Does Anybody implemented this before !!

native tide
#

okay now my links are working, just my templates aren't rendering still

tribal pewter
#

What is your templates path? Where is the html located

#

And is there any error you can share?

twilit needle
native tide
#

Hey

#

with flask im making a Rest api, How would i get the requests json? (when you make request like requests.get(url, json={}).)

tough oak
#

Hey guys which one is best for database

#

Sqlite?
Mangodb
Etc?

tribal pewter
#

It really depends on what your use is

#

for example SQLite is good for small or demo bapplications

tribal pewter
#

And Mongodb is NoSQL database so it really depends whether you wanna work with a SQL or NoSQL database

snow vessel
#

:c

lapis stratus
#

Hello is there anyone here who previously used Node and ExpressJS and suddenly switch to flask or django

#

how easy is it to use compare to two of that I'm using ReactJS in Front-End I can't easily grasp the idea on node and express :/

strong torrent
#

How would I add an authorization header for nginx?

fallow lake
#

how to debug 405 error i get for post: requests.post(url, data=json, headers=headers) ? thanks!

fallow void
#

on that url

fallow lake
#

thanks! is there a way to check what methods are allowed?

fallow void
#

If you have documentation of APIs, that is where I would look first

#

But doing OPTIONS on url should return Allow Header

fallow lake
#

unfortunately don't have tha pi docs. i will check options thanks a lot!

#

oh, great, it shows me only PUT is allowed

#

thank you @fallow void !

tender crater
#

@lapis stratus What is specifically that youu don't grasp?

lapis stratus
#

Something like that

#

I can only wrote few data on the tutorial I'm following

frank pawn
#

How i can insert video in column using for statement ?(django)

#
<h1 style="align-content: center;color: aliceblue;font-weight: 900;text-decoration: underline;">Python Lectures</h1>
{%for v in vide%} 
    <p style="font-family: monospace;color: bisque;font-size: x-large;">{{ v.video_name}}</p>
    {% video v.video "small"%}
{% endfor %}```----> This is code
tender crater
#

@lapis stratus I am afraid you have to elaborate your question a bit more, I don't get if you're struggling with:

  • Getting data out of the db
  • Parsing that data into the JSON structure to be returned
  • Something else
strong torrent
#

How would I add an authorization header for nginx?

tender crater
strong torrent
#

Um no

frank pawn
stable hemlock
full needle
#

It's my second accountyert

fair agate
#

Are there any good non-blocking ODM DBs using MongoDB that work well with Django?

quick cargo
#

idk why you want non-blocking and Django

#

All of Django's orm and database infa is blocking

stable hemlock
# full needle Yes

You can use a table, make the entire loop within a <tr> and each item within a <td>

fair agate
#

Ah, I was hoping to use Django as a testbed for using a nonblocking ODM for Discord.py as well but that's fine, what are the best packages for MongoDB integration in Django?

#

I remember using Djongo but ran into issues after a while with unusual behavior, not sure

lavish prismBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

steady swan
#

motor

#

but, I wouldn't use django for that

#

!pypi motor

lavish prismBOT
cloud path
#

hey guys

#

i don't manage to install whirlpool on a linux server, i need it for a flask web app

#

this is the error

#

solved

cloud path
#

guys what am i doing wrong? trying to run gunicorn

#

it says "serveraddress" isn't a valid port number, but if i use the numeric ip it works fine, but it isn't on the alphanumeric address

quick cargo
#

because you're trying to use a domain name instead of the host machine ip

#

when you're running a server you're either running on localhost or exposing the ip to the whole network

#

anything like domain etc... isnt the responsibility of the webserver

#

you either bind to 0.0.0.0 (publicly exposed across the network) or 127.0.0.1/localhost

#

the hostname resolution is the job of your DNS and nameserver

cloud path
#

oh i see, i'm not working on the server, i just made a flask app for a guy who is working on the server

#

so he should either bind the address.ip on 0.0.0.0 or localhost?

quick cargo
#

yes

cloud path
#

gotcha thanks!

uncut spade
#

Hi, does someone for which reason do I hac this error? Here are my model and form files :

#
from django.contrib.auth.models import User
from .validation_taille import  validate_file_extension
# Create your models here.
class Videos(models.Model):
    user = models.ForeignKey(User, on_delete = models.CASCADE,null=True)
    caption=models.CharField(max_length=100)
    Video=models.FileField(upload_to='video/%y',validators=[validate_file_extension])
    def __str__(self):
        return self.caption
#
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Videos


class UserRegisterForm(UserCreationForm):
    class Meta:
        model=User
        fields=['username','password1','password2']


class AuthenticationForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={'class': 'form-control','type':'text','name': 'username','placeholder':''}),
        label='Utilisateur')
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':''}),
        label='Mot de Passe')

    class Meta:
        model=User
        fields = ['username', 'password']


class Video_Form(forms.ModelForm):
    class Meta:
        model=Videos
        fields=('caption','Video')```
stable hemlock
cedar lodge
#

hey ,
I am having a serializer relation defined in my serializer class like below

class OptionsSerializer(MongoSerializer.DocumentSerializer):
    modifiers = ModifierSerializer(many=True, read_only=True)
    class Meta:
        model = Options
        fields = [
                "id",
                "name",
                "description",
                "price",
                "modifiers",
                "type"

                ]

Here's my models.py

class ModOptions(EmbeddedDocument):
    name = StringField(max_length=100, required=True)
    price = FloatField(required=True)


class Modifiers(Document):
    name = StringField(max_length=1024, required=True)
    options = ListField(EmbeddedDocumentField('ModOptions'))
    is_used = BooleanField(default=False)
    is_used_counter = IntField(default=0)


class Options(Document):
    name = StringField(max_length=100, required=True)
    description = StringField(max_length=1000, blank=True)
    price = FloatField(required=True)
    modifiers = ListField(ReferenceField('Modifiers'))
    type = StringField(max_length=100, blank=False)
    is_used = BooleanField(default=False)
    is_used_counter = IntField(default=0)

I am using django rest framework mongoengine.
If remove my serializer relations, The api works fine, But with the serializer relation I am unable to create or update document.

#

I need some help with this 😮

distant trout
#

thoughts on express vs django/flask?

#

in terms of simplicity, i guess

past cipher
#

how to handle ? in flask url
order/payment/complete/bulS83v********/?token=157*********&PayerID=C*******3AG

@order_bp.route('/order/payment/complete/<string:order_id>/<string:token>/<string:payer_id>', methods=['GET'])

if I remove the question mark, the route loads fine, however if I don't, then it just returns a 404

cyan pawn
#

A question mark starts a set of query params, you might need code to look for the query params in the dict that flask should construct for you... it shouldn't automatically return 404, that's odd.

cyan pawn
past cipher
distant trout
cyan pawn
distant trout
#

i was curious cuz im learning react and trying to choose a suitable backend for it. I am fairly good with flask since ive built several projects with it

fair agate
#

What is the best package to integrate MongoDB in Django?

native tide
#

Hi, how can i use javascript variables inside a php file?

silver hearth
#

anyone have experience deploying flask apps?

gleaming tiger
#

<script>console.log('it works!')</script>

gleaming tiger
cloud path
#

guys i'm trying to run this flask app with gunicorn on a domain

#

the domain is done with plesk obsidian

#

i can't change the ip of the domain in order to make it local or 0.0.0.0

#

it has its own ip and although i'm using it for running gunicorn, it works with the numeric ip but not the domain name, probably i'm failing the port, but i don't know what port it has

native tide
# gleaming tiger just use a script tag and put the js inside the script body

Thank for the response, let me give you a brief description of what I'm trying to accomplish,

A user checks a check box => JavaScript asks for location permission and then console.log(location),
Now this is what i want to do next with location variable,
Location variable should go to php file (test.php) and then test.php should echo location variable.
I'm a little confused how it can be done, JSON? Ajax ? I don't know, please guide me

native tide
gleaming tiger
gleaming tiger
native tide
#

Nevermind, someone else would help me.

#

@opaque rivet what you're upto?

opaque rivet
opaque rivet
native tide
opaque rivet
native tide
#

hello who know well django ?

opaque rivet
native tide
#

i have this error but i dont understand wht

#

personne is link to user

opaque rivet
native tide
#

yes

#

but

#

i have do this

opaque rivet
#

the error means that user.personne does not exist

native tide
#
class Personne(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="personne") 
    chartes = models.ManyToManyField(Charte, through='CharteSignature')


    def __str__(self):
        personne = self.user.first_name 

        return personne
#

@opaque rivet now you can see

opaque rivet
#

okay, and your view?

native tide
#

is the admin panel friend

native tide
opaque rivet
#

well it looks like your Personne instance is not linked to a user.

native tide
opaque rivet
#

having a field on a model does not mean it's populated, that's your job. user is null.

native tide
#

i have two user

opaque rivet
#
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="personne")

The user field of your Personne instance is null

native tide
#

Ohhhh sorry

#

i need to put on false ?

opaque rivet
#

you need to assign a user to your Personne instance. But yes, you should make null=False if you need each Personne to have a user (which you have to assign yourself).

native tide
#

i have already make signals @opaque rivet

#

but when i want to migrate i have error with admin_interface

#

ModuleNotFoundError: No module named 'admin_interface'

ocean dirge
#
def get_access_token(code):
        payload = {
            "client_id" : Oauth.client_id,
            "client_secret" : Oauth.client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : Oauth.redirect_uri,
            "scope" : Oauth.scope
        }

        access_token = requests.post(url = Oauth.discord_token_url, data=payload).json()
        print(access_token.get("access_token"))

my access token returns null but i dont know why

#

im working off of discords api

native tide
#

Hi, how do i make table generator. I mean, when something happen, it will generate new table to site with new stats, and the old ones will remain

last patio
#

I'm trying to go start a new DB but when i try to make migrations from scratch on it it keeps saying django.db.utils.ProgrammingError: relation "fighters_fighter" does not exist

last patio
#

o ty

glossy rover
#

Hi, have been struggling with getting test data into Django from csvs, for weeks now 😄 I am trying to import test data into the car inspection django model, I attempted via django admin and csv import, and also via python scripts but since tables are all related, one to many, many to many, I struggle to get the test data that is also been related imported to the django model (in sqllite). Doesn't make sense!
help would be awesome!

native tide
#

Can i write html into html? like ```py
file = open("sample.html","w")
file_to_add = open("adding_html.html", "w")
file.write(file_to_add)
file.close()

last patio
#

the new one?

#

its just a clean DB

#

its an empty db

#

well i actually think ive solved it, I had a certain migration i probably did incorrectly somewhere

#

i pulled my inital git version and redid the migrations one commit at a time and now its.. working ;-;

#

well for now, ill continue to keep pulling and migrating

#

hoping it doesnt break

#

thanks for the help anyways!

last patio
#

dammit

#

I went commit by commit making clean fresh migrations

#

and it worked on that db

#

I started a new db to test, and when i try to python manage.py migrate on that DB i get the same problem

last patio
#

anyone?

opaque rivet
last patio
#

literally just did that ;/

#

same issue

opaque rivet
#

did you delete your db also?

last patio
#

im trying to create a new one

#

like a blank one

native tide
#

hey guys

#

for some reason my program is outputting only a part of a html tag

elfin gorge
#

where could I get linux help ?

native tide
#

what is the difference between using a custom view template in django and a "generic view"

cunning prairie
#

I've a problem. I need to parse the site via request. When program parse, site sends a page with error 414. I suppose, it's antiparsing system. How i can get around this system?

molten siren
toxic flame
#

hiii guys any good apis to test and play around with?

eternal blade
#

Hi, can you suggest some good free services to host my django logo_django2 web app?, thanks

eternal blade
grim cedar
#

dont think so

vestal hound
#

but why does that matter

wooden ruin
#

@toxic flame dog api! free, easy to use and understand. Good practice for using fetch, axios etc

eternal blade
last patio
#

I wouldn’t run something where you are having users signup and save data like that on a platform like heroku