#web-development
2 messages Β· Page 183 of 1
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)```
never tried, let me search it up
I think it uses BS4 as well
but it's especially designed for scraping a lot of websites
What do I do if I get a 404 with loading my CSS file
u need to check the path and where u place the file
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 -
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>?
r you using git?
yes
I'm guessing a template failed to execute
Hey is anyone here?
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)
// 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
hey all, is there a Django and DFR developer here ?
I use Django. Not familiar with DFR though
do you mean DRF
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
DRF isn't for anything database-related, it's for exposing an API for your website
AFAIK
OOOOOoooooo...Thank you! π That makes sense. I really appreciate that answer.
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.
Yes sorry DRF
just ask your question
TBH Iβm just trying to find a community Django or someone to talk exchange about it and exchange some of the experience maybe
So I ask here, who is familiar with Django and Django rest framework
a fair number of people
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
I have already been attempted that lol.
@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
This guy has a good vid on how arbitrary == is in JS
https://www.youtube.com/watch?v=V3vZSO4zpFs
tool - https://emnudge.dev/abs-eq/
ToPrimitive in JS - https://jsitor.com/5ktE3jQzt8
0:00 - Introduction
0:49 - Implicit Coercion & Loose Equality
2:15 - The Spec And you
3:15 - The Abs Eq Stepper
6:50 - The Headscratcher
8:48 - Understanding ToPrimitive
12:08 - Throwing Errors
15:00 - Closure
Guys which framework is better for a web dashboard - Vue.js, angular, react
the function needs to retrun something, return some error code if the name is not in the json file
i fixed it but thank you
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.
for an ecommerce site how do you get the shipping cost? pre defined cost per city?
should you create form in django even for just add to cart form? or should you just hardcode it?
how 2 add input tag in flask
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
DRF is not replacing, it is complimenting what Django has.
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
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...
any web site can be basically split into Frontend from pure Html+CSS+Javascript made in React
and backend being done fully as REST API (which allows us to use any necessary language to do it)
it is a matter of following microservice architecture
and having better scalability for enterprising things
That wouldn't work well for my use case. 5 subscription levels, 4 paid, managing process improvement projects...there's a LOT of conditional controls all over the place
it means you have tight coupling. Which is not good.
Wow...that's very confident of you given that you have no clue what I'm building.
Generic statements like that really don't make sense.
It's like when people say....global variables are BAD!
When the reality is, there are very sound use-cases for global variables
monoliths have their own usage too
perhaps this book could give you a bit more food for thought
Thanks. I'm actually familiar with both concepts.
You on the other hand have no clue what I'm building. and just jumped to an un-informed opinion about how it was "bad"
I'm all for good advice. But unsought for opinions based on zero-clue of what I'm building...
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.
Yes...because the entire premise is based on users being able to access their project related information. The very nature of Process Improvement Project Management builds on a number of tools. Those tools are all associated through a hierarchy:
Organization - Team - Process - PIP - PIP tools..
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
Why do i ALWAYS get a 'preparing wheel metadata ... Error' when I'm trying to install requirements.txt
@ionic raft r u there , my real friend where r u
Might just bring this up again, I would really appreciate any advice. π
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)```
why there's no session for django-rest-framework?
what u mean
u mean resources?
yes
yes ofc as advance u will go resources will decrease but dont worry see playlist of JustDjango Codewithmosh and it's official docs
the easiest way honestly is to use djangorestframework_simplejwt
you just import the urls
ohh
also jwt is better than normal tokens
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),
}
(context django) it doesn't matter which model have o2o right?
o2o?
also when I said this I assume you should know that you should pip install it and then add it to your apps in the settings
yea doesn't matter as long as the connections make sense
if you want a tool to help you design your database use drawsql.com
btw there is a method that is more secure but needs a bit more steps, this method sets the cookies automatically
which is much more secure since no client will get the cookies, only django and the browser
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
6. Do not post unapproved advertising.
9. Do not offer or ask for paid work of any kind.
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
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
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
If you need to look at any of the code here is the github linkπ
help
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.
There are some recent responses on a similar issue https://github.com/realpython/flask-boilerplate/issues/14
I see
Hello, i want know how to get response of a get request
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?
why do you need both?
Because these settings are needed from many different places, async external api requests, pydantic models/validators etc.
response = requests.get("url")```
Hello everyone. I had posted this error yesterday. but no luck. please help me for the error..
thanks a lot of
No problm
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">```
try this
it works for me
No luck. I think curly braces is not working properly.
nope. i have to see some git reference. thanks
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
hey users
π
could you helpe me with one django issue
my django app doesnt recognize static directory when i use gunicorn with wsgi
but it works with manage.py
how can I pass a context to the base.html?
That message came in at 2am my time...was asleep π
How can I make custom user model django
Never tried plz tell me XD
Show me
I've not done that either. I've used the baked in User model and added a OneToOne relationship with a Profile. That way, I customize the Profile as much as I need. I only use username, email, and password1 and password2 for user model
I have, however, engineered in a Support ticketing system into LanesFlow over the past couple of days π
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.
How can I make a model/ serializer/ view of django for a mysql view?
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
In the same way as for any other database
The only thing is changed, your used database driver installed in OS, and url/login/password to database. So purely auth settings changes for your project.
i love python
Nice
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 ?
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?
That's the reason I love u too
U're smart
Gr8 choice
you can do
kwargs = {'my_field_name': Subquery(my_sub_query)}
queryset.annotate(**kwargs)```
And I could replace 'my_field_name' by let's say my_field_name_var?
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
someone can help me
:c
my website works with manage.py runserver
but it doesnt work with gunicorn
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 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
what if you apply a color to the border?
with border-color i presume?
yeah
What if you do just: border: 1px solid black?
hmm still no change
@clear bone Can you send the table HTML as text?
<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
not sure it is the cause, but shouldn't it be </tr> {%endfor%} and not ```
{%endfor%}
</tr>
hm, for some reason thead doesn't accept a border at all
hmm i tried also for "item-count" which is a tr element, but it also didnt work
hello , try to use bootstrap classes
@clear bone Add css border-collapse: collapse; to the table
https://stackoverflow.com/questions/31040422/table-borders-not-showing-up
https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse
oh wow that did the trick!!!
yes use style attribute inside tbody
thank you so much!!!
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
What framework are you developing on? Flask? Django? Something else?
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
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
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.
Oh so django provides a webserver? so that means I don't need to setup my own?
Yes. Both Flask and Django include a web server. They're a great place to start. I'd recommend Flask for ease of use.
Django has a robust framework for authentication and is used by some major players out there (very credible).
Django also brings outstanding authentication and administration tools out the box
If your web app is simpler, then Flask is great though
Great! Thanks for the information, when they said python is beginner friendly they really mean it
I was struggling trying to understand how all this web server and backend stuff worked
but now it'll be easier
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.
I recommend Corey Schafer's Flask tutorial on YT
Does django provide web security?
Or is that up to the user
And then some!
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.
Alright thanks, I'll try flash first then move onto django
Good luck! π
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
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"]
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.
yes me too
ive changed to production mode and it just donβt do it anymore there are no logs even when i hit ctrl c
Django runs on port 8000 for me in dev.
http://127.0.0.1:8000/
Port 80 will conflict with your web browser. You need a unique port number I believe.
Flask uses 5000 by default.
80 is the default port for web apps, it's what your browser uses as a default when you request http://some.web.site/
Don't have a solution for your issue atm but I noticed that you create a venv but never activate it so I don't think it's doing anything in your current image.
The buffer is not being flushed lol
Wait lemme find my repo
https://github.com/IgnisDa/learning/blob/a6ca89c064c333997690dd8d519b6e50e5189092/tools/shell/env-vars#L10-#L11 add these environment variables
tools/shell/env-vars line 10
echo -e "export PYTHONDONTWRITEBYTECODE=\"1\"" >> /etc/profile.d/env-vars.sh```
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?
CGI https://en.wikipedia.org/wiki/Common_Gateway_Interface is what you're probably talking about.
And no, modern Python applications don't work like that.
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.
set env variable PYTHONUNBUFFERED equal to 0
@opaque rivet correction, to 1
part of dockerfile:
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
if the guy wants to see realtime terminal output then it shouldn't be buffered
@opaque rivet i want users to upload pdf which type of model will i use FileField?
per hour?
filefield works fine
For a project it's my first proj
For its back-end
Whole proj backend

Is your friend jeff bezoz or something
he's jeff bezoz but of poor's
Lucky
lol
badluck
can u tell me place where i can really do freelancing
instead of working for a pizza( 75$ dollar lmao)
Nope I wanna get started too
Most of my previous free lancing was my friends referring me to others
Your friend is paying you 75$ for entire project or per hour
small kind of proj so proj
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..
That's still good
Since covid, many programming jobs have gone 100% remote and there are much more now
;-; sadd
I have a good github and a portfolio website.
But i would prefer a freelance, since im in college
FileField with some validation
So there is a different freelance / contract, or someone just gives you a program / website to build and leaves you to it
ohh
both are freelance
yes that's 101% true
but you not working for any company
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 π
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
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
there are things like upwork, people per hour, fiverr
ohh
Okay thanks Iβm gonna try it
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.
oh cool, so it literally can be anything to work
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?
yup
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
python manage.py makemigrations
python manage.py migrate
Β―_(γ)_/Β―
thanks it worked
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...
the templates just wont apply for me
i followed his steps but it wont apply
did you link the bootstrap or not? it looks like you didnt at all
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:
where can i check
in your html
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 %}
when you right click and inspect, are these links present?
i said when you inspect in the browser, not your editor
the dude from the video downloaded a template on github and the designs somehow overrided the old design
the base thing works
if that's not working, then idk, it's not being applied on your page
https://www.youtube.com/watch?v=Rpi0Ne1nMdk&t=1441s
here im at
17:15 currently
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...
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
looks to me like your bootstrap is not being applied on that page
are you extending the base in it?
i have no idea what im doing.
yea... learn the basics before you do something this complex
just wanted to have a base to learn it
yea i gues that makes more sense
once you do you'll probably see why your styles are not applying
yea started today with django
there is alot to learn
already taking notes and all but it will take time
and you jumped to use authentication? damn
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
is this a help to help me?
i think here is the issue
your issue is styling bro. i don't know django like that but i don't think the backend stuff affects your styling
and again, learn the basics first
Do u know why I canβt access to my web server whereas when I ran it on my computer I was able to access to it? I used curl to make a get request
hi does anyone here do web scrapping?
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?
Firewall should be checked first for this. ufw comes first to mind
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
what about dynamic ips?
Yea I'm going to be using nginx
Add ip rule by mask.
Allow all ips from your internet provider for example
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
so I should use apache?
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.
I really need some help there
sorry, I haven't used the library. I assume UserLoginSerializer is initialized with url and username attributes?
its telling you to run the migrations: python manage.py migrate
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
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
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
Ignore that just noticed I'm using a .txt extension but tryna find a .text which doesn't exist
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
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
you will need javascript for this
to read the input number and then display that many textboxes dynamically
Any idea, How to do it?@Dark Iceman
how do i write <> with a word inside?
this is what i get
do you know js?
yes, i do
any1?
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
tysm
thanks@Dark Iceman
What is a good program for writeing HTML?
@thorn igloo thx π
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
so dead
it's because your model has 3 mmm's in the field name commented on.
hi. please try domonic and let me know what you think. https://github.com/byteface/domonic
mmm's???
ye it says commmented_on but should be commented_on
should I git clone?
that's crazyπ« good eyeπ
if you like. its not related to your problem. just a thing im sharing
you can
pip install domonic
to play with it
ok
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?
You will need to recode it. Alternatively would you like to publish it to pypi so people can pip install it.
I didn't even think of that haha. I think I'd need to polish it up a bit as it's a bit messy to actually use, but interesting idea
@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
You can create a package (https://packaging.python.org/), which provides a standard way of installing Python programs
Guys which js framework is best for a starter in web dev
Yeah, I get that, but either way it's just not super user-friendly when it comes to actually working with the code. The actual program is fine, though. If I were to clean it up I'd probably put it up on github and make a package and stuff
If you've never touched JS, I would suggest making a simple interactive website in pure JS.
Well i am making a Discord bot dashboard that's why I am searching for a js framework to work on
Svelte is pretty nice and simple https://svelte.dev/tutorial/basics
How does it look like ?
wdym look like?
Can I see a website that is made with svelte
The looks are completely independent from the JS framework. They're defined with HTML+CSS.
Do u mean that I can use it along with html and css
??
Do you know how websites work on the frontend side, in general?
I am new to this
But learning at the moment
HTML defines the structure of a page.
CSS defines how each element looks like.
JavaScript allows you to add interactivity to the page.
Yes, svelte is just a tool to make writing a complex application easier.
If you're totally new to this, https://freeCodeCamp.org seems like a good way to start with frontend.
Ok
Is learning REST api same as learning web API?
@manic frost is it possible to make single page application with svelte?
yes
REST is a set of constraints that are often used in web APIs
https://en.wikipedia.org/wiki/Representational_state_transfer
@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?
I don't know, I haven't used react.
ok
yep π
i can try sure
can u tell me how to use django
rn i am learning about how to use js in html and how to make js functions
so i am not saying about react rn
i am saying about normal html file
i want to know how to make routing
system
django is a python backend web framework. I suggest watching some beginner youtube videos
well is django compatible with async
??
cause as i am going to use it for my discord bot i need it
yes you can have async views
ok and can u tell me how to make routing with django using async
you can watch some tutorials on django to make whatever you want, you dont need me for it
as u wish
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?
show your HTML
Django is, but DRF is not
can I send the css first?
.todo{
position: absolute;
left: 600px;
top: 1400px;
display: flex;
}
well
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
yes
I'm not that familiar on css, but I can understand..
okay, then you should know what to do
I actually don'tπ
π₯΄
that's why I asked this
are you SURE you know?
I know what most of them are used for, but for this case I thought some padding might help, what do you say?
no
this is entirely the wrong way to go about it...
okay
oh
alright, so position absolute does not affect other element around it and also it does not get get affected by the other elements...
uh
not true
I think you're thinking of position: fixed
position: absolute is affected by the containing block
but anyway
well, as I said I'm not that familiar on css, but I can understand..
so
I'm going to assum
eeach todo
has class="todo"
so all your todos are absolutely positioned
ok
so, the default positioning is static
oh
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
oh
yeah
in general
you only want absolute/fixed
when you want something to overlap something else
so, the solution is to use static?
ohk
so, if absolute or fixed can overlap elements and static is by default, then should I use sticky?
wait
hold up
why do you want to use sticky
idk, thought that maybe that might be used....
sticky is basically
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
show your HTML
<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>
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?
there are a lot of SRCs in the folder which I had done
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
oh alright
What is DRF
...did you Google it?
Django REST Framework. Addon to Django for making REST APIs. A set of libraries to make Django a bit more suiting the task.
the first result for "django drf" is Django REST Framework
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
yes you are right
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
Hey I was wandering if i could make a website in python?
s u can
is there any specific way how?
u can use the django framework
would this include receiving and sending https requests also could i make an api using django?
yup sites like instagram pinterest are made using django
@raven harbor may i help or u have debugged it?
what u wanna make
@opaque valve
@dusk portal please help still debuging
stuff for roblox
ohk tell me the features
i have no idea of roblox game
@dusk portal i have few doubts to clear have u seen the error?
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
sure
ok ill need to watch a couple of tuts for that
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?
yes just docs vids and practice else for errors and advices ask here , we r the ppl for the ppl by the ppl
wait lemme tell u
okay
gimme a sec
sure pls
from where r u learning
from a random udemy course
ohk cool nice
so when u create a app always make a habit
u go to settings.py and if ur app name is
app1
so write in installed app
app1.apps.App1Config
and then ctrl s
what this does bro
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?
@raven harbor did u debugged it ??
In ur app
name folder templates
Inside it one more folder by ur app name then go to ur app's views.py
there in return add the last folder name(app)
appname/index.html
And yes u need to create 1 more urls for ur app
And it will work for sure and go to settings.py in templates dirs u will see a empty list write there
'templates'
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.
not yet bro trying as im just starting wanna know certain things
did bro same issue
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
@raven harbor I got ur issue
So simple issue
wow great ahh for u that maybe simple but i was pulling my head for about an hour
sure sure
Nice nice
both are there in above screenshots bro
I got 2 problems in ur code
ono
i added it lol
And after ,
'apitest.apps.ApitestConfig'
ill remove
Yes ;_;
is this the proper way to add app to settings?
Yes the format is
appname.apps(this apps is constant never changes).Urappname(1st Letter in capital) and Config (C in capital)for checking see ur apps
App.py there u can see
ApiConfig
Can u?
Plz follow a good tutorial seems like u don't know anything @raven harbor
s i can c
okay as i am new cant guess and find a good one
It's ApiConfig (same sensitive) right I mean Block(lcapital) letters also match?
class ApitestConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apitest'
where does this comefrom
tried moving the folder out yet same issue π«
Send the URLs appearing in this image
the apps url?
Yes
U ccan u vc now??
voice chat?
Yes
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*
I also
We can call
Check the DM:s
okay
Now I would love to be better at django
How can I learn Django Channels
G0D is online
@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.
Umm can u give me all of them plz ;_; cez i am unable to find @opaque rivet
Literally just search django channels in youtube.
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.
Dude it's written in the error itself
Show urs views and when u r getting this error
Describe whole issue
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
anyone is familiar with this
$env:FLASK_APP="run.py"
it's one word with no spaces
type ls and send a screenshot of the results
hmm. maybe refactor your app into a create_app function
it was working before tho like i changed a thing i still have it in python anywhere
idk really what happened
i didn't get yo
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?
@eternal blade
yes
i meant create a function that creates the app. but nvm
can you be more specific on what you are trying to do?
this guides you on how to make a REST api
i am trying to take the data inserted in my frontend web dashboard made from php to another machine that is having my db in it
then you will need to create an api with an endpoint to receive the data
so is there anything in it that u said above
like the endpoint
yes it teaches how to create endpoints py @app.route('/hello/') def hello(): return "Hello World!" this is from the article
it covers the basics
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)>
I suggest moving to netlify and using their netlify forms feature. As for the form itself and including it on all the pages, you're better off using some templating language to do it
Lemme check this out. Thanks @versed python
@versed python this looks great its literally what I (might) need. Thanks a ton .π .π .π .π π
Haha never used it myself but its pretty cool
anyone suggests a CRUD rest api with django tutorial or documentation?
The chance of me receiving help when I post something web dev related in the help channels is 15%
please #π€‘help-banana
Well, depends on what you're wanting to do. Are you both on the same network? You have two options.
- Git and make sure to commit frequently. They would need to run the backend themselves.
- Setup port forwarding on your network and have him use your IP & port (I wouldn't recommend doing this)
my views
literally depends on the project and your style of coding really
define the API contract first
then you can work independently
contract testing would be quite helpful here
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.
anyone have a link to a Django exclusive Discord server?
I couldn't find a valid Django server
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 π
basically? yes
Thanx for the confirm. π
It is a very long random generated key...just wanted to make sure I could change
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...
Anyone familiar with Apache?
And now apache server won't even start...time to start all over again...
half of year ago I used it
and then abandoned in favor of nginx
I may have to try nginx out.
This has hit a wall
hard
it's sad. Site is great. deploying...PITA
just not knowing the right tools
so your main work done in Django?
Done to the point that it's v1 and ready to get out there for testing yeah. But stuck
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
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
so, you have django right?
Yep.
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)
which services the server has besides this application
Followed a Tutorial for just a Django site deployment. Apache2
so, the server can be destroyed and recreated from zero if necessary?
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...
Yes....I can wipe from scratch
my solution comes with cert thing included
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.
usually some temporary data like that is not written relative to the source files at all, but instead relative to the system, or the user directory. e.g. on linux there is the ~/.cache directory where apps tend to create their own subdirectory to store temporary data. On windows similar locations probably exists as well (%appdata% somewhere? dunno)
for shortlived things /tmp is also pretty common
oo
in django docs rn there is everything different from things that ytber JustDjang0 showed in his docs
there's a huge difference
different version perhaps? bottom right you can select older versions. though you should probably stay up-to-date
Cool, thank you!
someone help me
Can someone help me with django watermarking images?
Thanks
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
is the django development server a WSGI server?
yeah bro
`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
Hello guys, Any way for coding automated django tasks? like creating files, code, etc.. with the console. Like (python manage.py)
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?
Try heroku
you can deploy it for free, but with limitations just to try
Django ORM has inbuilt functions for this
from django.db.models import Sum
CsvFile.objects.all().aggregate(Sum('size'))
do you need this??
python manage.py shell
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.
no, I meant making it custom. Like (python makefiles) for example, and it will take care of doing some files for me.
**ig **it is not possible.
google it?
I want for that particular job but that can be handled by filter method .... but what if a new file is added using jobBackup.files.add(csv_file) now how will I update size field in JobBackup model do I have to use post_save ?? Thanks
yeah if you want to setup side-effects once a model instance gets saved, use signals, good idea mate
just got to know about m2m_changed signal
Thank you! Thats exactly what I wanted
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'),
]
are you making requests to your websocket view from your frontend yet?
me too dont know that much just following https://channels.readthedocs.io/en/stable/tutorial/index.html
yes
sorry i am in a class
ok, so what do you see in your browser's console?
you haven't created any consumer to accept that ws request so you'll get an error
wait lemme send screenshot
that's what im saying but i am not getting error

then maybe you're not making a request to your websocket endpoint?
check the network tab. do you see the request?
that's not the console though is it
console == empty
lol
check the network tab
so you're not making any request to your ws endpoint
umm but i followed the docs can u tell what im doing wrong
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
You got any JS?
yes
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
in both index and room
django channels docs are bad
from where u learned it from yt?
or udemy
Docs and yt
Can anyone who knows Django and DRF peek into #help-cookie for my question about filters please?

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
for renderItem is it compulsory i use item as the argument or can i use any random word

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
Π£ ΠΌΠ΅Π½Ρ Π΅ΡΡΡ ΠΌΠΎΠ΄Π΅Π»Ρ users, ΠΊΠΎΡΠΎΡΠ°Ρ Π½Π°ΡΠ»Π΅Π΄ΡΠ΅ΡΡΡ ΠΎΡ AbstractBaseUser. Π― ΡΠ΄Π°Π»ΠΈΠ» Π±Π΄ ΠΈ Ρ ΠΎΡΠ΅Π» ΡΠ΄Π΅Π»Π°ΡΡ ΠΌΠΈΠ³ΡΠ°ΡΠΈΠΈ. ΠΠ΄Π½Π° ΠΈΠ· ΠΌΠΎΠ΄Π΅Π»Π΅ΠΉ ΠΌΠΈΠ³ΡΠΈΡΠΎΠ²Π°Π»Π° ΡΡΠΏΠ΅ΡΠ½ΠΎ, Π½ΠΎ ΠΌΠΎΠ΄Π΅Π»Ρ users Π½Π΅Ρ. ΠΠΎΠ΄ΡΠΊΠ°ΠΆΠΈΡΠ΅ Π² ΡΡΠΌ ΠΏΡΠΎΠ±Π»Π΅ΠΌΠ°. Π ΠΊΠΎΠ΄Π΅ ...
Guys I want to know how to make the BASE_DIR = the root of my project, not of my app
any help for that Django error ?
May be you forgot to make migrations
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"
I'll check it out
did you migrate with the default User model before defining your custom user?
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
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!'))
code block or use the paste service
that doesnt make it any easier to read
yes sry , edited it
turns out the code snippit i was using to learn for some reason made me include quotes when not needed all fixed
anyone?
#help-cookie message
i want to send user mobile push notification and backend for frnd requests , is it necessary to apply django channels ;--;;--;;-
```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?
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
Anyone?
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".
what request should i make to get user guilds from discord api
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.
This is the article: https://api.slack.com/events/url_verification
Add AUTH_USER_MODEL to your settings file
Use pathlib
from Pathlib import Path
BASE_DIR = Path(__file__).parent # depending on file location
Not necessary, if you need real time feeds, then it is necessary
Just redirect to cart
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"}
snippet from here: https://api.slack.com/events/url_verification
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)
anyone here has experience with heroku?
Anyone can help in slider photos in html css !! pls
Ive used heroku before just put the problem and who knows it will answer.
You are trying to make a silder using HTML & CSS only?
yes html and css
What is the problem?
I wanna get some good video from yt which can help me do you have any yt video which can help me
come dm i will show my college activity
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
do you have an error in your browser? what does the dev server output?