#web-development

2 messages Β· Page 183 of 1

austere relic
#

@terse vapor what about using spider?

native tide
#
class DeletePost(generics.RetrieveDestroyAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = PostSerializer
    lookup_field = "slug"

    def get_object(self):
        item = self.kwargs.get('slug')
        return get_object_or_404(Post, slug=item)```
#

I want want to implement a patch method for this view

#

making all fields optional to update

#

cuz I don't want to let the user add an image each time for updating a post in react

#

I want to make it optional

#

this the model Post ```py

class Post(models.Model):
options = (('draft', 'Draft'), ('published', 'Published'))
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
title = models.CharField(max_length=250)
image = models.ImageField(gettext_lazy('Image'), upload_to=upload_to, default='posts/default.jpg', blank=True)
content = models.TextField()
slug = models.SlugField(max_length=250, unique_for_date='published', null=True, blank=True)
published = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='blog_post')
status = models.CharField(max_length=10, default='published', choices=options)
rating = models.IntegerField(default=0, null=True, blank=True)

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

def __str__(self):
    return self.title

def save(self, *args, **kwargs):
    self.slug = slugify(self.title)
    super().save(*args, **kwargs)```
terse vapor
austere relic
#

I think it uses BS4 as well

#

but it's especially designed for scraping a lot of websites

wet dust
#

What do I do if I get a 404 with loading my CSS file

terse vapor
#

u need to check the path and where u place the file

wet dust
#

The path is css/stylesheet.css relative to the html file

#

[19/Aug/2021 15:08:45] "GET /static/stylesheet.css HTTP/1.1" 404 -

wet hinge
#

Django REST
I have a Book model which holds "id" key along with some others.
Does anybody know how to not to include this "id" when calling certain book by GET /books/<book_id>?

mild stump
#

Whats wrong here ?

native tide
#

r you using git?

mild stump
#

yes

austere relic
#

I'm guessing a template failed to execute

opaque vale
#

Hey is anyone here?

native tide
#

Hey, I'm struggling with hCaptcha, I basically wants to make something like discord has, like there's login form and then it disappears and captcha appears.

captchaDiv = document.createElement("div"));
captchaDiv.setAttribute("class", "h-captcha");
captchaDiv.setAttribute("data-sitekey", "...");

I want to make the div like this, it should work because of when I have <div class="h-captcha" data-sitekey="..."></div> in html, it works fine, but for some reason it doesn't appear when I create it like this from JavaScript
(This peace of code should just make make the captcha, that's all what I need since I know how to make the rest, but for some reason it doesn't appears)

native tide
#
// Completely remove old form (where was the login form)
document.getElementById("boxForm").outerHTML = "";

// Create new box
var element = document.createElement("section");                        
element.setAttribute("class", "authBox");

// Create wrapper
element.appendChild(centeringWrapper = document.createElement("div"));
centeringWrapper.setAttribute("class", "centeringWrapper");

// Create div to center everything
centeringWrapper.appendChild(flexCenterClass = document.createElement("div"));        
flexCenterClass.setAttribute("class", "flexCenter"); 

// There should be the captcha 
flexCenterClass.appendChild(captchaDiv = document.createElement("div"));
captchaDiv.setAttribute("class", "h-captcha");
captchaDiv.setAttribute("data-sitekey", "...");

// End and write everything
document.getElementById('BeforeForm').appendChild(element);

Better example of the code

cosmic tangle
#

hey all, is there a Django and DFR developer here ?

ionic raft
vestal hound
ionic raft
#

Which might mean Django REST Framework?

#

It's funny...but I decided to get straight into Querysets, filtering etc. right inside Django. I should look into what REST Framework is about sometime...

#

The thing is, I've been able to do everything I've needed to so far with the DB. Not sure what I'm missing

manic frost
#

DRF isn't for anything database-related, it's for exposing an API for your website

#

AFAIK

ionic raft
#

Ok...so I'm not missing anything. An API for LanesFlow will be a v3+ feature methinks...much on the go right now

#

So, yeah, I decided to engineer a fully-automated ticketing system for LanesFlow Staff behind the scenes. user can initiate, we track, captures time/quality metrics, and sends emails to client on resolution.

#

1.5 days in and it's coming along NICELY.

#

Can use support tickets to identify future requirements, analysis through to implementation. The entire lifecycle...nifty stuff

#

This support application may actually be a viable product on its own. There are things that products such as ZenDesk really do not do well.

cosmic tangle
vestal hound
cosmic tangle
#

So I ask here, who is familiar with Django and Django rest framework

vestal hound
timber garnet
#

Hey everyone, I'm stuck with an error and don't really know what to do as a work around
the error is ModuleNotFoundError: 'fcntl' on Windows

austere relic
#

pip install fcntl

#

@timber garnet

smoky oar
#

!projects

#

!project

timber garnet
dense cloak
#
@app.route('/tag-team/<name>')
def asd(name):
  with open(f"allowedKeys.json", "r") as logs:
    l_logs = json.load(logs)
    keys = [key for key in l_logs]
    if name in keys:
      return l_logs
``` raises typeerror
#

no

#

yes it raises typerror

native tide
mystic vortex
#

Guys which framework is better for a web dashboard - Vue.js, angular, react

eternal blade
dense cloak
#

i fixed it but thank you

lavish ferry
#

Hey so if I am using Flask and have some forms which submit stuff I process, what is the best approach (maybe turbo Flask?) To updating that page with the result rather than having to re-render the entire page with all the user inputs carried over?

#

I saw something about sessions as well but it all went over my head.

cerulean badge
#

for an ecommerce site how do you get the shipping cost? pre defined cost per city?

cerulean badge
#

should you create form in django even for just add to cart form? or should you just hardcode it?

dense cloak
#

how 2 add input tag in flask

terse vapor
#

I created a function that allow me to scrape from internet, but the results contains html tag like this ```py
<h3 class="base-search-card__title">

    Software Developer
  
      </h3>, 
However, is there a way for me to do the cleaning that only laves the important data(the link)?
#

Like i only want the text inside and not everything

inland oak
#

I like the feature of serializers/deserializers for any incoming/outcoming JSON data. The best thing about it, that it supports nesting serialization. We write only one serializer for each element, and then just nest them if necessary. It makes quite DRY code for all of it.

#

it has all sets of additional features you can possible need for JSON API, for example enabling for particular request throtting limits against abuse. Like no more than X requests per N time from T ip

ionic raft
# inland oak DRF is not replacing, it is complimenting what Django has.

I get it. AND if I don't need an API (because I have user's get at their private data by logging in) then I don't need to work with REST in v1.0 πŸ™‚
An API would make sense if either users needed to download date, or if there was data that made sense to make publicly available (such as selling it).
I expect I'll get to it. However, bigger fish to fry for this web application for version 1. Users being able to download their data in json format is definitely down the road

#

Such as a fully fledged support engine inside LanesFlow...

inland oak
#

it is a matter of following microservice architecture

#

and having better scalability for enterprising things

ionic raft
inland oak
ionic raft
ionic raft
#

It's like when people say....global variables are BAD!
When the reality is, there are very sound use-cases for global variables

inland oak
#

monoliths have their own usage too

#

perhaps this book could give you a bit more food for thought

ionic raft
#

I'm all for good advice. But unsought for opinions based on zero-clue of what I'm building...

inland oak
#

I don't know, yes.
but you said it on your own, that your frontend logic is too tight to conditions of different subscriptions through your application.

#

I can understand it only as there is some problem with code separation there

#

it is possible that you don't need any improvement

#

I don't know how much people you target and e.t.c.

ionic raft
#

It's actually driven by the nature of how you improve processes in an organization.

#

I'm not saying it's perfect. And I'm open to improvement.
However, before tearing this down it has to be understood. And I've spent 25 years working with this process improvement methodology. It works on paper. Now I get to see how it applies to a web app

#

Subscription directly drives how many Orgs-Teams-Process-PIPs etc. you can have. Higher tiers get to store more of each. Free subscribers get 1 Org, 1 Team, 1 Process and 2 PIPs (each PIP has tools).

#

So yes, it is a monolith. However, it's also a series of apps.
The support engine is a separate app.
but I'm not sure how I could break apart the pips app, because of the nature of how process improvement methodology works. And simply hammering a pattern onto something without a solution is like trying to ran a square peg into a round hole.
It's a bit of a personal peeve when people throw technology at problems without understanding the problem

#

It's like the OOP purists that say, make everything OOP!
When the reality is, badly designed class structure can be a ticking time bomb

white delta
#

Why do i ALWAYS get a 'preparing wheel metadata ... Error' when I'm trying to install requirements.txt

dusk portal
#

@ionic raft r u there , my real friend where r u

lavish ferry
dusk portal
#

im trying to make sign up functionality by django rest framework

#
@csrf_exempt
def signup(request):
    if request.method=='POST':
        try:
            data=JSONParser().parse(request)
            form=RegisterForm(data.POST)
            if form.is_valid():
                form.save()
                token = Token(user=form)
                return JsonResponse({'token':str(token)},satatus=201)
        except IntegrityError:
            return JsonResponse({'error':'That username has already been taken. Please choose a new username'}, status=400)```
native tide
#

why there's no session for django-rest-framework?

dusk portal
#

u mean resources?

native tide
#

yes

dusk portal
# native tide yes

yes ofc as advance u will go resources will decrease but dont worry see playlist of JustDjango Codewithmosh and it's official docs

wraith cypress
#

you just import the urls

dusk portal
#

ohh

wraith cypress
#

also jwt is better than normal tokens

dusk portal
#

ohh

#

how can i do that

#

umm

#

can i see an example

wraith cypress
#
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
    path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
]
#

in settings.py

from datetime import timedelta
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=30),
}
cerulean badge
#

(context django) it doesn't matter which model have o2o right?

wraith cypress
#

o2o?

cerulean badge
#

o2o field

#

models.OneToOneField

wraith cypress
wraith cypress
#

if you want a tool to help you design your database use drawsql.com

wraith cypress
#

which is much more secure since no client will get the cookies, only django and the browser

wraith cypress
#

loadingpleasewait I have a serializer with a validate function that should return the url and the username as data, but I can't seem to be able to take the values from self. it keeps saying either url is not in self or you can't take from self etc

class UserLoginSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = (
            "id",
            "url",
            "username",
        )
    def validate(self, data):
        data["url"] = self.url # the issue
        data["username"] = self.username # the issue
        return super().validate(data)
#

the function's purpose is that when I login it should return the url of the user and the username

wraith cypress
#

logo_django2 btw

#

!rule 6 9

lavish prismBOT
#

6. Do not post unapproved advertising.

9. Do not offer or ask for paid work of any kind.

cerulean badge
#

logo_django2 i have 2 models order and orderdetails, orderdetails have o2o field to order therefore we can create order without orderdetails but not vice versa right? then why in admin it is required to fill the orderdetail?
i have orderdetails as stackedinline

native tide
#

Hi I’m beginning to study webdev next year, could you guys recommend me some books on website or software to read in advance? Thank you so much

crimson phoenix
#

I followed a tutorial of tech with tim for making flask app
a blog app
I tried to host it with heroku
FYI:I am using heroku for first time
it is giving me this error
πŸ‘‡```

2021-08-20T11:49:02.745211+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sreesankar007.herokuapp.com request_id=ced8292c-6e00-4de0-bb6f-729275676cbf fwd="103.161.144.64" dyno= connect= service= status=503 bytes= protocol=https
2021-08-20T11:49:03.100438+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sreesankar007.herokuapp.com request_id=4fc5ea6a-4220-4180-9e79-d8506b37e85f fwd="103.161.144.64" dyno= connect= service= status=503 bytes= protocol=https
2021-08-20T11:49:53.666130+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sreesankar007.herokuapp.com request_id=e8069fe8-6376-42f8-8d57-a9377f7cffa4 fwd="103.161.144.64" dyno= connect= service= status=503 bytes= protocol=https
2021-08-20T11:49:54.178373+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sreesankar007.herokuapp.com request_id=f8e1d828-868f-4293-b8c0-57f49712a894 fwd="103.161.144.64" dyno= connect= service= status=503 bytes= protocol=https

thanks in advance
crimson phoenix
#

If you need to look at any of the code here is the github linkπŸ‘‡

crimson phoenix
#

help

raw compass
#

I'm not sure with heroku though its convention to keep the venv in the .gitignore as the contents are suitable for your workstation only and shouldn't be shared.

raw compass
native tide
#

Hello, i want know how to get response of a get request

tranquil talon
#

Stupid question, but how can I call a sync function from an async context in django without awaiting it??

#
@sync_to_async
def get_config(key):
    try:
        return getattr(OConfig.get_solo(), key)
    except OperationalError:
        pass
#

So, I'd have to create a sync config getter and a async config getter in order to get around this?

tranquil talon
#

Because these settings are needed from many different places, async external api requests, pydantic models/validators etc.

crimson phoenix
mild stump
#

Hello everyone. I had posted this error yesterday. but no luck. please help me for the error..

native tide
crimson phoenix
terse vapor
#

try this

#

it works for me

mild stump
terse vapor
#

i didnt use the {% load static %}

#

not sure does it affect or nah

mild stump
terse vapor
#

k

#

rip

ashen bay
#

What are people's thoughts on the best way to approach this:

I have a model currently which inputs some data related to a dividend. I need to create something which will track the current FX rate (doesn't have to be 'live' could just be the latest daily rate) up until a specified date (the 'Ex-Date'), at which point the FX rate should remain as the FX rate related to that date

#

For the moment, I've left the fx-rate as a hardcoded decimal input field

#

This is Django related btw

last dagger
#

hey users

#

πŸ˜›

#

could you helpe me with one django issue

#

my django app doesnt recognize static directory when i use gunicorn with wsgi

true kernel
#

how can I pass a context to the base.html?

ionic raft
dusk portal
#

Show me

ionic raft
#

I have, however, engineered in a Support ticketing system into LanesFlow over the past couple of days πŸ™‚

shadow salmon
# ashen bay What are people's thoughts on the best way to approach this: I have a model cur...

If you haven't already found your answer, I would probably approach this by using either a task queue like celery or management script triggered by cron that runs a function to update the model everyday. Rather than having fx-rate be a field, make it a separate model with a foreign key so that you can give it a datefield to compare to the current date. So you can set a conditional in your function for how it's updated.

scarlet jacinth
#

How can I make a model/ serializer/ view of django for a mysql view?

safe narwhal
#

hey can someone help me I've been watching Corey Schafer's django tutorial creating a website. I tried to make a registering page but I wanted it to redirect user to home page. I did as the video instructs but mine is not working. Python seems not to read ---> if request.method: and the .get method

inland oak
chilly ivy
lapis basin
#

Nice

ember adder
#

In Django, we can annotate like so
queryset.annotate(my_field_name=Subquery(my_sub_query))

Is it possible to replace my_field_name by a variable ?

native tide
#

Hello, I was wondering so i was checking my cloudflare statistics page and on my freshly made domain it already had over 600 visits could this possibly be google scraper bots?

dusk portal
indigo kettle
#
kwargs = {'my_field_name': Subquery(my_sub_query)}
queryset.annotate(**kwargs)```
ember adder
indigo kettle
#

yeah

#

it's a string right

warped heart
#

if a user is changing there account password is better to use post or a patch request?

#

because in theory they are modifying a recourse so i think patch would be more ideal

#

not to sure

last dagger
#

:c

#

but it doesnt work with gunicorn

last dagger
#

ohh well

#

there is an static forlder

#

but is not the correct one

manic frost
#

Am I the only one who hates the way CSS names things? Like, using synonyms to distinguish between two different things (middle-center, justify-align, etc.)

clear bone
#

anyone know why my border styling is just not appearing?

manic frost
#

@clear bone Why do you add -style to properties?

#

If you open the devtools, and inspect the thead, you'll see a warning

#

oh wait

#

don't mind me

clear bone
#

-style is used for specifying a solid line or a dashed line

#

haha

manic frost
#

yeah

#

I forgot

#

can you open the thead in devtools?

clear bone
#

yep

manic frost
#

what if you apply a color to the border?

clear bone
#

with border-color i presume?

manic frost
#

yeah

clear bone
#

no change WTF

#

this is really weird

manic frost
#

What if you do just: border: 1px solid black?

clear bone
#

hmm still no change

manic frost
#

@clear bone Can you send the table HTML as text?

clear bone
#
            <thead id="table-header">
              <tr>
                <th> QTY </th>
                <th> ITEM </th>
                <th> AMT </th>
              </tr>
            </thead>
            <tbody>
              {%for x,y in tracks%}
                <tr>
                  <td> {{forloop.counter}} </td>
                  <td>    {{x}} </td>
                  <td>  {{y}} </td>
                  {%endfor%}
                </tr>
            </tbody>
            <tr id="item-count">
              <td> ITEM COUNT: </td>
              <td></td>
              <td> {{info.1}} </td>
            </tr>
            <tr>
              <td> TOTAL: </td>
              <td></td>
              <td> {{info.3}} </td>
            </tr>
          </table>
#

sorry if its a bit messy, i tried to add a border to "item-count" but also had no result

manic frost
#

not sure it is the cause, but shouldn't it be </tr> {%endfor%} and not ```
{%endfor%}
</tr>

clear bone
#

ahh yeah just fixed it but it didnt change anything

#

this is really perplexing

manic frost
#

hm, for some reason thead doesn't accept a border at all

clear bone
#

hmm i tried also for "item-count" which is a tr element, but it also didnt work

arctic wraith
#

hello , try to use bootstrap classes

manic frost
clear bone
#

oh wow that did the trick!!!

arctic wraith
#

yes use style attribute inside tbody

clear bone
#

thank you so much!!!

quiet ember
#

hi

#

do I need to use a webserver when testing my website backend code?

#

for example if I'm sending HTTP requests to my backend code would I need to have nginx setup or is that only when I'm pushing it for production

ionic raft
quiet ember
ionic raft
# quiet ember I'm going to use node.js for the backend

I'm not familiar with node.js. I've been developing extensively on Django. I'll be going to React for one app, but overall Django provides the webserver. You can render pages locally. When you promote to production it's a part of the stack

quiet ember
#

but the actual application which i'll be making http requests in is in python

#

but I might use django if I can figure out this webserver stuff

#

it's quite annoying

#

since it's my first time

ionic raft
# quiet ember it's quite annoying

I started with Flask for a month to learn the basics of web dev with python. it's an excellent start for building out a web server with a DB, application and front-end. You can then plug a front-end framework on top.

quiet ember
ionic raft
#

Django also brings outstanding authentication and administration tools out the box

#

If your web app is simpler, then Flask is great though

quiet ember
#

I was struggling trying to understand how all this web server and backend stuff worked

#

but now it'll be easier

ionic raft
#

When I realized I was going to have 7+ apps within the web app, along with 5 subscription tiers I knew Django would be the way to go. However, starting was Flask was ideal.

ionic raft
quiet ember
#

Or is that up to the user

ionic raft
#

Ok...I'll give you an example of Django and security...

#

So, you get 3 user tiers out the box...user, staff and superusers...

#

You can query in the front-end for those levels.
You can also create Groups to give granular permissions.

#

In addition, when you get to building views for the front end, you can include Mixin's that will ensure a test is passed before the page/view can be rendered...or gives a 403 permission denied error

#

It's a LOT to take in...but I recommend...start with Flask for a month or so. Get grounded. The when you're ready, shift over to Django and extend your app.

#

You can obviously jump straight to Django...but that for me would have been overwhelming

#

Flask does have some authentication...But Django comes with an administration backend built in.

quiet ember
#

Alright thanks, I'll try flash first then move onto django

ionic raft
velvet yew
#

How should I handle an ObjectId in my Django API that returns a JSON? I've tried json.dumps(my_dict, default=str) but it creates a mess

oak nest
#

Hi Im trying to create a container running python with django but the problem is when I run my image, nothing happened until I use CTRL + C to quit.
Here is the logs we can see that when I press CTRL + C the app starts and stopped

^CPerforming system checks...

System check identified no issues (0 silenced).
August 21, 2021 - 00:24:13
Django version 3.2.6, using settings 'web_redirector.settings'
Starting development server at http://127.0.0.1:80/
Quit the server with CONTROL-

Here is my image:

FROM python:3.9-alpine

MAINTAINER Pseudow
WORKDIR /usr/app/

COPY . .

RUN python3 -m venv venv
RUN pip install django
RUN python3 manage.py migrate

EXPOSE 80
CMD ["python", "manage.py", "runserver", "80", "--noreload"]
balmy lintel
#

Starting development server at http://127.0.0.1:80

This happens. It means that a web app is running on the localhost. Launch a browser and load your web app. If you are on the same machine then you will be able to access the web app at http://127.0.0.1 but this app is not available from other clients.

#

Okay... I see this all happens after you hit CTRL+C. Not really sure what's going on there.

oak nest
#

ive changed to production mode and it just don’t do it anymore there are no logs even when i hit ctrl c

ionic raft
manic frost
#

80 is the default port for web apps, it's what your browser uses as a default when you request http://some.web.site/

shadow salmon
lavish prismBOT
#

tools/shell/env-vars line 10

echo -e "export PYTHONDONTWRITEBYTECODE=\"1\"" >> /etc/profile.d/env-vars.sh```
versed python
#

Oh wow

#

Cool

tawny kelp
#

I remember reading that languages like Python that created an instance for each request or something like that, while node shared many resources between requests. Anyone know where I can read regarding this?

manic frost
#

There are synchronous frameworks (like flask or django) and asynchronous frameworks (like Starlette or aiohttp). In the first case, a thread can only process one request at a time, so you might spawn more than 1 thread per CPU core. In the second case, it works much like with node, and a single thread (usually with 1 thread per logical core) can handle many requests at a time.

opaque rivet
inland oak
dusk portal
#

finally started freelancing as 1 of my friend requested to me to do his work

#

70-75$

opaque rivet
dusk portal
#

@opaque rivet i want users to upload pdf which type of model will i use FileField?

inland oak
dusk portal
#

For its back-end
Whole proj backend

dusk portal
versed python
dusk portal
versed python
#

Lucky

dusk portal
#

lol

#

badluck

#

can u tell me place where i can really do freelancing

#

instead of working for a pizza( 75$ dollar lmao)

versed python
#

Nope I wanna get started too

#

Most of my previous free lancing was my friends referring me to others

versed python
dusk portal
pliant hollow
#

If you start on the freelancer type sites, your earning will be low at first. So there are two options. Do those, which I dont really recommend, or put together a good github repo and website, which is like an online cv, then get a remote job..

dusk portal
#

im 16

#

ohk

versed python
pliant hollow
#

Since covid, many programming jobs have gone 100% remote and there are much more now

dusk portal
versed python
#

But i would prefer a freelance, since im in college

eternal blade
dusk portal
#

i never used filefield

#

but ig it will be good

#

umm

pliant hollow
#

So there is a different freelance / contract, or someone just gives you a program / website to build and leaves you to it

dusk portal
#

ohh

pliant hollow
#

both are freelance

pliant hollow
#

but you not working for any company

dusk portal
#

nice

#

u know places where i can start

#

ig it's time for me to start

pliant hollow
#

taking a freelance job where you are not part of a company, and someone just gives you some work to do is ually a massive pain in the a55

#

but good experience πŸ™‚

dusk portal
#

ohh

#

from which site i can start

#

wait wait

#

damn

#

but i dont have portfolio

#

Um!!!!

#

btw to participate in hackathons == more profit then any freelancing proj , cez prizes are too good

#

and entry is free

#

and participants are also low

#

check

pliant hollow
#

I wouldnt think about money too much, one you start, if you are good, your fee / salary goes up quickly. But first jobs are always going to be lower

dusk portal
#

ohh

#

in which which sites and platform u do freelancing @pliant hollow

pliant hollow
#

there are things like upwork, people per hour, fiverr

dusk portal
#

ohh

oak nest
inland oak
# opaque rivet if the guy wants to see realtime terminal output then it shouldn't be buffered

https://stackoverflow.com/questions/59812009/what-is-the-use-of-pythonunbuffered-in-docker-file/59812588

Setting PYTHONUNBUFFERED to a non empty value ensures that the python output is sent straight to terminal (e.g. your container log) without being first buffered and that you can see the output of your application (e.g. django logs) in real time.

This also ensures that no partial output is held in a buffer somewhere and never written in case the python application crashes.
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONUNBUFFERED

Apperently both answers were equally correct, because the same result would be achieved with any set value.

opaque rivet
#

always thought it at binary on/off seeing it as numbers

#

env variables, even when the value is a number, it's still stored as a string right?

dusk portal
#
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User

class Notes(models.Model):
    title=models.CharField(max_length=60,blank=False)
    desc=models.TextField(blank=True)
    file=models.FileField()
    author=models.ForeignKey(User,on_delete=models.CASCADE)
    published_on=models.DateTimeField(default=datetime.now)

    def __str__(self):
        return  self.title
    
    class Meta:
        verbose_name_plural='Notes'```
#
OperationalError at /admin/users/notes/
no such column: users_notes.file
inland oak
dusk portal
#

lol done

#

im not that noob now

#

LoL

inland oak
#

Β―_(ツ)_/Β―

native tide
#

help i stuck here at 23:00

#

In this video, we are starting a new project. In this video, we are going to start a social media app. We will begin with creating a landing page for unregistered users and add the ability to login and register a new user. We will use Bootstrap 5 in this project, which at this time is very new and will have some small differences from Bootstr...

β–Ά Play video
#

the templates just wont apply for me

#

i followed his steps but it wont apply

thorn igloo
# native tide

did you link the bootstrap or not? it looks like you didnt at all

lavish prismBOT
#

Hey @native tide!

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

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

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

https://paste.pythondiscord.com

native tide
thorn igloo
#

in your html

native tide
#

1 sec

#
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

      <script src="https://kit.fontawesome.com/5136008754.js" crossorigin="anonymous"></script>
    <title>Social Network</title>
  </head>
  <body>
    {% block content %}
        <h1>Landing</h1>
    {%  endblock content %}

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
  </body>
</html>
#
{% extends 'landing/base.html' %}

{% block content %}
<div class="container">
    <div class="row justify-content-center mt-5">
        <div class="col-md-10 col-sm-12 text-center">
            <h1 class="display-2">Connect With Your Friends!</h1>
            <p class="mt-3 lead">Follow people who interest you, stay up to date on the latest news and join conversations with your friends</p>
            <div class="d-flex justify-content-center mt-5">
                <a href="#" class="btn btn-light mr-2">Login</a>
                <a href="#" class="btn btn-dark">Register</a>
            </div>
        </div>
    </div>
</div>

{% endblock content %}
thorn igloo
#

when you right click and inspect, are these links present?

native tide
thorn igloo
#

i said when you inspect in the browser, not your editor

native tide
#

yea they are

thorn igloo
#

and they are not applying?

#

alt + f5 to refresh

native tide
#

the dude from the video downloaded a template on github and the designs somehow overrided the old design

#

the base thing works

thorn igloo
#

if that's not working, then idk, it's not being applied on your page

native tide
#

In this video, we are starting a new project. In this video, we are going to start a social media app. We will begin with creating a landing page for unregistered users and add the ability to login and register a new user. We will use Bootstrap 5 in this project, which at this time is very new and will have some small differences from Bootstr...

β–Ά Play video
thorn igloo
#

bro, it's your thing that's not working

#

checking this won't help me help you

native tide
#

and on 24:40 it works

#

yea i dont know what to ask tbh

#

i followed anything step by step anything worked well too and now the template wont apply xD

thorn igloo
#

looks to me like your bootstrap is not being applied on that page

#

are you extending the base in it?

native tide
#

i have no idea what im doing.

thorn igloo
#

yea... learn the basics before you do something this complex

native tide
#

just wanted to have a base to learn it

native tide
thorn igloo
#

once you do you'll probably see why your styles are not applying

native tide
#

yea started today with django

#

there is alot to learn

#

already taking notes and all but it will take time

thorn igloo
#

and you jumped to use authentication? damn

native tide
#

yea i wanted a copy paste the base from his video series and tweak code an watch what its doing to get a feeling for it

#

atleast i know how to host a site on my network now haha

native tide
#

i think here is the issue

thorn igloo
#

and again, learn the basics first

oak nest
native tide
#

I'd realy like to fix that first πŸ˜„

#

now its working

#

wrong templates file

native tide
#

hi does anyone here do web scrapping?

quiet ember
#

hi does anyone know how I can make an admin panel private? I want it to be only accessible by me and a few other users

#

does cloudflare provide protection or something of sorts?

inland oak
#

Nginx comes second to mind

#

We could expose app for users and for admins to different endpoints

#

Which nginx have in different cfgs provided

#

For admin endpoint, ip white listed as requirement

quiet ember
quiet ember
inland oak
#

Not sure if it is possible by nginx tbh

#

But firewall or nginx, or combination of them should work

#

Btw, u can hide admin panel by having secret long url for that

#

/admin path is not requirement, just default

quiet ember
#

so I should use apache?

inland oak
#

Whatever u wish, sugarcube.
Apache is just alternative to nginx

#

It can be used as the same reverse proxy too

#

Or as static file server

#

Oh yes, I remembered

#

I did it already by nginx

#

I enabled basic auth for all users by default to dev server. And made exception for our provider ips range to access freely without auth.

wraith cypress
austere relic
pliant hollow
quiet ember
#

does anyone know how I can make a webserver that has a file download and the version, I need this for my auto updater

#

any examples would be nice

lime frigate
#

Guys i need help for github

#

I need to add a large file

#

I added the .gitattribures

#

But somehow this shitty thing keeps on saying it's too larging

#

*larhe

#

*large

native tide
#

trying to get a flask app running that uses data gathered from a text file but file comes back as not existing is this a flask issue or have i messed something up ```py

import urllib,json,os,time,threading
from mcstatus import MinecraftServer
from livereload import Server
from flask import Flask, render_template
from livereload import Server

app = Flask(name)

result=""
ping=""
@app.route('/')
def main():
catagory=["Name","IP","location"]
names=["jordan","Kerry","Jen"]
ips=["127.0.0.1","127.0.0.2","127.0.0.3"]
locations=["UK","Scotland","Ireland"]
os.chdir("C:/Users/Jorda/Desktop/anarchy")
with open ("deets.text") as r:
deets=r.read()
sepdeets=deets.split("-")
names.append(sepdeets[0])
ips.append(sepdeets[1])
loactions.append(sepdeets[1])
return render_template("index.html",names=names,headers=catagory,ips=ips,locations=locations)

if name == 'main':
server = Server(app.wsgi_app)
server.serve(port=5555)

#

file is there

#
C:\Users\Philipp\Documents\sound>django-admin startproject socialsound
The command "django-admin" is either misspelled or
could not be found.
#

in windows console why cant i use this command

#

pip install works etc

native tide
clear bone
#

does anyone else get a 403 error when using spotify's search api?

#

403 errors usually happen when theres permission issue but i feel like the search api endpoint is all public data anyway

tropic pulsar
#

Hello, I need help! Html input type number to control number textbox needed. like if you select 2 as input your web display 2 textboxes

marsh canyon
#

you will need javascript for this

#

to read the input number and then display that many textboxes dynamically

tropic pulsar
#

Any idea, How to do it?@Dark Iceman

native tide
#

how do i write <> with a word inside?
this is what i get

marsh canyon
tropic pulsar
#

yes, i do

marsh canyon
#

so you first, get the input element in js using querySelector or getElementById, read the input value. You would need to generate the text area html code within JS (store the html of a textarea in a variable).
Since you now know the number of textarea you need(as you read the value from the input), insert that many textareas using insertAdjacentHTML() in a loop

marsh canyon
tropic pulsar
#

thanks@Dark Iceman

ashen warren
#

What is a good program for writeing HTML?

thorn igloo
#

any text editor

#

but vscode has inbuilt emmet

ashen warren
#

@thorn igloo thx πŸ™‚

native tide
#

why this error django.core.exceptions.ImproperlyConfigured: Field name `commented_on` is not valid for model `CustomUser`. when this is my model py class CustomUser(AbstractUser): # user_image = models.ImageField(gettext_lazy('UserImage'), upload_to=upload_to, default='users/default.png') liked = models.ManyToManyField('blog.Post', related_name='liked_posts', blank=True) disliked = models.ManyToManyField('blog.Post', related_name='disliked_posts', blank=True) bookmarked = models.ManyToManyField('blog.Post', related_name='bookmarked_posts', blank=True) commmented_on = models.ManyToManyField('blog.Post', related_name='commented_on_posts', blank=True,) And this is the serializer ```py
class RegisterUserSerializer(ModelSerializer):
class Meta:
model= CustomUser
fields = ('username', 'email', 'first_name', 'last_name', 'password', 'liked', 'disliked', 'bookmarked', 'commented_on')
extra_kwargs = {'password': {'write_only': True}}

def create(self, validated_data):
    password = validated_data.pop('password', None)
    instance = self.Meta.model(**validated_data)
    if password is not None:
        instance.set_password(password)
    instance.save()
    return instance

class UserListSerializer(ModelSerializer):
class Meta:
model = CustomUser
fields = ('all')

#

views.py ```py
class RegisterUserView(APIView):
permission_classes = [AllowAny]
serializer_class = RegisterUserSerializer

def post(self, request):
    reg_seria = RegisterUserSerializer(data=request.data)

    print(request.data)

    if reg_seria.is_valid():
        new_user = reg_seria.save()
        if new_user:
            return Response(status=status.HTTP_201_CREATED)
    return Response(reg_seria.errors,status=status.HTTP_400_BAD_REQUEST)

class BlacklistTokenView(APIView):
permission_classes = [AllowAny]

def post(self, request):
    try:
        token = RefreshToken(request.data['refresh_token'])
        token.blacklist()
    except Exception as e:
        return Response(status=status.HTTP_400_BAD_REQUEST)

class UserListView(generics.ListAPIView):
queryset = CustomUser.objects.all()
serializer_class = UserListSerializer

class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = CustomUser.objects.all()
serializer_class = UserListSerializer```

#

also this is the full traceback Traceback (most recent call last): File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\renderers.py", line 724, in render context = self.get_context(data, accepted_media_type, renderer_context) File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\renderers.py", line 696, in get_context 'post_form': self.get_rendered_html_form(data, view, 'POST', request), File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\renderers.py", line 511, in get_rendered_html_form return self.render_form_for_serializer(serializer) File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\renderers.py", line 519, in render_form_for_serializer serializer.data, File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 548, in data ret = super().data File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 250, in data self._data = self.get_initial() File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 398, in get_initial for field in self.fields.values() File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 349, in fields for key, value in self.get_fields().items(): File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 1053, in get_fields field_class, field_kwargs = self.build_field( File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 1199, in build_field return self.build_unknown_field(field_name, model_class) File "C:\Users\kenny\.virtualenvs\drf_react-uZeTBhos\lib\site-packages\rest_framework\serializers.py", line 1317, in build_unknown_field raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Field name `commented_on` is not valid for model `CustomUser`.

#

I get this error when I try to register a user

native tide
#

so dead

native tide
#

it's because your model has 3 mmm's in the field name commented on.

native tide
#

ye it says commmented_on but should be commented_on

native tide
native tide
#

you can

#

pip install domonic

#

to play with it

#

ok

proper osprey
#

Hey, I've got an interactive program which I built in tkinter. I'm planning on creating some kind of portfolio website where I can show off some of my projects and stuff (this one likely being the first). Is there any easy way for me to translate that tkinter setup onto a webpage, or will I likely have to recode it?

raw compass
proper osprey
manic frost
#

@proper osprey You actually don't need to publish it on pypi if you want people to install it -- you can just publish it on github

mystic vortex
#

Guys which js framework is best for a starter in web dev

proper osprey
manic frost
mystic vortex
mystic vortex
#

How does it look like ?

manic frost
#

wdym look like?

mystic vortex
#

Can I see a website that is made with svelte

manic frost
#

The looks are completely independent from the JS framework. They're defined with HTML+CSS.

mystic vortex
#

??

manic frost
mystic vortex
#

But learning at the moment

manic frost
#

HTML defines the structure of a page.
CSS defines how each element looks like.
JavaScript allows you to add interactivity to the page.

mystic vortex
#

Ok

#

So is it possible to use svelte along with it

#

??

manic frost
#

Yes, svelte is just a tool to make writing a complex application easier.

mystic vortex
#

Ok

lime frigate
#

Is learning REST api same as learning web API?

mystic vortex
#

@manic frost is it possible to make single page application with svelte?

manic frost
mystic vortex
#

@manic frost is it ok if i use react cause i have started with it and it is good from my opinion so will it be able to make single page application?

manic frost
mystic vortex
mystic vortex
#

@opaque rivet

#

can u help me a bit

opaque rivet
#

i can try sure

mystic vortex
#

can u tell me how to use django

opaque rivet
#

pretty broad question

#

you can use it as an API for your react frontend

mystic vortex
#

so i am not saying about react rn

#

i am saying about normal html file

#

i want to know how to make routing

#

system

opaque rivet
#

django is a python backend web framework. I suggest watching some beginner youtube videos

mystic vortex
#

??

#

cause as i am going to use it for my discord bot i need it

opaque rivet
#

yes you can have async views

mystic vortex
#

ok and can u tell me how to make routing with django using async

opaque rivet
#

you can watch some tutorials on django to make whatever you want, you dont need me for it

tulip beacon
#

Hey guys I made a todo list, but the text I entered is piling up on eachother, what should I do inorder for this to work?

vestal hound
tulip beacon
#
.todo{
    position: absolute;
    left: 600px;
    top: 1400px;
    display: flex;
}
vestal hound
#

I mean

#

you can but it's not useful

#

unless

#

that is the CSS of each individual item

#

in which case

#

well

#

if you have position: absolute

#

of course they overlap

tulip beacon
#

and

#

the

#

solution

#

is?

vestal hound
#

...don't use position: absolute?

#

do you know what the various position values do

tulip beacon
#

I'm not that familiar on css, but I can understand..

vestal hound
#

okay, then you should know what to do

tulip beacon
vestal hound
vestal hound
#

are you SURE you know?

tulip beacon
#

I know what most of them are used for, but for this case I thought some padding might help, what do you say?

vestal hound
#

this is entirely the wrong way to go about it...

#

okay

tulip beacon
#

oh

vestal hound
#

tell me what your understanding of position: absolute is

#

and we'll go from there?

tulip beacon
#

alright, so position absolute does not affect other element around it and also it does not get get affected by the other elements...

vestal hound
#

not true

#

I think you're thinking of position: fixed

#

position: absolute is affected by the containing block

#

but anyway

tulip beacon
#

well, as I said I'm not that familiar on css, but I can understand..

vestal hound
#

so

#

I'm going to assum

#

eeach todo

#

has class="todo"

#

so all your todos are absolutely positioned

tulip beacon
#

ok

vestal hound
#

so, the default positioning is static

tulip beacon
#

oh

vestal hound
#

when static is used, elements will not overlap

#

they each have their own space

#

but when you use absolute or fixed

#

they're taken out of this normal flow

#

and occupy a space specified by top, left, etc.

#

which also means

#

they can overlap.

#

all your todos

tulip beacon
#

oh

vestal hound
#

have position: absolute

#

and the same top/left

#

you see why that's a problem?

tulip beacon
#

yeah

vestal hound
#

in general

#

you only want absolute/fixed

#

when you want something to overlap something else

tulip beacon
#

so, the solution is to use static?

vestal hound
#

static is default

#

so you don't need to specify it

tulip beacon
#

ohk

#

so, if absolute or fixed can overlap elements and static is by default, then should I use sticky?

vestal hound
#

hold up

#

why do you want to use sticky

tulip beacon
#

idk, thought that maybe that might be used....

vestal hound
#

relative that turns into fixed

#

okay

#

you know how

#

like

#

Google Sheets

#

when you scroll down

#

the rows change

#

but the headers stay the same?

#

that's one usecase for sticky

#

ANYWAY

#

just remove your position: absolute

#

and see what it looks like

tulip beacon
#

I tried, but i didn't work

#

I tried it wayy before

#

but

#

didn't

#

work

vestal hound
#

show result

#

and explain what you mean by "didn't work"

tulip beacon
#

this is whats happening

#

@vestal hound this is what happend...

vestal hound
tulip beacon
#
<input placeholder="Max Length - 50 Characters" type="text"
                className="PostTodo-input"  value={inputText} onChange={inputTextHandler}
                maxLength="60"/>
                        <IconButton onClick={submitTodoHandler} className="postTodo-icon" type="submit">
                            <AddBoxIcon className="postTodo-icon" 
                            fontSize="large"/>
                        </IconButton>
            </div>
vestal hound
#

...is that all of it

#

that's not valid HTML

tulip beacon
#
import React from 'react'
import'./PostJobTodo.css'
//ICONS
import DeleteIcon from '@material-ui/icons/Delete';
import { IconButton } from '@material-ui/core';


function PostJobTodo({text}) {
    return (
           <div className="todo">
               <li className="todo-item">{text}</li>
               <IconButton className="trash-btn">
                   <i className="trash__btn">
                   <DeleteIcon fontSize="large"/>
                   </i>
               </IconButton>
            </div> 
    )
}

export default PostJobTodo
``` well I did it all in js
#

what about this?

vestal hound
#

this looks like

#

the HTML for the submit part...

tulip beacon
#

there are a lot of SRCs in the folder which I had done

vestal hound
#

okay

#

I mean

#

the problem is clearly with your CSS

#

but

#

it's super hard to debug remotely like that

#

I would suggest

#

you do a quick refresher on CSS positioning?

#

you should be able to fix it yourself

tulip beacon
#

oh alright

mystic vortex
vestal hound
inland oak
# mystic vortex What is DRF

Django REST Framework. Addon to Django for making REST APIs. A set of libraries to make Django a bit more suiting the task.

vestal hound
#

the first result for "django drf" is Django REST Framework

mystic vortex
#

I see

#

Thanks for telling me

thorny quartz
#

How to use foreign key without choices like when i pick a particular row from a table then foreign key takes that row field as a id or whatever

#

anyone please help I am new in django

mint echo
raven harbor
#

i have some doubt in navigating between pages in django. when there is no app i can navigate without any issue but iam confused when i create an app i hav a views.py inside the app and urls.py outside the app in the projest should i create urls.py inside the app? or i should use the one outside ? i created template folder outside the app im really confused can someone help

#

or should i change here

opaque valve
#

Hey I was wandering if i could make a website in python?

raven harbor
#

s u can

opaque valve
raven harbor
#

u can use the django framework

opaque valve
raven harbor
#

yup sites like instagram pinterest are made using django

dusk portal
#

@raven harbor may i help or u have debugged it?

dusk portal
#

@opaque valve

raven harbor
#

@dusk portal please help still debuging

opaque valve
dusk portal
#

i have no idea of roblox game

opaque valve
#

Well verification for discord

#

or other cool stuff i could use my knowledge for

dusk portal
#

ohh

#

django hmm yes u can ezily

opaque valve
#

yes

#

i hope XD

raven harbor
#

@dusk portal i have few doubts to clear have u seen the error?

dusk portal
#

for api part django rest framework or applying react , for non-https requests websockets django channels for everything else django and yes both django channels and rest framework are applied in django so django is full stack

#

u can do

#

everything

opaque valve
raven harbor
#

first i can navigate with django project without any app installed by just creating a views.py

#

but when i create a app should i need to add the template inside the app or to keep it in project folder?

dusk portal
raven harbor
#

okay

dusk portal
#

gimme a sec

raven harbor
#

sure pls

dusk portal
#

from where r u learning

raven harbor
#

from a random udemy course

dusk portal
#

so when u create a app always make a habit

#

app1

#

so write in installed app

#

app1.apps.App1Config

#

and then ctrl s

raven harbor
#

what this does bro

dusk portal
#

can u come voice chat?

#

and and whats ur age @raven harbor

raven harbor
#

im 22 i can come to voice but a bit later now uill hear a lot of bg noice

#

i just wanna know where to put my template folder in the project inside the app or outside it?

#

also do i need to create seperate urls.py inside the app or we can use the urls.py outside the app itself

balmy pollen
#

@raven harbor did u debugged it ??

dusk portal
stoic lark
#

Traceback (most recent call last):
File "c:\Users\isaYILDIZ\Desktop\Decoy\app\worker.py", line 7, in <module>
from database import *
File "c:\Users\isaYILDIZ\Desktop\Decoy\app\database.py", line 274, in <module>
class Lobby(BaseModel):
File "c:\Users\isaYILDIZ\Desktop\Decoy\app\database.py", line 280, in Lobby
members = ArrayField(IntegerField, 5, default=[])
File "C:\Users\isaYILDIZ\AppData\Local\Programs\Python\Python39\lib\site-packages\playhouse\postgres_ext.py", line 171, in init
self.__field = field_class((field_kwargs or {}))
TypeError: peewee.IntegerField() argument after must be a mapping, not int
hi guys i trying convert this repo https://github.com/b1naryth1ef/GoPlayNao from python2 to python3 i fixed some lines and sytax but i stuck here.

GitHub

A web-based matchmaking system for CS:GO. Contribute to b1naryth1ef/GoPlayNao development by creating an account on GitHub.

raven harbor
raven harbor
#

my views and url code

#

the template location

#

project url and settings .py

#

extremely sorry if iam spaming . this wt displayed in my browser instead of index.html

dusk portal
#

@raven harbor I got ur issue
So simple issue

raven harbor
#

wow great ahh for u that maybe simple but i was pulling my head for about an hour

dusk portal
#

XD lol it's ok

#

Lemme tell u reason and then how to fix it ohk?

raven harbor
#

sure sure

dusk portal
#

So u have created urls.py in ur project and app also?

#

Am I right?

raven harbor
#

only urls.py i created inside my app folder

dusk portal
#

It's already there in project

#

Now u r confusing me too lol

#

Just tell me

raven harbor
#

ya bro it was alredy there when i did python manage.py startapp apitest

dusk portal
#

Nice nice

raven harbor
#

both are there in above screenshots bro

dusk portal
#

I got 2 problems in ur code

raven harbor
dusk portal
#

Remove that

raven harbor
#

i added it lol

dusk portal
#

And after ,
'apitest.apps.ApitestConfig'

raven harbor
#

ill remove

dusk portal
#

Yes ;_;

raven harbor
dusk portal
#

ApiConfig

#

Can u?

#

Plz follow a good tutorial seems like u don't know anything @raven harbor

raven harbor
raven harbor
dusk portal
#

It's ApiConfig (same sensitive) right I mean Block(lcapital) letters also match?

raven harbor
#

class ApitestConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apitest'

#

where does this comefrom

#

tried moving the folder out yet same issue 😫

balmy pollen
raven harbor
#

the apps url?

balmy pollen
#

Yes

raven harbor
balmy pollen
#

U ccan u vc now??

raven harbor
#

voice chat?

balmy pollen
#

Yes

raven harbor
#

ya give me a sec

#

vc-0

#

where can v connect i dont have permission to speak in vc-0 and vc-1 is takes

#

taken*

balmy pollen
#

I also
We can call
Check the DM:s

raven harbor
#

okay

dusk portal
#

Now I would love to be better at django
How can I learn Django Channels

#

G0D is online

#

@opaque rivet

opaque rivet
#

I learnt it on YouTube and the source code. I had to give some of my own explanations for things and I thought about it a lot. It was pretty hard but after some time you feel comfortable.

dusk portal
#

Umm can u give me all of them plz ;_; cez i am unable to find @opaque rivet

opaque rivet
#

Literally just search django channels in youtube.

manic crane
#

want to migrate in my django project and ive been getting this error

#

django.django.db.utils.IntegrityError: could not create unique index "Occupy_post_user_id_7dca33ac_uniq"
DETAIL: Key (user_id)=(1) is duplicated.

dusk portal
topaz basalt
#

Hi everyone,

I build a real-time course finder search engine like Coursera using ElasticSearch, Python server, React+Redux, and deployment using Kubernetes.
Please give a star for this GitHub repository, if you find this project helpful.

Repo: https://github.com/dineshsonachalam/tech-courses-search-engine

GitHub

A real-time tech course finder, created using Elasticsearch, Python, React+Redux, Docker, and Kubernetes. - GitHub - dineshsonachalam/tech-courses-search-engine: A real-time tech course finder, cre...

desert estuary
#

anyone is familiar with this

thorn igloo
desert estuary
#

i've done it still it doesn't start the app

thorn igloo
desert estuary
#

oh wait

#

still the same thin

#

thing*

thorn igloo
#

type ls and send a screenshot of the results

desert estuary
thorn igloo
#

what's in run?

#

if you don't mind me asking

desert estuary
thorn igloo
#

hmm. maybe refactor your app into a create_app function

desert estuary
#

it was working before tho like i changed a thing i still have it in python anywhere

#

idk really what happened

desert estuary
eternal blade
#

Hello, me and a some friends are working on a web site, I am working on the backend my friend is working on the frontend, but we are on 2 different machines, how can I make the api I make accessible for the frontend dev?

mystic vortex
#

@eternal blade

eternal blade
#

yes

mystic vortex
#

so how to make a api

#

using flask

#

??

#

or something else?

thorn igloo
eternal blade
eternal blade
mystic vortex
eternal blade
#

then you will need to create an api with an endpoint to receive the data

mystic vortex
#

like the endpoint

eternal blade
#

it covers the basics

feral shadow
#

Hey! needed some help with webdev stuff.

I have a static website hosted on github...
I want to embed some form or button to be able to log user input.

To be a bit more concrete... I'm trying to figure out the easiest way to log someone pushing a button on the website. Its literally for a research project so the code/implementation can be as hacky as possible.

currently I was thinking of embedding a google form and asking people to submit that but the issue is that the website has 100s of such pages that all need to have the logging capability and I'll need to generate a different form for each one... And managing 800 google form spreadsheets is not ideal :\

Put another way, is there a service/framework/etc. where I can open an account in and literally log whatever data I feed it? eg:

A literal website where I can just embed a push request in each button... So

<button onPress=(POST api.shadycorp.com/u/muds?page=1?response=3)>
versed python
feral shadow
#

Lemme check this out. Thanks @versed python

#

@versed python this looks great its literally what I (might) need. Thanks a ton .😭 .😭 .😭 .😭 😭

versed python
rotund perch
#

anyone suggests a CRUD rest api with django tutorial or documentation?

native tide
#

The chance of me receiving help when I post something web dev related in the help channels is 15%

jade lark
native tide
#

what is more great flask or django?

#

Django

quick cargo
#

literally depends on the project and your style of coding really

native tide
#

I use Django even for small projects

#

Django is just more organised IMO

vestal hound
#

then you can work independently

#

contract testing would be quite helpful here

vernal vault
#

Can anyone share some good resources and/or courses for django. I am doing the pretty printed course now, but I want to build an app for my work and its going to be more involved than the toy apps they show you most tutorials. Thank you.

native tide
#

anyone have a link to a Django exclusive Discord server?

vernal vault
#

I couldn't find a valid Django server

ionic raft
#

Question. I'm deploying a Django site to production. i've got a secret key in settings.py. I would like to change it for Production. Can I change the SECRET KEY text inside settings.py to whatever?

#

It looks like there's a generate secret key function...

#

It looks like it's only an issue mid session. Only one way to find out πŸ˜„

ionic raft
ionic raft
ionic raft
#

oh my goodness...I must have messed this up HARDCORE...
I'm getting Forbidden..You don't have permission to access this resource. on every URL...ideas?

#

on port 80...

ionic raft
#

Anyone familiar with Apache?

ionic raft
#

And now apache server won't even start...time to start all over again...

inland oak
#

and then abandoned in favor of nginx

ionic raft
#

I may have to try nginx out.

#

This has hit a wall

#

hard

#

it's sad. Site is great. deploying...PITA

inland oak
#

so your main work done in Django?

ionic raft
#

Done to the point that it's v1 and ready to get out there for testing yeah. But stuck

inland oak
#

the most painless way to deploy django: docker-compose which launches one container with python web server, and second container with nginx as reverse proxy to first container
it makes deployment a matter of writing one command docker-compose up --build

ionic raft
#

fantastic...
Job for apache2.service failed because the control process exited with error code.
See "systemctl status apache2.service" and "journalctl -xe" for details.

#

Ill have to look into that. This is brutal

#

I've followed Corey Schafer's tutorial...and his flies...mine hits a wall. And I'm not alone.

#

Another on SO has the exact same bloody issue

#

Anyways...I've got to fly. Back at this wall tomorrow

ionic raft
#

Yep.

inland oak
#

I could give you a hand if you wish, it does not take a long time

#

but later, at my evening (in 9 hours from now)

ionic raft
#

On Linode

#

That's very kind of you. it's 9.51pm here

inland oak
ionic raft
#

Followed a Tutorial for just a Django site deployment. Apache2

inland oak
#

so, the server can be destroyed and recreated from zero if necessary?

ionic raft
#

In this Python Django Tutorial, we will be learning how to deploy our application to a Linux Server from scratch using Linode.

If you would like $20 of free credit towards a Linode account, then you can use my link here to sign up:
https://linode.com/coreyschafer

We will be covering the entire deployment of a Django application. This includes...

β–Ά Play video
#

Yes....I can wipe from scratch

inland oak
#

good

#

that will make the job fast

ionic raft
#

Yes it's a fresh install...fabulous πŸ™‚

#

I do need to get a cert/https as well

inland oak
#

my solution comes with cert thing included

odd locust
#

HI there.
I'm working on a Flask app that connects some Github stuff to Slack.
Algorithmically speaking, what is the best way to handle 'caching' my slack user list so I don't have to request it via the Slack API every time I need to find a user?
I'm thinking that this would work, but I'm not sure where I should write that user list file to disk relative to the source files for this app.

if a file containing the slack user list does not exist:

  • retrieve the slack user list
  • write it to disk.
    Now that the file exists, load it, parse, use that user list as needed.
versed lotus
#

for shortlived things /tmp is also pretty common

dusk portal
#

oo

#

in django docs rn there is everything different from things that ytber JustDjang0 showed in his docs

#

there's a huge difference

versed lotus
#

different version perhaps? bottom right you can select older versions. though you should probably stay up-to-date

mystic vortex
#

someone help me

final geode
#

Can someone help me with django watermarking images?

eternal blade
inland oak
# eternal blade What is an API contract?

speaking simply...
..a deal between backender and api clients(frontender) that the API could be used in exactly the same way.

That frontender can expect by using the same format to address the API, to receive the same result without breaking his frontend, when a new backend version comes up

#

and with new coming changes to backend, its usage will be still kept in the same way

#

sometimes major breaking changes are inevitable though, but even that could continued supported by... pointing in url, which API version they address

#

the contract is usually described in API documentation

eternal blade
#

Oh

#

Interesting

#

Thanks

opaque rivet
#

is the django development server a WSGI server?

balmy pollen
grave raft
#

`class CsvFile(models.Model):
file = models.FileField(upload_to='csv/')
size = models.FloatField(default=0.0)

class JobBackup(models.Model):
files = models.ManyToManyField(CsvFile)
combined_size = models.FloatField(default=0.0)`

#

how can I get combined size of all the files?? and how to update for every addition in files field

rotund perch
#

Hello guys, Any way for coding automated django tasks? like creating files, code, etc.. with the console. Like (python manage.py)

opaque rivet
#

ok. so I'm looking to deploy my first django app. The backend will be served by gunicorn as that has some benefits over the inbuilt django server, then I have to learn nginx to serve my staticfiles and to act as a proxy between the users request on port 80 and my gunicorn server on port 8000.
how do I then "deploy" it? can I use AWS?

rotund perch
#

you can deploy it for free, but with limitations just to try

opaque rivet
balmy pollen
manic frost
#

Is there a built-in inverse of request_response in Starlette? Something like this:

class PassThrough:
    """
    Pass-through around an ASGI app.

    In many places, Starlette accepts either a function/method or a
    custom object. THe former is interpreted as a request->response
    function, the latter as an ASGI app. This app allows treating
    plain functions as ASGI apps.
    """
    def __init__(self, app: ASGIApp):
        self._app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        await self._app(scope, receive, send)

I have a function which is an ASGI app and I want to treat it as an ASGI app instead of a request->response function.

rotund perch
balmy pollen
grave raft
opaque rivet
grave raft
rotund perch
dusk portal
#

umm

#

i need help bruh

#

@eternal blade

#

according to the docs if user does not make consumers.py he'll get error but im not getting any error

#
  • plz check am i applying django channels perfectly
#

added 'channels' in installed apps then below wsgi
ASGI_APPLICATION='ChatApp.asgi.application'

#views.py
from django.shortcuts import render

def index(request):
    return render(request, 'app1/index.html')

def room(request, room_name):
    return render(request, 'app1/room.html', {'room_name': room_name})
#urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='index'),
    path('<str:room_name>/', views.room, name='room'),
]
opaque rivet
eternal blade
opaque rivet
#

you haven't created any consumer to accept that ws request so you'll get an error

dusk portal
dusk portal
opaque rivet
#

then maybe you're not making a request to your websocket endpoint?

#

check the network tab. do you see the request?

dusk portal
opaque rivet
#

that's not the console though is it

dusk portal
#

console == empty

opaque rivet
#

what was the point of sending that screenshot

#

oh there is a console

dusk portal
#

lol

opaque rivet
#

check the network tab

dusk portal
#

yes

#

i too saw

#

empty

#

XD

opaque rivet
#

so you're not making any request to your ws endpoint

dusk portal
#
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('app1.urls'))
]
``` proj urls
#
urlpatterns = [
    path('',views.index,name='index'),
    path('<str:room_name>/', views.room, name='room'),
]
``` app urls
opaque rivet
#

You got any JS?

dusk portal
#

yes

opaque rivet
#

I don't know the docs. But you have no consumer route and you're not making any request to the route, so yes, it makes sense you have no error

dusk portal
#

in both index and room

dusk portal
#

from where u learned it from yt?

#

or udemy

opaque rivet
#

Docs and yt

strong palm
#

Can anyone who knows Django and DRF peek into #help-cookie for my question about filters please?

cerulean badge
#

logo_django2
model

class OrderItem(models.Model):
    order = models.ForeignKey(
        Order,
        related_name='items',
        on_delete=models.CASCADE
    )
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(
        default=1,
        validators=[MinValueValidator(1)]
    )

form

class UpdateCartForm(forms.ModelForm):
    class Meta:
        model = OrderItem
        fields = ['quantity']
        widgets = {
            'quantity': forms.NumberInput(
                attrs={
                    'min': '1',
                    'class': 'form-control d-inline add-to-cart-input'
                }
            )
        }

min value is still 0 at frontend

manic crane
#

for renderItem is it compulsory i use item as the argument or can i use any random word

minor island
#

logo_django2
When I make migrations(python manage.py migrate) I have error.
ValueError: Related model 'main.users' cannot be resolved
I have model users, which extends from AbstractBaseUser. I deleted db file. One of models migrated successfully, bot model users not. How to fix it?

Code and full error(question on Russian language) : https://ru.stackoverflow.com/questions/1320586/valueerror-related-model-main-users-cannot-be-resolved-django

rotund perch
#

Guys I want to know how to make the BASE_DIR = the root of my project, not of my app

low badger
#

any help for that Django error ?

minor island
stiff totem
#

can anyone tell me why any exception is not throwing even i submit wrong id ? it throws only django.db.utils.IntegrityError: insert or update on table "core_label" violates foreign key constraint "core_label_admin_id_ffc7b8a7_fk_account_user_id"

@transaction.atomic
def mutate_label_update(*_, id: str, input) -> Label:
    try:
        label = Label.objects.select_for_update().get(id=id)
        for key, value in input.items():
            setattr(label, key, value)
        label.save()
        return label
    except (Label.DoesNotExist):
        raise GraphQLDoesNotExistError
    except IntegrityError:
        raise "IntegrityError"
    except Exception:
        raise "Error"
low badger
cerulean badge
minor island
#

Yes, I delete it and all start working

#

Thanks

native tide
#

in flask how do i stop a python var from sending over with quotation marks its causing my html to escape itself i think and breaking links

#

i think it has something to do with taking a list index which includes quotes but unsure how to strip in in the actual html

rotund perch
#

Trying to do auto-create & edit for django folders/files but it is not really working as expected, any help?

from django.core.management.base import BaseCommand
import os 

class Command(BaseCommand):

  def add_arguments(self, parser):
    parser.add_argument('folder', help="Write the APP Name")

  #display it in the documenation
  help = 'Creates Necessary additional Files/Folders for an app'

  def handle(self, *args, **kwargs):
    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    folder = kwargs['folder']

    path = os.path.join(f'{BASE_DIR},{folder}')

    file = open(f'{path}/urls.py', "w+")

    path2 = os.path.join(f'{path}, templates')
    os.mkdir(path2)

    path3 = os.path.join(f'{path2}, {folder}')
    os.mkdir(path3)

    file2 = open(f'{path3}/home.html', "w+")

    file3 = open(f'{path}, views.py')

    file.write(
      """
from django.urls import path
from . import views

urlpatterns = [
    #to direct to the views
    path('', views.home), 
]

      """
    )

    file2.write(
      """

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
  <!-- this is the home page we got from the views.py-->
    This is the home!
  </body>
</html>

      """
    )

    file3.write(
      """

def home(request): 
  #this is the function for the url
  return render(request, "appname/home.html") 

      """
    )

    self.stdout.write(self.style.SUCCESS(f'Neccesary Folders/Files are Created Successfully!'))
native tide
#

that doesnt make it any easier to read

rotund perch
#

yes sry , edited it

native tide
strong palm
dusk portal
#

i want to send user mobile push notification and backend for frnd requests , is it necessary to apply django channels ;--;;--;;-

cerulean badge
#

logo_django2 ```py
@login_required
def checkout(request):
try:
order = request.user.orders.get(placed=None)
if order.items.filter(product__available=True).exists():
pass
except Order.DoesNotExist:
pass

what error should i raise if someone tries to visit checkout url when no order exists or there is not in stock products in order?
#

404?

ashen bay
#

Does anyone know how I can include a modelfield within an email subject line?

I've correctly set up a send_mail function to send an email based on when a new item is added via a CRUD setup

I would like my email subject line to include the name from that form input

rotund perch
# cerulean badge 404?

404 stands for page not found. I dont think thats the best solution since it is a checkout page. Why not just render an HTML with a message "No orders found" or "You did not add any order".

tidal garden
#

what request should i make to get user guilds from discord api

odd locust
#

Hey, can anyone explain how to send this as a Response object?
This is from the url_verification help page in the Slack API documentation:

If you prefer, you can respond with application/x-www-form-urlencoded:

HTTP 200 OK
Content-type: application/x-www-form-urlencoded
challenge=3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P

Or even JSON:

HTTP 200 OK
Content-type: application/json
{"challenge":"3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P"}

I've gotten this far:

@app.route('/slack_event_handler', methods=['POST'])
def handleSlackEvent():
    payloadJS, payload_raw = get_payload_request(request)
    if( payloadJS is None or payload_raw is None ):
        print( "failed to parse JSON!!")
        return Response(status=401, response="failed to parse JSON")

    print(json.dumps(payloadJS, indent=4))
    challenge = None
    if 'challenge' in payloadJS:
        challenge = payloadJS['challenge']

    headers = {
        "Content-type": "application/json"
        
    }
    params = {
        "challenge": challenge
    }

    return Response(status=200, headers=headers, params = params)

but I can't get the challenge to send correctly.

naive egret
naive egret
naive egret
odd locust
#

Does anyone know how to create a JSON payload for a Response() object?

#

I'm trying to send this:

HTTP 200 OK
Content-type: application/json
{"challenge":"3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P"}
#

Obviously, i'm going to send the proper challenge back.

#

but I am having no luck sending back the challenge in a Response(status=200, headers={"Content-type": "application/json"}) object

#

Got it!
response = json.dumps(params)

native tide
#

anyone here has experience with heroku?

onyx cosmos
#

Anyone can help in slider photos in html css !! pls

rotund perch
rotund perch
onyx cosmos
rotund perch
onyx cosmos
#

come dm i will show my college activity

limpid python
#

Hey!

I am trying to load a JS file into django with this:

{% load static %}
<script src="{% static 'js/site.js' %}" type="text/javascript"></script>  

But it dose not work, although, my CSS file loads

static ->
  css ->
    style.css
  js ->
    site.js
meager anchor