#web-development

2 messages · Page 187 of 1

rotund perch
#

try putting

#

/ in the last

#

..../create-question/

nova sonnet
#

that doesnt work

#

let me try and change the action first

eternal blade
#

I have Django-cors-headers and allowed hosts

rotund perch
#

if none then sorry I dont know what would the solution be.

eternal blade
rotund perch
eternal blade
eternal blade
rotund perch
eternal blade
#

🙂

opaque rivet
dense slate
nova sonnet
dense slate
#

Great

nova sonnet
dense slate
#

You added the path to the view?

#

Share some code and we can look over it.

#

the form and the view

#

Show the whole form,

#

the view, and the full url/path

#

See you're cutting stuff off with screenshots. It's better to paste actual code.

#

But post your view as well, where you handle the post request.

nova sonnet
#

yeah my bad

#

im doin something atm so im rushing

dense slate
#

No worries, we can look at it later.

nova sonnet
#

thats the view

dense slate
nova sonnet
dense slate
nova sonnet
#

on the top of the method

dense slate
#

Show me where, I don't know what on top means.

nova sonnet
#

the form_valid one

#

right beneath it

dense slate
#

put one as the first line in the class

#

and then submit the form, do you get anything printing in the terminal?

#

and I assume you're logged in?

nova sonnet
#

yeah

#

the thing is nothing is being calledf

#

the print doesnt work and ive moved it

dense slate
#

what happens if you remove the action= from the form all together and then submit?

nova sonnet
#

ive used the createview in other instances and the action wasnt even needed

dense slate
#

Yea it's not necessary.

#

But now that you've actually hard-coded it, and it still doesn't get into the function, means you have something obviously not making that connection, and my guess is something isn't written correctly. Is that url called 'create-question' at the end?

nova sonnet
#

yeah

dense slate
#

oh

#

you have community spelled incorrectly, if that matters

#

in your url/path

nova sonnet
#

oh dang

#

let me check it now

dense slate
#

why do you have a pk in the create question path?

#

what's the pk related to?

nova sonnet
#

the community the question is going to be added in

#

fixed the typo but no change :((

dense slate
nocturne basalt
#

Can you explain what a meta class do? pithink

dense slate
#

the whole thing

#

and the url that's in your browser on that page

barren sable
#

I am rendering http content on a https page, therefore getting the mixed-content error. I have searched on web what solutions there are for this issue and for now I have chosen to create a proxy server that uses https and will forward the request. If you know a better way except not using http let me know. I am not using https because I cannot change that system.
I am rendering images on my website this way.

<img src="http://image.com/image/12" />

I am wondering if it is possible to use the proxy inside src attribute. Something like

<img src="https://someproxy.com/http://image.com/image/12" />

I am using django and I could also try to make the request in python and send the image to the dom. But since I have already configured the proxy I want to try using it inside src attribute.

dense slate
#

it's misspelled again, are you making the changes?

nova sonnet
#

yeah just had to clear the cache

#

yet it aint working

dense slate
#

It might have something to do with the 'community/<int:pk>/create-question/ and 'community/<int:pk> urls

#

Do they all need / at the end?

#

But then you wouldn't see the page either... 🤔

nova sonnet
#

yeah i added it when the other guy told me to

dense slate
#

but not to all of them

nova sonnet
#

i have no idea why the view just doesnt want to work

manic hearth
#

Hi Guys

#

I want to do something like that

#

using django rest framework

#

can anyone help me?

nova sonnet
dense slate
#

You can, for example, return a json object via DRF but that's very general and you would need to share what you're trying to accomplish.

native tide
#

hello why i get this error: ImportError: cannot import name 'Oauth' from 'oauth' i just copied swastik

nova sonnet
#

Everytime I was submitting they were being left out so it wasn’t being validated

vital crest
#

hey guys

#

im writing an API i should use which name formatting??

#

camel case right??

dense slate
wispy niche
#

Question Web Dev Friends,

Are you able to use any/most bootstrap templates with Django?

eternal blade
ionic raft
rustic sky
#

Hi all, I'm struggling with finding analytics for my site...

#

Was going to decide Google Analytics, but that's a privacy compromise

#

was told about https://ackee.electerious.com/ and other self-hosting solutions
but I've never self-hosted something like that before and I'm not sure what I'll do if my site ends up blowing up

#

(using DigitalOcean

manic warren
#

how to use ajax in django

tough crane
#

Quick stupid question I didn't find an answer to, but is it possible to link an image in css / scss file that is online? Or do I have to have them localy? nvm I just had a typo. fml

opaque rivet
#

@eternal blade what are your DEFAULT_AUTHENTICATION_CLASSES in settings.py?

#

My guess is you have some middleware requiring a token.

eternal blade
#

knox.auth.TokenAuthentication

opaque rivet
#

So that means that all your views have the knox.auth.TokenAuthentication middleware which requires a token, I'd find a way to take that off your LoginAPI view

eternal blade
#

Thanks, I'll try to do that

opaque rivet
#

Are HTTP requests between docker containers SSL secured?

green prairie
#

Does anybody have any good resources on modern web design? (Not web development, but actually designing beautiful websites)

inland oak
#

with 90% there is no SSL in between

#

unless you set it on your own

worthy lake
green prairie
#

Perfect - Thanks a lot! I'll check it out 🙂

inland oak
#

I went so far with firewall option

opaque rivet
#

Ah, thanks, not looking to do it just wondering.

inland oak
#

beware, UFW firewall is not working for docker 😉 due to some conflict in records

#

but iptables works

tulip beacon
#

hey guys, how can I make it so that when I close the sidebar, the elements on the white background must occupy the area of sidebar and when I close it, do the opposite...

fossil pond
#

Hey can we ask HTML and JS queries here?

native tide
#

no they need to run in a browser

#

i think you can get bots to render html. not sure about js

#

that was a joke btw

rotund perch
#

Hello, is there a way to unregister Token from the admin dashboard the Token im using is from rest_framework.authtoken.models import Token.
When I try to register it in the admin it displays two Token tables

manic frost
fossil pond
west arrow
eternal blade
glacial yoke
#

If I have a function in django views.py, how can I call that function in my react frontend app, when for example pressing a button, which is displayed on the website?

opaque rivet
#

@glacial yoke you're looking at making an API endpoint and making http requests to it from your frontend.

glacial yoke
#

by api endpoint, do you mean an APIview?

#

and also, how could I make an http request to one?

opaque rivet
#

@eternal blade I'm on my phone, but what I can tell you is that authentication class is default so it affects all views.

#

@glacial yoke You can use JS. A request lib like axios to send http requests.

glacial yoke
eternal blade
#

So should I remove knox.auth.TokenAuthentication from the settings.py and then make all classes (except the LoginAPI) inherit from knox.auth.TokenAuthentication

glacial yoke
#

But then how do I call it?

opaque rivet
#

@eternal blade yes, maybe it has some docs on how to set the authentication class on a view.

eternal blade
#

Thanks lemon_pleased

opaque rivet
#

Here is an example for how to set the authentication / permission classes on a view

eternal blade
#

Thanks

opaque rivet
#

@glacial yoke axios.get returns a promise. To access the response you can await it or have a .then() block

glacial yoke
#

and then, would I just stick the function into a button, and it should work, right?

#

and also, can you please show me an example of a proper api view, because I'm not too sure how to set it up

pearl quiver
#

hello, I have a question regarding FLASK.
My FLASK application sometimes has to process a folder of files, and I would like an update to come back as they're finished.
But right now, it's like:
@app.route('/processfiles'): def processfile(): for x in dirname: process_file(x) return "status text"

#

and that status text doesn't get returned until everything is finished

#

is there a term I can google to get more information ?

dense slate
#

What kind of update?

pearl quiver
#

so let's say i'm processing 100 files ... ideally i would like output after each file is done. filename and success/failure code

dense slate
#

Just in the terminal?

pearl quiver
#

no, through the browser using FLASK

dense slate
#

You would need to probably handle the for loop on the front end in that case, and print something for each thing it iterates over.

#

return the context/array, and iterate on the front end, printing for each item.

pearl quiver
#

the problem is that FLASK only takes 1 return, and that return gets put on the page

#

i could be wrong because i'm new at this 🤔

dense slate
#

Hmm, Is see what you mean... I'll have to think about it.

#

Maybe handle it like a % done indicator?

pearl quiver
#

I can do it in the terminal no problem

#

it's getting it to do it in the browser i'm having trouble with 😅

dense slate
#

Yea, so I would probably look into how to setup a % status complete indicator on the front-end.

#

And just print "done" instead of changing the %.

pearl quiver
#

great, thanks! I'll take a look

dense slate
#

How long does it take to process the folder?

pearl quiver
#

it depends on the time of the month but between 10-20 mins

#

there are a bunch of excel sheets to lift info off of and screenshots to be made

#

it's for a local application, so requirements aren't high

#

but people get suspicious when the page just says "loading" for that long 🤣

pearl quiver
#

thanks! except I probably can't do celery or redis 😅 but i'll take a look. maybe I just need the idea
it's cuz we're on windows because of Excel

warm goblet
#

Hello..I want to learn django..but since moat of the tutorials are on django 2 ..what should i do

glacial yoke
warm goblet
#

Thanks @glacial yoke ...

dense slate
warm goblet
#

Thanks @dense slate .

fast lava
#

hello

#

does anyone know django

#

Pls help me here

nova sonnet
#

for django is there a way to pair contexts? im iterating a qs with users and im trying to get a count of related objects using a filter

rotund perch
#

u mean u want to count the objects that is returned after filtering it?

nova sonnet
#

I want to count all of the objects set for that user

#

but i want to filter that objects set

native tide
#

I'm trying to decide on Django REST framework or FastAPI for my backend for a new project I want to work on. Anyone have any suggestions or experience with either of those?

rotund perch
nova sonnet
nova sonnet
rotund perch
#

for user in users?

nova sonnet
#

yeah i have a user qs, and im displaying a list of users, i want to show a count for all of the objects set for that specific user with a few filters on too

rotund perch
#
for user in users:
   objects = user.objects.all()
return objects.count()

something like this? btw I am just trying to help you with how I understand what you said, sorry if I did not understand you well

nova sonnet
rotund perch
#

if its correct, just replace it with the blocks

tawny pollen
#

hello I have a django question

tawny pollen
#
def forms(request):
    inital_dict={
        "text": "Some initial data",
        "integer": 123,
    }
    form = TestForm(request.POST or None,initial=inital_dict)
    data = "None"
    text= "None"
    if form.is_valid():
        data = form.cleaned_data
        text= form.cleaned_data.get("text")
    return render(request,'first_app/forms.html', {'form': form,'data': data, 'text': text})

is it okay to remove "or None" inside TestForm?

nova sonnet
#

Yeah like that I’m trying to figure out how I can get a count of all related objects through the template or if I can pass it as another object but still have it related to that specific user

rotund perch
nova sonnet
nova sonnet
rotund perch
nova sonnet
#

im iterating through a list of users and they all have objects related to them

#

so they are linked through an fk

rotund perch
#

oh u mean u want the user who matches the fk of other models?

nova sonnet
#

kinda and i need to display the list of each user and data that relates to them

rotund perch
#

is it one fk ? or multiple

glacial yoke
#

I've got a login system using django social auth app, and it has it's own integrated sessions and etc.
I'm trying to make a function which would find out if the user is logged in or not, can someone help me with that?

glacial yoke
#

I don't really need to, because if a user is logged in, they'll just have a permanent session

#

until they log out of course

rotund perch
glacial yoke
#

I’ve been looking for this for the past 2 or so hours

rotund perch
glacial yoke
# rotund perch np

Btw, how could I request this function from react front end, for example if I wanted to render the log in button if the user isn’t login, but if he is, I would render the logout button

#

Would I have to create an apiview?

rotund perch
glacial yoke
rotund perch
glacial yoke
#

yeah, but jwt is probably easier to manage, especially using DRF

odd nova
#

hii
this question is a bit more about electron but I think I can ask it here?
I wanted to call a function in a .py file using electron, without having to use stdout, stdin, etc
is that possible?
I only found stuff about python-shell so far, which doesnt fit my requirements...

rotund perch
rotund perch
glacial yoke
rotund perch
glacial yoke
#

ok, I need it to be permanent, so it's fine

dense slate
#

Permanent tokens aren't safe so make sure you're not doing that in a sensitive app.

odd nova
#

specificly
I dont want to change the function

rotund perch
odd nova
#

acess it
my idea is to use the data that the python function returns to me to build the page

#

well
i mean

#

whatever
if it returns only text of the result i can use it as json, right?

#

i just havent found how to get anything from it

rotund perch
#

u can convert it to a JSON object instead of making it an array

#

but idk how electron works tbh, is there a way to import files?

rotund perch
dense slate
broken mulch
#

Hello guys if my frontend is React how would I store tokens generated from backend? I can’t even see HTTP headers

#

localStorage and document.cookie doesn’t seem to be very secure

rotund perch
broken mulch
#

And about WWW-Authenticate response header, how would I do that in frontend React?

broken mulch
#

How

#

Axios.get to backend?

rotund perch
#

No its a react library

broken mulch
#

Then backend respond with WWW-Authenticate

broken mulch
#

And I usually use fetch

rotund perch
#

U will get response data and take token from it

broken mulch
#

I can get token but how do I store it

#

In user’s browser

#

I cannot make httpOnly cookies

rotund perch
#

idk that sorry

broken mulch
#

Nor use Authentication

#

Unless I use a template rendering tool which I am not planning to

#

Since I’m using React-router-dom

dense slate
#

If you just have a permanent token, why not just use sessions with django auth?

dense slate
#

That's the way you should be storing them, as httpOnly cookies.

odd nova
#

I will use a separate file
That once runned
Will get a specific module and function
Using the string values passed by this system
That is a good enough workaround my issue I guess

broken mulch
opaque rivet
broken mulch
#

Like login session

#

How do I remember a user

#

I’m going to host my website on netlify so my backend would just act as a database and REST API

broken mulch
dense slate
#

Oh access them.

broken mulch
#

I need a secure way to store login sessions

dense slate
#

I set the access token in state, and then use an httpOnly refresh token to refresh it upon refresh or opening a new window.

broken mulch
#

Hmm

dense slate
#

After each refreshToken is used, you set it to invalid in the DB and assign a new one.

broken mulch
#

I don’t really understand can u map it?

dense slate
#

When a user logs in, return the access token to React and set it in state.

#

Along with sending an httpOnly refresh token into a cookie.

#

Use the access token until it expires or state is cleared, such as on a refresh.

#

When the access token is invalid in that case, use the refreshToken to silently grab a new token and reset the state.

broken mulch
#

Yes

dense slate
#

and repeat as necessary.

dense slate
broken mulch
#

How do I know refresh Token in React then

opaque rivet
#

damn, why can't you just save it as a non-http cookie? 😂

broken mulch
#

If the state is reset

dense slate
#

You grab it on the backend.

opaque rivet
#

sounds complicated

broken mulch
dense slate
#

Wait no, sorry. I use django-jwt to run a functionin React to run a refresh command on the backend. That function grabs the token from the browser.

broken mulch
#

I see

dense slate
#

The refreshtoken is saved in the DB

#

so it validates it against that

#

when it uses it, it invalidates it and sets a new one in the DB

broken mulch
#

How does Django-jwt run a function in React

dense slate
#

that last part to invalidate is just extra security.

#

I don't know, the library handles that. 😄

broken mulch
#

kk

#

I’ll check it out

#

token-security-conversation

#

^^^ ignore that I just need that to control-search later

dense slate
nova sonnet
#

hey is there a good way to get a count of all related prefetched objects?

dense slate
#

backend?

#

on the query?

#

Query.objects.count()?

nova sonnet
#

I wanna display it on the template

dense slate
#
qcount = Query.objects.count()
return render("page", {"qcount": qcount})
fossil pond
#

Hey guys. I wanted to make a Django website where the window is divided into two divs of equal size. The left side has links and the right side has an image. When I hover over any link the image should change on the right as per the link without the page reloading. The images and the links would be dynamically added from the backend using models. Is that possible?

dense slate
#

Then use qcount in the template.

dense slate
fossil pond
dense slate
fossil pond
#

By new content I mean link and image

nova sonnet
dense slate
dense slate
fossil pond
nova sonnet
dense slate
#

So you need to query the right thing first, and just add .count() on the end

#

So filter the query to get the stuff you need.

#

query.objects.filter(group="correct_group").count()

nova sonnet
#

because i want to display a list of users and a count next to each user

dense slate
#

What exactly are you counting?

broken mulch
#

Anyone good in CSS know why this is happening?

#

When I change overflow-y to scroll it just does that

#

The middle row is the exact size of the container div if that helps

#

this is the container div:

.rightSlide {
    overflow-y: scroll;
    position: absolute;
    display: flex;
    flex-direction: column;
    height: 100vh;
    width: 6vw;
    margin-left: 85vw;
    margin-right: 2.5vw;
    justify-content: flex-start;
    align-items: center;
    -ms-overflow-style: none;
    scrollbar-width: none;
}
nova sonnet
# dense slate Elaborate on this.

there is a m2m relationship between my users model and custom group model, I have a page listing all of the users within a certain custom group, I also have objects such as 'questions' that are linked to the custom groups and users, how can i get a count off all of the 'questions' that are linked to the user and group

dense slate
#

Btw, you can also {{ qobject.count }} in the template

#

if that helps

broken mulch
#

this is react-calendar

.rightSlide .react-calendar {
    position: absolute;
    margin-top: 25vh;
    background-color: gray;
    color: white;
    border-radius: 10px;
    padding: 10px;
    width: 20vw;
    height: auto;
}

I tried z-index but that’s not the issue

glacial yoke
# glacial yoke I've got a login system using django social auth app, and it has it's own integr...

this is refering to my old so called problem
so I've set up a social authentication in my django app, and whenever someone logs in a jwt token is made to manage their session
firstly, how can I refresh this token, if it expires when the user is active
and secondly how can I check on my react frontend if the user is signed in or not, would I just check if the jwt token equals to none, but how exactly would i be able to refer to this session, because I can't really refer to a user, because he is "anonymous", because he is not logged in yet

dense slate
#

This might have your answer.

nova sonnet
nova sonnet
nova sonnet
dreamy jewel
#

Hi

#

I need website for my startup

dense slate
#

You have a list of users.

#

You want to count the questions that belong to both the user and the current group and show it?

nova sonnet
#

correct

dense slate
#

So like... Questions.objects.filter("user"=user).filter("group"=group).count()?

#

I'd have to see your models i think.

nova sonnet
#

well to display the users i got community.users.all()

dense slate
#

oh yea ok, show your models

nova sonnet
#

what part would you like to see?

dense slate
#

You're probably going to be best off doing something like adding a method to your model class where you pass the user and group ids into the method and then in that method query the questions where user and group equal those ids. Then in the template, make a for loop that runs that method for each user in the group.

#

That make sense?

nova sonnet
#

hmmm

#

can you give an example

dense slate
#

Give me a moment and I can.

#

so under your model class, you'll have a method like

def count_stuff(self, user, group):
  qcount = Questions.objects.filter(user=user).filter(group=group)
  return qcount
#

In the template, you'll make a for loop, and inside of it you'll do {{question.count_stuff}} for each user

(question is the model class name that you returned to the page earlier)

nova sonnet
#

what model would this go under?

dense slate
#

The user

#

so in the for loop you'll do {{user.count_stuff}}.

#

Because you originally queried users right? to display?

nova sonnet
#

yeah

#

so how would it get the group?

dense slate
#

On the page, are you only querying the user or the user and group?

nova sonnet
#

im querying the users through the group

dense slate
#

Show me your queries and how you display them in the page. When I just have bits and pieces I can't give you solid examples.

nova sonnet
#
        community = Community.objects.get(id = self.kwargs['pk'])
        users = community.users.all()
        context['users'] = users
        return context
#

hopes this helps

#

thats how im querying the users

dense slate
#

And community is the group?

nova sonnet
#

yeah

dense slate
#

So users is just the users in a particular community already?

nova sonnet
#

no, users and community are m2m

dense slate
#

but you're getting community.users, so users is the set of users in that community, yes?

nova sonnet
#

oh yeah mb read that wrong

dense slate
#

so in the User model, write a function/method that states:

def count_questions(self, community):
  count = Question.objects.filter(author=self).filter(community=community)
  return count

Right? That gets all the questions for those two variables.

#

in the template:

{% for u in users %}
  {{u.name}}: {{u.count_questions}}
{% endfor %}
#

that will list the question count for each of those users in that community

#

so you just have to modify that however you need it

nova sonnet
#

so would author = self, and how would the community get passed into the method?

#

sorry if im being slow

dense slate
#

Ah right, so that might have to be pulled from the URL. Maybe put request in the method like the above edit and pull the communty id from your URL.

#

Trying to think of another way but that's the first way that comes to mind.

nova sonnet
#

im able to pass in the request?

dense slate
#

request.GET.get['whatever_variable']

#

See if you get an error trying it.

nova sonnet
#

how would i implement it in the template though

#

to pass the request?

dense slate
#

Yea you can't pass that. Hmm I'm trying to think how to get that variable in there.

#

You might need to create a custom templatetag

nova sonnet
#

yeah i heard about that but i try to avoid it

dense slate
#

But I feel like there's another way. I just can't think of it now. I'll look at it again later.

dense slate
#

I think using sets will get you there but I don't have a lot of experience with that.

native tide
#

yo

#

is <html> </html> considered containing tags

celest ferry
#

Was following programming with mosh's beginner django tutorial and keep getting this error when trying loading it. Any ideas?

#

I'm assuming its the "running scripts is disabled on this system"

#

Figured it out, for someone reason vscode default terminal to powershell 😴

solar lodge
#

Hello, I am building an API for my website and when the user is being rate limited I don't want to display an error but rather do..nothing. Would anyone have a good way of doing so? I am using Quart to do it.

lethal junco
#

I'm having a difficult time with my django, can someone help me? I'm getting this error on my front-end

#

here is my form tags

#

don't know what went wrong 😩

toxic hemlock
#

hey y'all i'm making a web app in flask and i want to have my log in involve a redirect but i want the redirect to have all the html form info to be invisible in the url of the page the user gets redirected to, i.e. like using POST, but when i do the redirect i end up getting the info in the url. for example, if the user's username is "zeljko", the url will be something like "localhost:5000/dashboard/zeljko". i don't want the "zeljko" to be there, meaning something like "localhost:5000/dashboard" while still having access to the form data. is there any way around this? here's the code with descriptions if it helps:

## /join pulls directly from the method="post" form on login.html, where the user logs in
@app.route("/join", methods=["POST", "GET"])
def join():
    username = request.form.get("username")
    ## basic log in logic, checks if passwords match and if user is verified, etc.
    ## if all matches, then:
    return redirect(url_for("dashboard", username=username))
    ## if not, then:
    message = "Looks like the username and password don't match."
    return render_template("login.html", message=message)

## /join redirects to /dashboard when login is successful
@app.route("/dashboard/<username>", methods=["POST"])
def dashboard():
    username = request.form.get("username")
    return render_template("dashboard.html", message=username)
toxic hemlock
#

nvm i got it lol

lucid marsh
#

I have a flask app, running on AWS Instance, i want to make some kind of websocket to sync a slider, i've tried flask_websocket but it doesn't seem to work.

Question is:
Does anybody know how to serve a websocket with one flask app?

#

i also used python socket, it works for both server and client, but... i cannot combine it on one ip address

native tide
#

How to interface the esp8266 with python

#

How do i send serial data over wifi???

thin lance
#
class DeleteContact(ListView):
    model = AdressEntery
    template_name = "main/contact_list.html" 
    context_object_name = "contact"
    def get_queryset(self, *args, **kwargs):
        queryset = super(DeleteContact, self).get_queryset()
        return queryset.filter(id=self.kwargs['pk']).update(active=False)```
I need help in Django, how to redirect the url?
i know this method contains http_method_not_allowed ()

in html form there is a link that looks like this: http://localhost:8001/api/contact-list/delete/35 - and after clicking on the link it leaves me on that same page
and I want it to redirect me to this page: http://localhost:8001/api/contact-list/ - shows contacts
inland copper
#

yy

lavish prismBOT
#

:incoming_envelope: :ok_hand: applied mute to @inland copper until <t:1630572378:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).

eternal blade
#

RIP

glacial yoke
#

i decided to use webpack and babel to bundle and transpile my react frontend, and now I have problems with my project
I get this error when I runserver in django

"GET /main.js HTTP/1.1" 404 4309

this is my webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.resolve(__dirname, "./build/static/js"),
  },
  module: {
    rules: [
      {
        test: /\.?jsx$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        },
      },
      {
        test: /\.?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        },
      },
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|jp(e*)g|svg|gif)$/,
        use: ['file-loader'],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, "./build/index.html"),
    }),
  ],
};

this is my babel.config.json

{
    "presets": [
      [
        "@babel/preset-env"
      ],
      "@babel/preset-react"
    ],
    "plugins": ["@babel/plugin-proposal-class-properties"]
  }

these are my dev dependencies in package.json:

},
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "babel-loader": "^8.2.2",
    "html-webpack-plugin": "^5.3.2",
    "webpack": "^5.51.1",
    "webpack-cli": "^4.8.0",
    "webpack-dev-server": "^4.1.0"
  }

and this is how it manages static files in settings.py:

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

STATICFILES_DIRS = [
    os.path.join(PROJECT_ROOT, 'apps/frontend/build/static')
]
dawn shard
#

So I am taking input from users in number. How can I add all and print it on a page?

neon osprey
native tide
#

I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE.I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.

glacial yoke
neon osprey
#

It's my first time doing a full stack web application and i've got no idea at the moment as to why it's not loading, certainly feel like missing part of the puzzle unless i've overlooked something!

worthy lake
#

These labels for my models... what class and attribute can I change these labels in admin.py?

heady quail
#

This pattern worked in Python for Regex, but lookbehinds like this aren't allowed in JavaScript or something?
How do I convert this into something that works in JavaScript? I don't know JavaScript or Regex well.
The regex is trying to match words beginning with underscores but not words with underscores inside them - works fine in Python.

regex = r'(?<![a-z])_[a-z]*'

Edit: For my purposes it was fine to not do the look behind and just use a character like ![a-z])_[a-z]*

glacial yoke
glacial yoke
#

Right here the problem is, that it's searching for the static files in localhost:8000/main.js

inland oak
#

should not it be index.html?

glacial yoke
#

and not just grabbing it from static files

inland oak
#

I thought React built files look like html/css/js files

#

have you made React build?

glacial yoke
#

So it's literally just an html file and a main.js file

#

the main.js file is inserted into the html

#

django can get the html, but for some reason not the main.js

inland oak
#

Right here the problem is, that it's searching for the static files in localhost:8000/main.js
I thought you expected to search at this route

#

which route you expected to have?

#

according to your settings

#

/static/main.js

#

should be current address of this file probably

#

if you want your static files served without /static/

#

change STATIC_URL variable to /

#

or explain your problem further

glacial yoke
#

ok, this is what's happening

#

this is how it looks in my frontend app

inland oak
#

right

glacial yoke
#

and this is how it looks in the main directory/static

#

pretty much, what django does, is it take all the files from the staticfiles dirs, as it's stated in settings, and puts all of them into the main directory/static, which is the static root

#

and then from there it should display them onto the website

inland oak
#

yes

#

and what's the problem?

glacial yoke
#

the problem is that it's searching for main.js's directory as localhost:8000/main.js, when quite literally it's not a website directory, so it should search for it in the website files(static files)

inland oak
#

the correct path should be /static/js/main.js for this file

glacial yoke
#

yes

inland oak
#

so... your links in frontend are broken to search main.js at /main.js url

#

that's your problem?

glacial yoke
#

could be

#

let me check

#
<script defer src="main.js"></script>
#

it looks fine in the html file

inland oak
#

so, you have relative path written here

#

you access index.html at folder /

#

relative path searches for the file in / (the same path as /index.html is)

#

it worked correctly.

#

<img src="picture.jpg"> The "picture.jpg" file is located in the same folder as the current page

#

if you wish to access the file from /index.html... you have next options:

#
  1. changing path to "js/main.js" | "static/js/main.js" or something like that
  2. changing to absolute /static/js/main.js
  3. changing static_files in django settings, to collect all statics into one level folder instead of having sub folders (it will lead to collisions for same named files)
  4. perhaps there is some webpack/react/frontendframework solution I don't know, like using some special flag during front building
glacial yoke
#

ok, thanks

native tide
#

Morning everyone.......I have been trying to create an API using rest framework that allows user react to a comment and I got stuck somewhere....Anyone familiar in DRF?

real herald
#

hi there i am a complete beginner to web development in python. i don't know python even. from where do i start?

real herald
#

yes

inland oak
#

then starting from here could be an option

real herald
#

thanks

inland oak
#

is it your first or not first language?

real herald
#

first

inland oak
#

uh.

real herald
#

?

inland oak
#

then optionally you could try some Head First book

#

Something like this

real herald
#

idk they're too long sort of like 2000 pages, can't i have something short?

inland oak
#

they are really easy to read and understand

#

they have a lot of pictures

real herald
#

yeah i'll try both

#

thanks

uncut geode
#

I'm currently working on my small Flask project and I got stuck at some point. I got stuck on Response method because it doesn't work as I expected. When I use it in my code it's available only in 1 tab unless I run it with Gunicorn with more workers and threads, but that's not what I want. I want it to be accessible in multiple tabs with same content. Is there maybe some other method that I should use?

fast lava
#

Hello

#

Does anyone here know django well

thin lance
thin lance
# inland oak there is literally `redirect` function https://docs.djangoproject.com/en/3.2/top...

Thanks for the answer, I found a solution to this with the help of override method

class DeleteContact(ListView):
    model = AdressEntery
    allow_empty = False
    template_name = "main/contact_list.html" 
    context_object_name = "contact"
    def get_queryset(self, *args, **kwargs):
        queryset = super(DeleteContact, self).get_queryset()
        return queryset.filter(id=self.kwargs['pk']).update(active=False)   # filter by clicked contact card get id and set active false
    def dispatch(self,request, *args, **kwargs):   #this method allows us to use methods such as (post, get, put ..) and allows us to return HTTP methods such as (response, redirect)
        super(DeleteContact, self).dispatch(request)  #dispatch method will override the second method and allow us to do redirection
        return redirect('/api/contact-list/')
fossil pond
fossil pond
#

Redirection was working up until I changed the name of the html file

spiral moon
#

What a chaos car 😸
But I start liking it's drifting 😁

#

Btw, of you want to make more points for the 3k needed, stay in Pro league.
Very slim races in Elite, I needed to quit EIGHT races to get back to Pro as there are almost no races except 1v2 or so...

versed python
#

Looks like Asphalt 9

#

Was a nice game

spiral moon
#

Oh 😁 sorry guys

native tide
#

Guys, I have a question related to Django

#

Can I ask here?

opaque rivet
#

@native tide go ahead

native tide
#

I am trying to use Model Form's with class based views but I can't get the submit button to work
Here's my code

my forms.py

from django import forms

from .models import Volunteer


class VolunteerJoinForm(forms.ModelForm):
    class Meta:
        model = Volunteer
        fields = '__all__'

my views.py

from django.http.response import HttpResponse
from django.views.generic.edit import FormView

from .forms import VolunteerJoinForm


class VolunteerJoinFormView(FormView):
    template_name = 'website/join.html'
    form_class = VolunteerJoinForm
    success_url = '/join-success/'

    def form_valid(self, form):
        return HttpResponse('DONE')

my join.html template

{% extends 'website/_base.html' %}
{% block title %}Join Us{% endblock title %}
{% block content %}

    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit">
    </form>

{% endblock content %}
#

Whenever I click on the submit button, I get redirected to the same form page join.html

#

And no data is getting saved into the db

#

basically submit is doing nothing

sudden gulch
#

you have to define the get method and post method

native tide
#

In my CBV you mean?

sudden gulch
#

yes

#

see my code

#
class Events_view(View):
    model = EventForm
    events = Event.objects.all().order_by('-updated_at')
    context = {
            'events':events,
            'form':EventRegistrationForm,
           }

    def get(self,request,*args,**kwargs):


        if(len(self.events)==0):
            
            messages.info(request,"no events for now.")
            return render(request,'events.html')      

        return render(request,'events.html',self.context)

    def post(self,request,*args,**kwargs):

        form = EventRegistrationForm(request.POST)

        if(form.is_valid()):
            form.set_event(request.POST['event_name'])
            form.save()
            messages.success(request,"form submitted",extra_tags="success")
            

        return render(request,'events.html',self.context)```
#

see ive overrided get and post and returned rendered response according to that

native tide
#

I will try to do as you told me and get back to you

#

Can you please format your code, it's hard to read on Discord

sudden gulch
#

hey i want to post code like you did

#

how to do that

#

im new to discord

native tide
#

Surround the code with three backticks

sudden gulch
#

ok

native tide
#
\```
\```
sudden gulch
#

done

native tide
#

Try to write the word python right next to the first set of backticks at the top

#

it should also add syntax highlighting

sudden gulch
#

ok

fossil pond
sudden gulch
#

not response

#

same in render(request)_

#

if i correctly understood your code

fossil pond
sudden gulch
#
  def projects(request):
    return render(request, "projects.html")
#

try this

sudden gulch
#

what is the error saying

fossil pond
# sudden gulch what is the error saying

Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/projects/undefined
Using the URLconf defined in .urls, Django tried these URL patterns, in this order:

admin/
debug/
[name='home']
projects/ [name='projects']
portfolio/ [name='portfolio']
The current path, projects/undefined, didn’t match any of these.

You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

#

it's getting redirected to undefined

sudden gulch
#

strange

#

code is correct

fossil pond
#

stays at projects for a while

sudden gulch
fossil pond
#

and then goes to projects/undefined

sudden gulch
#

are u using js in this html

fossil pond
sudden gulch
#

so check if u write some redirect code there

sudden gulch
#

you can redirect using js also

#

so if u wrote some js code which redirect you to some value

#

because undefined is a js data type

fossil pond
#

ah makes sense

#

thanks

manic crane
#

How to display the names instead of pk in the list viewset in Django Rest Framework?

manic crane
#

ive read it before but ill see

manic crane
opaque rivet
#

@manic crane what did you try, exactly?

#

You can override the .to_representation() method of your serializer, or use StringRelatedField

dense slate
#

I'm getting this error in React:
Warning: [object Object]: ref is not a prop. Trying to access it will result in undefined being returned.
However I used this exact code in another project and it was working. Is ref just bugging out here or can I really not use it? I don't get this error in the other project.

rotund perch
dense slate
fast lava
#

Is there anyone here

#

well if anybody knows Django

supple lantern
#

I want help in django please
when I open django admin dashboard then all model tables are show but add delete edit option not showing?
what should I do?

ionic raft
supple lantern
supple lantern
#

no

#

should i run for this?

ionic raft
# supple lantern no

python manage.py migrate is required to make the changes to the DB. makemigrations is just prepping the files for the change

ionic raft
ionic raft
#

You use admin to edit or delete records. But the DB structure is all driven by models.py and makemigrations/migrate commands

supple lantern
ionic raft
supple lantern
supple lantern
ionic raft
supple lantern
#

will do it

ionic raft
ionic raft
# supple lantern thanks a lot

You're welcome.
As a tip, I backup with version control before makemigrations and migrate. Those two commands can have interesting results if your model is not perfect.

supple lantern
#

oh okay got it

ionic raft
#

The only time I've ever needed to hard reset a git branch was on changing the model and having a field setting incorrect. In particular, default values for image fields are nasty if you get them wrong.

grave raft
#

I am using django-rest-knox everything like login and register from postman is working fine but I can not create user from admin panel as it do not show email field
Do I also have to update admin.py for django rest knox??

ionic raft
#

Django question: I have just created a new template with an image. In dev the template and image renders perfectly. In prod it will not load.
When pushing the new image to prod I can see the additional count in collectstatic. So I know the image is brought over. And bear in mind, this is an established prod deployment that has many images.
Why would an image in the same static directory successfully serving up images not load in prod when it clearly loads in dev? Using nginx.

The irony is, I'm only creating this page because I need to get a URL path to be able to render these images for articles.

quartz yacht
#

Does anyone know how to get context data within a function based view in Django?

#

I know how in a class based view, but that's not translating for me.

#

not translating in a function based view.

nova sonnet
quartz yacht
#

What if the data is in the model?

nova sonnet
#

what do you mean by that

quartz yacht
#

I have a function based view to create an object, and within that object I want the end user to select a specific object from the model to attach it to. Like, Book to Author, the user can name the book and then choose from a list of authors and assign the book to the author.

#

The list of authors is coming from the model.

nova sonnet
#

so you want the list of authors as context?

quartz yacht
#

I think so, yes.

nova sonnet
#

all authors or specific authors?

quartz yacht
#

Specific, I want to filter based on the user to entered the authors name.

nova sonnet
#

are you going to get the authors name through a form? if so you can access the POST/GET data through request.POST or request.GET

quartz yacht
#

Yes, I have a form that they'll be filling out.

nova sonnet
#

so I'd say filter the authors using whatever author the user puts in the form and pass that in as context, are you trying to access the data the user is inputting into the form?

quartz yacht
#

I want the user to select the author from a dropdown list

#

like this

nova sonnet
#

So what is the issue? Is it the drop down or filtering the authors?

#

Once you get the list of authors you can iterate it for the drop down

quartz yacht
#

I don't know how to get the list of authors from the model within a function based view.

#

I know how to do it in a class based view, not a function based view.

nova sonnet
#

And you want to filter the list of authors depending on the book title?

quartz yacht
#
 def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['form'].fields['author'].queryset = author.bjects.filter(customer_id=self.request.user)
        return context
#

No I want to filter the list of authors based on the creator

#

That's what I use for a class based view and it works well, but I want a function based view due to some extra processing and that's what I'm more comfortable in.

nova sonnet
#

What are you specifically filtering for when it comes to the authors because im a bit confused

quartz yacht
#

I want to list all authors, and then filter for authors that were entered by the logged in user.

#

For example, if there are 100 authors in the model, I want to only display the authors that I've entered myself.

nova sonnet
#

So you want to list all the authors the user can pick right and which ever one they pick all books from the author will be shown right?

quartz yacht
#

basically.

nova sonnet
#

You want the user to input it though a drop down or input?

quartz yacht
#

I want the user to select the author through a dropdown.

nova sonnet
#

Will the books only show when the author is selected or will it show before and after when the author is selected?

#

You’d want to pass in 2 querysets, one for the authors and books

quartz yacht
#

It's not that complex, I literally have a blank form, I want the user to enter a book title and then select from a dropdown list the author.

#

Book Name "Harry Pawter"

#

Select from a dropdown list of all authors that I manually entered.

ionic raft
#

Django question: I've deployed a web site in production through Docker/Nginx. When I add static images I can go to the docker container and collectstatic. Is there a way to configure the ngnix.conf file to update static files after the build? Currently, this is not happening automatically.

nova sonnet
quartz yacht
#

I can do a get within a post request, or would I perform it on the outside of the post request.

#

@ionic raft I can't answer your question specifically but Django has a 3rd party app called WhiteNoise that will allow Django to serve the static files no problem.

ionic raft
ionic raft
quartz yacht
#

btw @nova sonnet I really appreciate your help on this.

nova sonnet
#

You can check if there is any GET data through an if statement in the function (such as if request.GET: <do something>)

quartz yacht
#

Ok, I'll try to figure it out then.

ionic raft
violet dock
#
from flask import Flask, request, redirect, render_template, abort
from steambot import client
from panel import *
import multiprocessing
import steambot
import json


app = Flask(__name__,template_folder='template')


@app.route("/")
async def overview():
    return redirect("/prices")


@app.route("/prices")
async def prices():
    return render_template("prices.html", items=get_pricelist())


@app.route("/pricelist")
async def pricelist():
    return redirect("/prices")


p = multiprocessing.Process(target=lambda: __import__(steambot))
p.start()


if __name__ == "__main__":
    app.run(debug=True)```
 why my flask app wont start? only steam bot is running
vivid cobalt
#

guys so I am making a os and I dont know the place to go to!

ionic raft
vivid cobalt
#

well where can i go to make a os

#

...

#

do u know Grepper

ionic raft
#

I have no idea. And no, I don't know Grepper. This is a Discord for the Python programming language, and this particular channel is for web development using Python, typically Flask or Django

tawny pollen
#

hello django newbie here I have a question

stark tartan
#

How to get the request user in .save method in django

ionic raft
ionic raft
tawny pollen
#

path('author/int:pk/update/', AuthorUpdate.as_view(), name='author-update')

in the above path function, can i change int:pk to just pk ? like

path('author/pk/update/', AuthorUpdate.as_view(), name='author-update')

ionic raft
tawny pollen
#

is it better to use generic views or class/function views?

lapis stratus
#

Hello, "Unable to log in with provided credentials." I have this error but when I check the network tab and check the request payload my credential was correct.

neon osprey
#

Just searching for some more information, I'm trying to make an full stack web application with Flutter & Djanjo, but apparently if I do this, it's actully called a ' Progressive Web Applicaiton' ? Would you still call it a Full Stack Web Application?

lapis stratus
inland oak
patent cobalt
#

The other invites are also related to the question, right?

inland oak
#

yes

#

at least of them should be sent

#

they were leading to the same server

patent cobalt
inland oak
#

Code Monkeys discord server has OS channel too

#

yeah, thanks

patent cobalt
#

I'll add it to our allowlist

inland oak
#

preferably the first version,

#

which had /cm path

#

it looked more permament

opaque rivet
#

I've got a prod server with docker containers running. Say I wanted to push an update from dev -> prod, do I always have to git pull, then restart my containers? Or is there a better way about this?

inland oak
#

no attachments that pollute the server beyond your code, everything is version controlled

opaque rivet
#

But in either case, the prod server will not be usable once the update occurs right? So the website will be down?

inland oak
#

ansible => connects to servers => installs docker if it is missing => copies the code and builds the image and runs

inland oak
#

for example if you would be using Hetzner provider, they allow Floating IPs

#

temporally attached to any server

#

you could have it attached to your domain

#

and when you update

#

you... create new server

#

install, check that everything work

#

and then in one click reattach ip to new server

#

if everything goes ok, you destroy old server, if not, switch back

#

same could be done manually if you will have additional server with reverse proxy

opaque rivet
#

Cool, so essentially a second server on the old codebase while the main prod server gets updated. I think AWS has some feature like that too

inland oak
#

I think it is called Blue-Green deployment, when both environments exist at the same time

inland oak
#

switching accurately traffic from first to second one, while looking if we need to switch back in case of emergency

cerulean badge
opaque rivet
#

Say you had a domain and an A record that points to your prod server IP. Could you add a second A record to use if that first one can't connect?

#

Redirecting to a different server essentially

inland oak
#

you could have several servers raised with identical software

#

and distribute your user load between them

#

through DNS usage

opaque rivet
#

Hmm, this is definitely worth a read. I feel like there is definitely something out there with AWS that probably solves this. I'll have a look there later.

#

I appreciate the help :)

inland oak
#

you could ask, what would be issue, and why would it be primitive? Answer: there is no healthcheckers. If one of servers is down, % of users would be still sent to dead server

#

normal load balancers (like Haproxy) can have healthcheckers

#

sending only if the servers are alive

inland oak
#

quite loving a bit of devops. it makes life easier to devs.

opaque rivet
#

I'm liking it too. All started with Docker! Lovely to have on the CV too :)

inland oak
#

tbh I even decided having devops as my secondary direction

#

I'll first finish learning essentials for high level backend though

#

then I will dive in a more advanced devops

neon osprey
manic crane
opaque rivet
#

@manic crane OK, and how did "it not work"? Did you create a str method for your model?

#

question: CORS does not stop cross site forgery requests, correct?

manic crane
#

'Clique' object is not iterable

opaque rivet
#

What's your model

manic crane
#

AttributeError: type object 'CliqueSerializer' has no attribute 'StringRelatedField'

mystic wyvern
#

hi i want to know what these signs are called like r and w+ or $

opaque rivet
#

Need to see some code to be able to help.

foggy bramble
#

what is the point of using python venv inside docker image?

cerulean badge
#

(context django) best way to add a markdown editor for a textfield?

#

i am looking for something like the editor on stackoverflow

dusk portal
#

**where to start
Everyone wants to learn new skills and deciding which skill to learn is easy. But, the difficult part is WHERE TO START? People often get lost on this huge web in the quest of the best, personalized and easily available course.

Organized Learning
An issue we face when it comes to learning multiple skills is management/organization. It becomes hard to organize what, when, how and where you have to learn.

EdTech for Rural India
Urban and Rural students often face differences in terms of financial conditions, exposure, language, etc. despite this, they all deserve a friendly platform to learn.** which one i can do asap and easiest plz suggest

#

@opaque rivet @inland oak

strong palm
#

Is there anyone with experience architecting django?
I stand before the decision on splitting an app into small apps or modules but I do not have enough experience architecting django and some consultation would be very useful.
It's difficult to ask a more specific question on this topic.

inland oak
#

each django app has separate set of tests / views / model

#

best recomendation is usually separating into django apps, if you feel that those are two different entities and logically they should be tested separately

#

usually separating into another django app... comes from the size of the thing

scenic rune
#

how can i put the text on the picture and how can i make the picture on the whole screen?

inland oak
#

if you know that it will eventually be big one, feel free to separate, in order to not overbloat the current app

gusty wagon
#

Does anyone know if its possible to manage the search results of google by geo location? For example, when having a real estate listings website, and you are in New York... when googling for offices. You will get Offices in new york... But for real estate listing websites this is crucial. I want to show my top visited pages or most important ones, and not the one where the user is located at. Anyone have an idea how to tackle this? Please tag me.

opaque rivet
#

@gusty wagon could use the IP of the user to determine their location. Then show listings based off that.

ashen parrot
#

What can u do with web-development in python ?

cerulean badge
#

anyone worked with ckeditor?

manic crane
#

sorry for the late reply man

opaque rivet
#

it's fine, could you format the code to make it more readable?

manic crane
#

like that ?

opaque rivet
#

(3backticks)py
code
(3backticks)

#

!code

lavish prismBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

manic crane
#

oh okay 3 back ticks each

#

    class CliqueObjects(models.Manager):
        def get_queryset(self):
            return super().get_queryset().filter(level='public')
    options = (
        ('private', 'Private'),
        ('public', 'Public')
    )

    name = models.CharField(max_length=200, null=False, blank=False,default='')
    occupiers = models.IntegerField(null=False,blank=False,default='')
    created_at = models.DateTimeField(auto_now_add=True)
    occupation = models.CharField(max_length=90,null=False,blank=False,default='')
    level = models.CharField(max_length=10, choices=options, default='public')
   
    objects = models.Manager() # default manager
    cliqueobjects = CliqueObjects #custom manager

    def __str__(self):
        return self.name


class Post(models.Model):
    # filters posts so only published posts are avaible in the home screen .
    class PostObjects(models.Manager):
        def get_queryset(self):
            return super().get_queryset().filter(status = "posted")
    options = (
        ('draft' , 'Draft'),
        ('posted' , 'Posted'),
    )
    clique = models.ForeignKey(Clique, on_delete=models.PROTECT, default=1,related_name='cliques')
    content = models.TextField(max_length=400,null=False, blank=False,)
    caption = models.CharField(max_length=400,null=False, blank=False,)
    posted = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clique_posts',)
    status = models.CharField(max_length=12, choices=options, default='posted')
    objects = models.Manager() # default manager
    postobjects = PostObjects() # custom manager

    class Meta: 
        ordering = ('-posted',)

    def __str__(self):
        return self.caption```
opaque rivet
#

clique will always be a singular object, which is not iterable, hence the 'Clique' object is not iterable error

manic crane
#

ohhhh hmmmmm

#

time to problem solve & thanks very much

opaque rivet
manic crane
#

oh no i can make more than one clique

opaque rivet
manic crane
#

like i the drf request page it lets me make more than one clique

#

more than one post

#

wait actually just revised on one to many relationships

cerulean badge
#

i am getting this error
An invalid form control with name='description' is not focusable.
i rendered the form with crispyforms
and have this

<script src="https://cdn.ckeditor.com/ckeditor5/29.2.0/classic/ckeditor.js"></script>
  <script>
    ClassicEditor
        .create( document.querySelector( '#id_description' ) )
        .catch( error => {
            console.error( error );
        } );
  </script>```
what i got to know is that ckeditor makes the input hidden and it is required.
this error is raised when you submit the form because the input remains empty when validating
i added `blank=True` to description field but i want it to be required you know of a better solution?
manic crane
opaque rivet
manic crane
opaque rivet
#

it would be a step in the right direction

manic crane
#

thanks dude

opaque rivet
# cerulean badge which function?

Possibly you could make this into a function?

<script>
    ClassicEditor
        .create( document.querySelector( '#id_description' ) )
        .catch( error => {
            console.error( error );
        } );
  </script>
cerulean badge
opaque rivet
#

ah okay. wasn't sure what that does. i'm not sure then!

tawny pollen
#

i have a django question. can someone help me ?

opaque rivet
tawny pollen
#

the date doesn't show on the template. I am using generic views

opaque rivet
tawny pollen
#
class AuthorDetailView(generic.DetailView):
    model = Author
    context_object_name = 'author_detail'
    template_name = 'catalog/author-detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['author_list'] = timezone.now()
        return context
#

yes date time object

opaque rivet
tawny pollen
#

i heard you can do something like this : {{ book_detail.date_of_birth|date }}

#

or like {{ book_detail.date_of_birth|date:'Y-m-d' }}. but it didn't work for me

opaque rivet
tawny pollen
#

ok thanks. i'll try

light cloak
#

Does anyone know if it's possible in Django to access management form attributes inside a template? I'm trying to dynamically add new form fields but I think the management form TOTAL_FORMS field needs to be updated for extra forms to be submitted. Any ideas?

opaque rivet
#

what looks better?
1.

#

I prefer 1. because it fills more horizontal whitespace

light cloak
#

Yeah, 1

fossil pond
#

1 for sure

opaque rivet
#

thanks 👍

ionic raft
# ashen parrot What can u do with web-development in python ?

A LOT. Django/Flask are web development frameworks. Google sites built with Python and you'll see some big players come up.
Flask is great for getting going. Django is amazing for more complex sites (there's a link on my profile to a site I built with Django/Python. Didn't know any Python before April 16, 2021.

ashen parrot
#

oh

ionic raft
ionic raft
# ashen parrot oh

If you want a fancy front end you can add a JS Framework like React of Next.js to the mix. However Django/Flask are very powerful application layers. When you pair Django with a Postgres DB you have a stack that is truly enterprise ready.

ionic raft
ionic raft
opaque rivet
#

which color of button is better?

ionic raft
# opaque rivet

Interesting question. The bottom button has greater separation, and feels more suited as a CTA. However, if the text 'Let's dive in' is not clickable I wondering if it might distract...

opaque rivet
ionic raft
# opaque rivet

That said, once you pick your CTA colour and consistently apply, I say that lighter blue is better. It flows with the darker blue above and yet stands out.

opaque rivet
#

Ok, I'll remove the "Let's Dive in" and have them the blue color

ionic raft
opaque rivet
#

this is for the mobile view which is a bit different

opaque rivet
ionic raft
opaque rivet
ionic raft
#

Oooo...
Is UniHalls a hyperlink?

opaque rivet
#

Footer, redirects to main page

ionic raft
#

I have to say (and this is but one opinion) I definitely prefer the lighter blue, and a consistent CTA. But then that's a preference. I want to train the user to know what to click and they don't have to think about it.
With the clickable logo being the same colour that fits

#

What about 'Contact us' text also being the same CTA blue?

opaque rivet
#

Nice, I agree

opaque rivet
#

this is the view on a computer

#

and this for the mobile. added some shadows and I think it looks nice

ionic raft
#

In short, everything that is a CTA is that blue. And seeing the lighter blue on the darker blue...yes. I like.
I'd change the two buttons on the computer view to the lighter blue too

#

I'm a HUGE fan of button shadows...
Interestingly, I break my own rule with the Support and Signout buttons.
All text links are the light blue. But the signout I make white so that it stands as a secondary click.
Support is dark blue because I'm not looking to drive them to create support work for us 😄

opaque rivet
#

I think it looks worse. Maybe because of the "lets dive in"

#

Actually it looks alright... hmmm

ionic raft
# opaque rivet

Agreed. Either remove the Let's dive in, or change to dark blue.
But I think it's a redundant invitation.
Also, change 'contact us' to same lighter blue perhaps?

#

But then, you've posed the question...Ready to get started? This is the invitation. Let's dive in doesn't add anything. The buttons are clear implication for behaviour

fossil pond
#

Hello guys! I want to send {{projects.thumbnail}} object in Django (which contains an image) to onmouseover="DisplayThumbnail()" as a parameter inside DisplayThumbnail so that it can be processed by JS. Is it possible?

ionic raft
#

I would keep the space between the words and the buttons equidistant above and below. If you remove the dive in, keep the white space...And now that I think about it, keeping contact us as dark is solid option too. Contacting is not really a CTA

fossil pond
opaque rivet
#

@ionic raft I'll test out colors later, heading on a run.

#

@fossil pond you think light blue > black?

opaque rivet
#

Thanks! 👍

fossil pond
ionic raft
opaque rivet
#

I mean, for the color of the two buttons, on the light gray background

#

Aah, design is my downfall 😁😁

#

At least I can change things quick with tailwindcss

fossil pond
ionic raft
# opaque rivet I mean, for the color of the two buttons, on the light gray background

The lighter blue is definitely preference for me on the light grey background...
Here's my latest UI...very close colours to what I've gone with...
My big challenge was picking a CTA colour for a data rich experience. This is a portal for project management after all. In the end, making all text links that light blue really pulled them forward. I'll be curious what alpha testing reveals

ionic raft
fading wolf
#

Hi Everyone
As a JavaScript & PHP software engineer, I am looking for a full-time job using my skills recently.
If you have any jobs, please let me know.
Actions Speak Louder than Words
I hope your business is doing well
Thanks for your time.

thorny quartz
#

how I can make a login and registration in Django using email not username please help me anyone

#

is anyone there ?

true turret
# thorny quartz how I can make a login and registration in Django using email not username pleas...
Coding for Entrepreneurs

Coding for Entrepreneurs is a series of project-based programming courses designed to teach non-technical founders how to launch and build their own projects. Learn Python, Django, Angular, Typescript, Web Application Development, Web Scraping, and more.

#

HI Everyone.
I have been out of a job search again due to lack of experience.
how did you guys? They know of a project where I can collaborate with Django to gain experience

thorny quartz
#

I was looking for this for hours

glacial yoke
#

My project is giving me the error with status code 500, which means that I haven't got the same methods used in my http requests/api calls. Even though the methods are the same in both my django views.py, and my react frontend axios get function:

class UserView(APIView):

    def get(self, request):
function isAuth(){
    const response = axios.get("/user")
    console.log(response.data)
  }

this is the error:

createError.js:16 Uncaught (in promise) Error: Request failed with status code 500
inland oak
# glacial yoke My project is giving me the error with status code 500, which means that I haven...

u a using promise based js library
https://github.com/axios/axios

correct get requests with it:

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
#

speaking in python terms, you used coroutine function, which you did not await ;b

glacial yoke
inland oak
glacial yoke
#

Does it make much difference tho?

inland oak
#
const response = axios.get("/user")
console.log(response.data)

replace to

axios.get('/user')
  .then(function (response) {
    // handle success
    console.log(response.data);
  })
inland oak
glacial yoke
inland oak
#

while await I am not sure if will work, because it could be requiring additional requirements... like async env, what needs for that in js I have no idea.

glacial yoke
#

nope, it still gives the same mistake @inland oak

#

I've tried to add async and await to it

#

and it gave me this error:

#
Uncaught ReferenceError: regeneratorRuntime is not defined
#

oh right, that's probably because my babel config can't transpile it

#

give me a sec

#

ok, I fixed the babel part, but I still get the error 500

#

How else can I try to fix this? @inland oak

opaque rivet
#

@inland oak .then() is just syntactic sugar for await. However, I don't know how you'd handle errors (non 2xx) with await.

inland oak
#

Oh right, it is not js part

#

You have django crashing with 500

glacial yoke
#

Yeah, the error is definitely happening on the backend

#

but idk how to fix it

inland oak
#

Enable debug true

glacial yoke
#

it is

inland oak
#

And read

#

Resp o nse body

glacial yoke
#

from the console?

inland oak
#

Use .then, with error catching

#

.catch

#

And just read the error from response

glacial yoke
#
assert isinstance(response, HttpResponseBase), (
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`  
[03/Sep/2021 22:24:49] "GET /user/ HTTP/1.1" 500 80418
#

this is what it gives in console

inland oak
#

Or see django error log

glacial yoke
#

if it says anything to you

inland oak
#

In python

fossil pond
#

I am facing a certain issue with Django. When I upload picture to my model it gets saved on static/images but when I run the code it looks for the image in the folder static/images/projects (projects is the name of the html file

glacial yoke
#

It's returning json

inland oak
#

How it returns Json

glacial yoke
#

as a serializer

#
user = SteamUser.objects.filter(steamid=payload['steamid']).first()
        serializer = SteamUserSerializer(user)
        return Response(serializer.data)
#

Response() is a rest_framework function

inland oak
#

Looks legit

late gale
#

Hello can someone help me , when i type py manage.py collectstatic there's no css for the admin page while my static settings is

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
        ]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
late gale
#

hehe

inland oak
#

Really bad

opaque rivet
#

@fossil pond what's the code?

late gale
#

ok gonna remove it but i believe that wont create css admin

inland oak
#

No idea how u run the server

late gale
#

py manage.py runserver

#

normal way

fossil pond
# opaque rivet <@718466728320827543> what's the code?

urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('__debug__/', include(debug_toolbar.urls)),
    path('', include('main.urls')),
]


urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)```

settings.py:

```STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'main/static/images')
late gale
#

i have css for my admin on other site while they have the same static settings

inland oak
#

Enable debug then.
Runserver is for dev anyway

late gale
#

it's enabled

fossil pond
# fossil pond urls.py: ``` urlpatterns = [ path('admin/', admin.site.urls), path('__d...

projects.html:

                        
                        <ul class="list-group mx-auto justify-content-center list-group-flush">
                            {% for project in projects %}
                                <li class="list-group-item"><a href="#" class= "project-link" style="text-decoration: none;" onmouseover="DisplayThumbnail('{{project.thumbnail}}')"><span class="projects-title">{{project.title}}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="projects-summary">{{project.summary}}</span></a></li>
                            {% empty %}
                            <h4 class="display-4">There are no available projects as of now :(</h1>
                            {% endfor %}
                        </ul>
                          
                    </div>
                    <div class="col-6" id="ImageContainer"> 
                        <img style='height: 100%; width: 100%; object-fit: contain' id= "thumbnail" src="{% static 'images/rdr2.jpg'%}">
                    </div>```
#

project.thumbnail is the image basically

inland oak
#

Shrugs then.
Fell asleep

fossil pond
# glacial yoke check your templates code in settings.py

Didn't change anything its basically this:

    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]```
glacial yoke
#

how is it imported into your html/css?

fossil pond
late gale
#

hahaha

#

i have css admin in staticfiles folder

#

but not in static folder

#

gonna copy it and add it in static folder

#

they are the same so

fossil pond
#

Other than that it's all basic stuff

glacial yoke
fossil pond
#

Not Found: /projects/coolman.jpg
[04/Sep/2021 01:12:52] ←[33m"GET /projects/coolman.jpg HTTP/1.1" 404 3102←[0m (when I don't manually place the image inside the projects folder)

glacial yoke
#

wait, so if you are uploading the image to your model, then it should save in db, right?

fossil pond
#
    title = models.CharField(max_length=200)
    thumbnail = models.ImageField(null=True)
    body = models.TextField()
    slug = models.SlugField(null=True, blank=True)
    summary = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

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

Basically the thumbnail
glacial yoke
#

Yeah, I'm not sure if there is a way to fix this

#

only if you can somehow change the directory of where your images are saved if you upload it from local storage, because usually it is just saved as a link, and it can easily refer to it from anywhere

fossil pond
#

omg i fixed it!!

#

replaced project.thumbnail with project.thumbnail.url in the html

#

worked

glacial yoke
#

yeah, i was thinking that it had something to do with project.thumbnail, but wasn't too sure

#

well done

late gale
#

any image should has .url

#

since it directs to the url of the image from static folder

#

but nice

opaque rivet
#

Think I'm burnt out, think I just spent 2 hrs for a simple react animation

solar lodge
#

Anyone one the best way to make a select menu like this?

wide canyon
#

I want to start reading a few technical books. I'm starting from obey the testing Goat. Dies anybody want to join me? We'd act as accountability partners and discuss what we read at intervals

ionic raft
ionic raft
# glacial yoke wait, so if you are uploading the image to your model, then it should save in db...

That's a question that when I started to get answers became a rabbit-hole...uploading media....
In the end, I dropped profile pics and logos entirely. I opted to not use media entirely. If you upload images to the app server (/media/) then you lose statelessness and potential for load balancing. If you upload images to the DB other risks surface. I kicked that can down the road.

It's one thing to have media in development. But in production, it's another matter entirely.

lime frigate
#

Guys i need help in django, i have two views, one is to delete something and another one get it. However, when i call the view to delete and view to get it at the same time, it actually gets the result before it is even deleted

#

How can i fix this... i know this is about smtgh like async but i'm pretty weak in this

fast lava
#

can anyone help me

#

in

#

If somebody knows Django

worthy lake
#
# profile/<str:pk>/edit/
class UserProfileUpdateView(LoginRequiredMixin, UpdateView):
  ...

this is not sufficient for this view. Not only should the user be logged in, but they should have to be the exact user specified in the url. in a class based view (same as always) I dont know where to put this logic.

inland oak
#

If u a dealing with sql database, they have their own database level locks

#

The most simplest and primitive, would be just blocking by creating file and checking its existence

inland oak
#

If it is not sufficient for you, you could lock object in advance. Not knowing your case enough to suggest more precise answer

#

Unless u know for sure, I would recommend redis locks. They are meant for this, fast, comfortable code interface

#

The most precise locks would be probably database level locks, but I am not sure if there are good libraries to deal with it. Django ORM supports them or not

lime frigate
#

class UserInRoom(APIView):

    def get(self,request,format=None):

        print("userinroom")

        if not self.request.session.exists(self.request.session.session_key):

            self.request.session.create()


        data = { 'code' : self.request.session.get('roomCode') }



        return JsonResponse(data,status=status.HTTP_200_OK)


class UserLeaveRoom(APIView):

     def post(self,request,format=None):

        print("userleaveRoom")

        if 'roomCode' in self.request.session:

            print(self.request.session.get('roomCode'))

            self.request.session.pop('roomCode')

            host = self.request.session.session_key

            roomToDelResults = Room.objects.filter(host=host)

            if len (roomToDelResults) > 0:

                roomToDel = roomToDelResults[0]
                roomToDel.delete()

                print("done deleting")

        return Response({'message','You have left the room'},status=status.HTTP_200_OK)

#

Here's part of it, but i couldn't understand what ur saying hehe

#

The solution i have atm is

#

To use setTimeout

#

But i'm not sure if it's the best solution

#

In the original case, room is get before it is done deleting

fast lava
#

If anybody knows Django and Html pls help me

#

in

inland oak
# lime frigate ```py class UserInRoom(APIView): def get(self,request,format=None): ...
class UserInRoom(APIView):
    def get(self, request, format=None):

        print("userinroom")

        if not self.request.session.exists(self.request.session.session_key):
            self.request.session.create()

        data = {"code": self.request.session.get("roomCode")}
        return JsonResponse(data, status=status.HTTP_200_OK)


class UserLeaveRoom(APIView):
    def post(self, request, format=None):

        print("userleaveRoom")

        if "roomCode" not in self.request.session:
            return Response(
                {"message", "No room has been found"}, status=status.HTTP_404_NOT_FOUND
            )

        print(self.request.session.get("roomCode"))
        self.request.session.pop("roomCode")
        host = self.request.session.session_key
        deleted_rooms = Room.objects.filter(host=host).delete()

        if deleted_rooms:
            print("done deleting")

        return Response(
            {"message", "You have left the room"}, status=status.HTTP_200_OK
        )

a bit of formatting before doing anything

#

you know.. the simpliest solution would be just

#

returning proper error that room got dissapeared

#

where you request the room

#

return something like

return Response(
            {"message", "The room was deleted"}, status=status.status.HTTP_410_GONE
        )
#

pooof. no problem. ;b

#

hmm.

#

oh wait

#

that can be done simplier ;b

#

see... the problem we have

#

that you keep in which user room in session

lime frigate
#

What if userin room is ran before the Response is called

inland oak
#

so... if we have always delay between operations

#

while requests reach the server

#

think about using cookies 😉

#

cookies store user info client side

lime frigate
#

Hmmm

inland oak
#

so you can be fast enough to delete information about him leaving the room

#

or client side local storage, whatever

lime frigate
#

Are the syntax almost the same

inland oak
#

not really

#

client side operations are made in javascript mostly

#

cookies can be accessed/created server side at the same time in python

#

so... it is like a mix of two languages here, and mix of frontend and backend

#

====================================

#

essentially you would have something like this....

#

User creates Room, he gets cookie, preferably JWT Token, that he is in this room, and that he is the host (you have logic like this, right?)

#

User leaves the room... Request is sent to server to delete the room in case he is host, and his cookie is deleted

lime frigate
#

Yes....

inland oak
#

a bit unsafe, since in order to delete the cookie we will need it being visible to javascript, but it should work

lime frigate
#

Hmm great idea

#

But which one is usualy used

inland oak
#

Cookies in the form of JWT Tokens have verifications that they were produced by your server