#web-development
2 messages ยท Page 24 of 1
honestly I cant see what's wrong there
.center {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 0.5em;
height: 10em;
text-align: center;
display: inline-block;
} .center-under {
height: 0;
}
.samaritan {
transform: translate(-50%, -50%);
border: 0;
font-size: 48px;
box-shadow: none;
border-bottom: 1px solid #000;
} :focus {
outline: none;
}```
<html>
<head>
<title>Iลฤฑk Kaplan</title>
<link rel="stylesheet" type="text/css" href="onecsstorulethemall.css">
<script defer src="onescripttorulethemall.js"></script>
</head>
<body>
<div class="center">
<input
type="text"
class="samaritan"
placeholder=""
spellcheck="false"
autocapitalize="off"
>
</div>
<div class="center center-under">
<span>HELLO</span>
</div>
</body>
</html>```
]
Hello is not directly under the help, rather starts typing from the exact middle
I want the entire hello to be in the middle
Not the start of the hello to be the middle
I'm looking at someone else's code for a flask app and trying to learn some basic stuff with it. I don't quite understand what's going on with this in a template and how it's 'seeing' these variables despite not being passed in the render_template() method
<div class="w3-container">
<p>
{% if config.lang == 'fr' %}
Pour commencer un test, utilisez le lien d'activation
que vous avez reรงu.
{% else %}
You need an activation link to start a quiz.
{% endif %}
</p>
There are context processors
config is app.config, I've seen that much but...
Context processors can give global context to templates
so if I make a variable of my own in my app how can I turn it into one of these global type things?
@app.context_processor
def _():
return {'global': 'hello'}```
where context_processor is the name of the variable?
I'm looking for it in the py file and don't see anything named like that
@app.context_processor
def _():
return {
'global_var_1': 'val_1',
'global_var_2': 'val_2',
'global_var_3': 'val_3',
}```
This can be anywhere
But config is by default
config session request url_for are just a couple of them
thanks, I'll keep digging
I just can't find where they hid this dictionary
or is it possible to set a new entry inside the app?
like, all I'm seeing is things being initialized like
app.config['key'] = 'thing'
do I need to go into the config to create first 'key' entry or will it let me set it like this?
ok nm, I tested it and it seems to work like that
thanks again for the help
hi is there a way to get a template and put it in my django cause it takes too much time to make a custom template
hello?
hi is there a way to get a template and put it in my django cause it takes too much time to make a custom template
as in?
"get a template"
you can just google for templates
and pick one
Build your templates so they are easy to make
A django template is tied to the application
hi, has anyone deployed a python web app on azure before ?
got a simple question regarding their deployment tutorial for python apps
Mind showing your app structure?
oh god solved it
@outer lynx Who?
Hello guys!
I'm looking for a big community for Django/DRF specifically, am I in the right place? ๐
I learned Django like a year ago and I'm getting back to it.
No I haven't used Swagger yet, still getting my hands dirty learning the basics to build confidence around the framework, the docs come later!
Do you recommend any project to get myself started? still going thru the tuts, that would help me alot ๐
Something usefull for your self
Build something that you yourself would use
Timetracking isn't a bad place to start
That's how I started
What I like to do also is finding a project you think is good and learn it
Even if you don't end up changing any code it's very intersting see how other people programmed their django apps
Honestly i'm lacking imagination, I need to build a project that is consistent enough to show it on my portfolio, yes its generally a good idea to read other people's code, its one the best way to learn thank you for the tip!
Try but you can get ideas from other people's code
Believe me, sometime I look at code and I am like damn I want to do that and implement it in my own project
Alright man thanks for the tips ๐
One last thing, which django app you recommend me reading?
I would high recommend looking at Raymond Hettinger talks on wirting better python code too
Hmm
Huge project
No way, didnt know OpenStack was built on django!
Parts of it are
That frontend peice is
Almost all of the api servers are built in flask such as nova, cinder and neutron
Those are intersting too to look at
I remeber looking at what it would take to wirte my own openstack nova driver
It didn't look too hard
Because their code is pretty good
Very interesting indeed, lost myself on reading now tbh x)
You're good man
Tell me, Is Django Rest considered the best way to create robust/secure API? because that's the reason i started learning it. do you think other frameworks offer better alternatives? (I prefer batteries included type )
Honestly the django rest framework belows me out the fucking water
It's so powerful yet simple
Anything I would ever want to do with a Rest api is possible with the django rest framework
I told a programmer, who has never touch django, or even knew about rest to make an api endpoint. He figured the django rest framework out in like 4 hours
That's encouraging, glad to know I'm on the right track x)
I'm surprised there is too few content
had a hard time finding a community
Good luck man! I figured this out and I ended getting a job for doing django deveoplment
I think it's crazy because I don't even have a degree
Thank you so much for the help mate. Really appreciated it ๐
No problem, I am glad to shoot the shit anytime
I don't know why but I hate frontend so much
Javascript feels like mine field of anti patterns
@kindred cosmos Why ping me?
You said Mind showing your app structure?
hello guys
iam beginner in leaarning pyhton
i want to prompt the user to write serial key and user name in the displayed string any one know how to excute two command at the same time in python ??
here the simple code
i still learn the basics
i want user name and serial key to be appeared at the same time in the compiled code
any help
??
Why would I say show your app structure to you when you didn't even ask a question??
@pallid root You might be better off at one of the #help channels, doesn't look like #web-development
iam sorry @outer lynx
why?
all, I've worked out some of my things from earlier and I thank you for it. I'm working on a problem right now where my annotations seem incorrect when I try to incorporate more filtering with django_filter
Here is a mockup of everything
https://dpaste.de/RoQi
The annotations get bloated almost like its not going over the model's queryset but the full queryset
I'm looking for an async Flask-like webframework
There seems to be millions of options
So far I've looked at Sanic, Quart, Starlette
Any recommendations?
@outer lynx may I get an explanation about the @app.context_processor thing?
Im unsure if its due to me using blueprints
I have currently an app.py implementing a blueprint with my routes
@app.context_processor
def _():
return {
'test': '123'
}
and that
Any context processor you create from the app is global
And will be applied to your blueprints
shouldnt I get to read 123 if I do {{ test }} in the rendered template?
yes
that's not happening
Any errors?
nope
what happens instead?
i'll double check really fast just in case
just blank
damn I'm not smart
did the app context under the app start
<.<
also, is the context_processor the place where I should initialize a db connection?
considering that I'll need to access it from the blueprints
so I'll need to connect to mysql with sqlalchemy on each .py file that needs it?
No
It is like blueprints
you write your database stuff in a file
you import it in blueprints
use it
then import it in your main
and init it
^^
@uncut solar what matters most to you for an async framework? What will you be using it for? Iโve building our platform on startlette, which is among the newer but is the best performing, has a lot of momentum, and is written by the guy who also created the ASGI spec that other frameworks use under the hood: https://www.starlette.io/
The little ASGI library that shines.
It doesnโt have as much baked in as others but itโs actively developed and then again it also has a few things baked in that others do not (such as graphql, swagger, etc)
@uncut solar the others Iโve used and enjoyed the most over the last couple years are aiohttp and sanic. They all have their ups/downs so let us know if you have more specific criteria. Iโve only been writing async backend code for at least a couple years now and Iโve encountered most of the joys as well as pain points
Idk, the only requirement right now is websockets
Thanks, I think I'll go with starlette
@uncut solar starlette is great. they all handle websockets well. just gotta be really good about using async properly and all that jazz. the same guy also makes a good async framework for use with sqlalchemy and such
How to do a 24 hour clock in html?
In 00h00 format.
@native tide well, not much to do. you use javascript. you get a new Date(). it will return an object with the current date and time. running its getHours() method will return what hour it is in 24-hour format.
+1 for starlette, great framework
Thx.
@junior cloak
I have a WTForm and it's being printed via flask this way
<form action="/" method="POST" role="form">
<table class="w3-container w3-table w3-bordered w3-striped">
{% for field in form %}
<tr class="w3-red">
<th>{{ field.label }}</th>
</tr><tr>
<td>{{ field }}</td>
</tr>
{% endfor %}
</form>
but the fields, which are radio buttons, are being printed with bullets
how do I specify that I don't want the bullets?
@limber orchid I don't see any radio buttons here
they are in the object, one sec I'll grab the source .py
class Quiz(Form):
name = StringField(u'username', validators=[input_required()])
q1 = RadioField(
"Rule #1 prohibits",
choices=[('chioce 1','chioce 1'),
('chioce 3', 'chioce 3'),
('chioce 2','chioce 2'),
('chioce 4','chioce 4'),
('all of the above','all of the above')
],
validators=[CorrectAnswer('all of the above')]
)
submit = SubmitField("Submit")
and what is the html output?
i mean in code?
diff q, but from the same class
sorry, sec
<tr class="w3-red">
<th><label for="q3">How often can you post a link to your site?</label></th>
</tr><tr>
<td>
<ul id="q3">
<li><input id="q3-0" name="q3" type="radio" value="never">
<label for="q3-0">never</label></li>
<li><input id="q3-1" name="q3" type="radio" value="as often as you want">
<label for="q3-1">as often as you want</label></li>
<li><input id="q3-2" name="q3" type="radio" value="no more than once every 3 days">
<label for="q3-2">no more than once every 3 days</label></li></ul>
</td>
</tr>
ugh, formatting
I'll fix
don't know how to fix it via py with library that you use (need to check docs)
but via html or css it's simple
https://www.computerhope.com/issues/ch001704.htm
I've tried placing this in the css but no luck
fieldset.inlineLabels ul {list-style:none}
How is Python used for web devs
can someone help me with WEBSOCKETS
to understand what is wrong here?
same code on nodejs working fine
but on py - no errors, no outputs, nothing
I need to connect via WS to another server and listen for events
from flask import Flask
import socketio
app = Flask(__name__)
@app.route("/")
def hello():
return "test"
sio = socketio.Client()
sio.connect('wss://socket.............')
@sio.on('connect')
def on_connect():
print('I\'m connected!')
sio.emit('add-user', {token: '.............', type: '.............'})
@sio.on('donation')
def on_message(data):
print('donation')
print(data)
Hi
Can anyone help me adding product quantity
:((((
All is working good til that product quantity
im having issues i think in my views.py
@hollow aurora i'm pretty convinced you can't do that with synchronous code like that - you'll need to delegate the client to a separate thread or you will block your webserver
alternatively, use something like asyncio with starlette as web framework, you'll need to search for a async websocket library though
@austere apex we need way more context for that, see
!ask
Asking good questions will yield a much higher chance of a quick response:
โข Don't ask to ask your question, just go ahead and tell us your problem.
โข Try to solve the problem on your own first, we're not going to write code for you.
โข Show us the code you've tried and any errors or unexpected results it's giving
โข Keep your patience while we're helping you.
You can find a much more detailed explanation on our website.
Trying to center these fontawesome icons: https://i.imgur.com/biMSCJj.png
But I'm pretty shit at CSS
Anyone who could help me out? Here's the HTML&CSS (76 lines all together) https://hastebin.com/utuhuruqol.xml
@native tide
try using <center>somehting</center>
you can also put divs and whatever you want inside center tag
Somehow did not receive a notification even though you mentioned me... got to check my settings.
Thanks, it really was that easy.
np
isnt that deprecated?
nope
is there some special trick to linking a css stylesheet when running your site locally?
it's in the same directory as the flask app .py
I've tried for the href values: style.css and http://127.0.0.1:5000/templates/style.css
and without the port, too
can you put it on git?
which part do you want to see?
so like, if I reference an online .css file, it does work
it's just local ones that are not
did you try making an "Assets" folder and just routing it?
and later referencing everything such as href = "./Assets/filename.extension"
I've tried giving it the full path from C:/
thats always a bad idea lol, keep all your paths relative
yeah well we all do desperate things when trying to debug
hmm this seems like more work than necessary just to do my local testing. I have it working on pythonanywhere using the static file stuff, but am just doing local running to test it
I'll just upload the .css to a website and reference it with http
you do you
but thanks
try to cut external frameworks/platforms to a minimum if you're just starting out
what do you mean?
Algum mago do R ai?
Is there a standard way to make user uploaded images visible on your page while in development? I feel like I'm so close to having this work, but I can't figure it out. The path is fine, but django doesn't recognize my media folder. relevant code: https://pastebin.com/5A9p7DLF
in django
is there any meaning to setting DEBUG = True in a flask configuration if flask uses environment variables at initialization to determine the environment? the config won't do anything since the application would've already been running in a production environment
Can someone help me with my thesis project, adding product quantity. Using teamviewer app. Im willing to give. Im really sorry im just so desperate
@austere apex, you could try codementor.io for help if you're willing to pay for it
Guys i am new to REST APIs. I am exercising and i am confused. There are many ways to do things. For example lets say i have Library object which has child object Book, when i make POST request should i add the Book objects as well or should i make separate url for adding Book objects to the Library?
you would usually go for a separate resource for books in this case, to keep api simple. That will allow you add/delete/modify books without modifying Library itself.
@timid arrow ๐
Has anyone had trouble getting gitlab to load static assets (CSS) for a gitlab pages?
It works on my laptop, I push it to gitlab pages and it doesn't work.
regarding WTForms, for anyone familiar, I'm using them for a multiple choice quiz and would like to have the ability, when the user gets one wrong, to reload the page and show which were incorrect.
I feel like there's gotta be a way to do this, but can't find in the docs how to get it to return which fields failed their validations.
@limber orchid
Can you provide what you've done till now?
yes, so its a standard WTForms class using one StringField() object and several RadioField() objects (I will post an example in a sec, opening my IDE now)
and then I'm using the 'validate on submit' method in my flask app to decide what to do.
I wish I could just find a nice list of all the methods and what they do but these particular docs I can't seem to ever find just like a nice cheat sheet of all the functionality...
this is the WTForms class
class Quiz(Form):
def no_slashes(form, field):
if '/' in field.data:
raise ValidationError('Be sure that you are NOT including /u/ or u/ with your username.')
name = StringField(u'username', validators=[input_required(), no_slashes])
q1 = RadioField(
"question 1 text?",
choices=[
('option 1','option 1'),
('option 2','option 2'),
('all of the above','all of the above')
],
validators=[CorrectAnswer('all of the above')]
)
submit = SubmitField("Submit")
this is the flask app
@app.route("/", methods=["GET", "POST"])
def quizlet():
error = ''
form = Quiz()
if request.method == 'POST':
if form.validate_on_submit():
try:
reddit = bot_login()
#reddit.subreddit('subreddit').contributor.add(reddit.redditor(form.name))
print(form.name + 'approved assigned')
return render_template('quiz_results.html', user_passed=True, approved_submitter=True, user=form.name)
except:
print('approved not assigned')
return render_template('quiz_results.html',user_passed=True, approved_submitter=False)
else:
print('not approved not assigned')
return render_template('quiz_results.html',user_passed=False, approved_submitter=False)
return render_template('quiz.html', errors=error, form=form)
@vagrant adder
Not home rn
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.dropdown-item').click(function(){
var clickBtnText = $(this).text();
var clickBtnId = $(this).attr('id');
var ajaxurl = 'ajax.php',
data = {'id': clickBtnId, 'text': clickBtnText};
$.post(ajaxurl, data, function (response) {
alert("Doing stuff...");
});
});
});
</script>```
Do you guys see any error here?
my ajax.php php <?php echo "<script type='text/javascript'>alert('shit');</script>"; ?> doesn't do anything, or so it seems
But alert("Doing stuff..."); is run
I'm having an issue with font awesome when loaded locally
this is loaded locally
this is from font awesome cdn
thing is, only the datatable sort icons arent working
I am creating a portfolio website with Django and I want to create a contact form. What is the best way to store the data of a contact form. Should I store it in the database or should I make a mail message??
that's on you honestly, if you setup a portfolio and want someone to contact you, will you check your email or that database?
anyone using FastAPI? it looks pretty great
Anyone used the function send_mail() in django to send confirmation mails?? I am trying it with the gmail mail server but I cant figure it out I tested SSL and TLS and this is my error (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError f13sm1232182ejj.7 - gsmtp', '=?utf-8?q?Paul?=')
you aren't specifying email and password for the sender somewhere in the code
I am specifying it in the settings.py file
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'paulogameplays12@gmail.com'
EMAIL_HOST_PASS = '*********'
EMAIL_PORT = '587'
EMAIL_USE_SSL = False
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
this is my views.py
def mainview(request):
all_projects = Projects.objects.all()
if request.method == 'POST':
messagecontainer = request.POST['name']
host_mail = settings.EMAIL_HOST_USER
send_mail('Contact Form', host_mail, messagecontainer,
['paulaldabaghwork@gmail.com'], fail_silently=False)
return render(request, 'portfolio/index.html', {
'all_items': all_projects
})
I tried changing my password, using SSL instead of TLS, using only plain strings, turning on lesser apps and different emails
@sweet wharf gmail is a bit security paranoid i think
i think there is a setting that you have to change on your gmail account
hello guys i am working on a school ERP and i want to add a feature in this project which is when admin add a new student a message will send to user on there email and sms so how can i add this any idea ?
How would you define a "global" object to be used within each Django or Celery process? In my case I want to define a ConnectionPool for redis. I do not really know where I should define it to be clean ๐ค (I cannot use django-redis)
@sweet wharf if send_mail isn't working try EmailMessage method
will flask be able to take a somewhat big pandas dataframe?
@sweet wharf @grand badge I find to get Gmail to work, you need to have 2FA and app- specific passwords.
Otherwise, it will not allow you to use it.
Its their attempt to stop spoofers using Gmail
If I were to write a website writer in python, what other languages would I need to learn for that? I heard css and Linux was good but I'm not sure which ones to use
Html, css, javascript
Well I am actually not sure how much you could get away with on JS knowledge
But other two are essential
I stumbled upon this article not long ago
so apparently you can do a lot with no or minium javascript... if you are bored
Awesome thank you
Hey guys.
any ideias to make it?
I have an API with django rest framework.
I want to display the users of the respective groups in the API.
to make what exactly?
@north swift
I just want to display the users that are in their groups.
something like: users: [<users in the group>]
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
users = UserSerializer(many=True)
class Meta:
model = Group
fields = ('url', 'name', 'users')
guys
i tried to make like that but
i got a : Group has no attribute users
AttributeError at /api/groups/ Got AttributeError when attempting to get a value for field userson serializerGroupSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Group instance. Original exception text was: 'Group' object has no attribute 'users'.
Maybe i have to overwrite the Group models?
asd
asdas
Just tryin lol. sorry
class CartItem(models.Model):
product = models.ForeignKey(Product)
quantity = models.IntegerField(default=1)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.product.title
class Cart(models.Model):
items = models.ManyToManyField(CartItem, null=True, blank=True)
user = models.ForeignKey(User, null=True, blank=True)
products = models.ManyToManyField(Product, blank=True)
subtotal = models.DecimalField(default=0.00, max_digits=65, decimal_places=2)
total = models.DecimalField(default=0.00, max_digits=65, decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def cart_update(request,slug):
try:
the_id = request.session['cart_id']
except:
new_cart = Cart()
new_cart.save()
request.session['cart_id'] = new_cart.id
the_id = new_cart.id
cart = Cart.objects.get(id=the_id)
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
cart_item, created = CartItem.objects.get_or_created(product=product)
if created:
print("yeah")
if not cart_item in cart.items.all():
cart.items.add(cart_item)
else:
cart.products.remove(cart_item)
new_total = 0.00
for item in cart.items.all():
line_total = float(item.product.price) * item.quantity
new_total += new_total
request.session['items_total'] = cart.items.count()
cart.total = new_total
cart.save()
return HttpResponseRedirect(reverse("cart"))
Can i have some help with my qty
my html doesnt count the product default as one
{% if cart.items.exists %}
<table class="table cart-table">
<thead>
<tr>
<th>#</th>
<th>Product Name</th>
<th>Product Price</th>
<th>QTY</th>
</tr>
</thead>
<tbody class='cart-body'>
{% for item in cart.items.all %}
<tr class='cart-product'>
<th scope="row">{{ forloop.counter }}</th>
<td><a href='{{ product.get_absolute_url }}'>{{ item.product.title }}</a>
{% include 'carts/snippets/remove-product.html' with product_id=product.id %}
</td>
<td>{{ item.product.price }}</td>
<td>{{ item.quantity }}</td>
</tr>
{% endfor %}
@fringe fog fastapi is pretty nice. Iโve rewritten one of our internal services to Starlette (from Flask) and that one turned out great, so I am now working on the next, which will use FastAPI. The Python types as schemas idea of pydantic is great
Cool, glad to hear it. Iโm just digging into the docs now and it looks good.
If you donโt mind my asking what are you doing for your data layer? Sqlalchemy is great but not async, I was looking at the databases package as an option. After reading issues and whatnot I see that pydamtic models are separate which seems a little laborious but probably fine (it looks like they are working on that)
@meager anchor ^
@fringe fog i currently use databases with sqlalchemy core with starlette. it is not ideal, and there's some minor issues, but it's been fine for the most part in a production setting. i don't do anything fancy with models -- i just have the db tables, my pydantic object schemas match what the table fields will be, and pass a dict of the pydanctic model to it
havent done too much with fastapi as somewhat ironically ive just finished a total move to graphql for this particular project but i use pydantic a lot and starlette
@fringe fog aioriak
Cool, thanks for the tips guys!
Iโll have to look up aioriak
Ahh i see riak is a nosql datastore
Yeah, for a hobby project Riak is probably a bit overkill, but it's really nice regardless :P
Asyncpg is also a great pick
Wrong place sorry
I've got a flask app that's taking user input and generating an excel spreadsheet. How do I serve this to the user (one time) while not retaining a copy on the server?
@limber orchid can we see the code?
it's openpyxl so the part that makes the xlsx is
book.save('weekly2019_anne.xlsx')
I haven't actually done anything in terms of the flask part because I honestly don't know where to start
my knowledge of flask goes as far as getting the form input and returning html templates
writing a user test case for django
if i'm not mistaken
from django.contrib.auth import SESSION_KEY
from django.test import TestCase, Client
class UserTest(TestCase):
def setUp(self):
self.credentials = {
'username': 'testsuser',
'password': 'testsuser'
}
self.client = Client()
user = User.objects.create(username=self.credentials['username'])
user.set_password(self.credentials['password'])
user.save()
def test_login(self):
logged_in = self.client.login(**self.credentials)
print(logged_in)
self.assertTrue(logged_in)```
does this test register and login?
so, you want to server some xlsx files and delete the file after serving it @limber orchid
@native tide sry but you are interrupting
might wanna take it to some #help channel
oh my fault man
yes, exactly
can you show the code for the route where you want to server
@app.route("/something")
def something():```
flask_app.py yeah
right now it's local but I'll be running off pythonanywhere, if that makes a difference
sure, I'll show what I have but it's not finished obviously ๐ค
doesn't matter
i am going to bed in few mins hurry up
Can i use two frameworks and connect them to each other? like Angular and Django
yes
Sorry but which is better for a blog either i choose Wordpress or make my website on my own and why
@late gale using one front end framework paired with one backend framework is almost always how you do things
Please if someone can refer me a good comprehensive beginner level course for django
I had developed webpages previously using php html css
I know basic of py
@native tide go through the official django tutorial
Does anyone know how whats wrong with my code for quantity
def cart_update(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
entry_obj = Entry.objects.filter(cart=cart_obj)
# product_id = request.POST.get('product_id')
product_id = request.POST.get('product_id')
quantity_input= request.POST.get('quantity-field')
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Show message to user, product is gone?")
return redirect("cart:home")
# cart_obj, new_obj = Cart.objects.new_or_get(request)
Entry.objects.create(cart=cart_obj, product=product_obj, quantity=quantity_input)
# Entry.objects.create(cart=cart_obj, product=product_obj, quantity=quantity_form)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added = False
else:
cart_obj.products.add(product_obj) # cart_obj.products.add(product_id)
added = True
request.session['cart_items'] = cart_obj.products.count()
# Entry.objects.create(cart=cart_obj, product=product_obj, quantity=quantity_input)
# cart_obj.products.add(product_obj)
# added = True
# request.session['cart_items'] = cart_obj.products.count()
return redirect("carts:home", {
'cart': cart_obj,
'entry': entry_obj,
'some_var': some_value,
})
Cannot resolve keyword 'cart' into field. Choices are: eCart, eCart_id, id, product, product_id, quantity
Hey all trying to find some help regarding subqueries. Code https://dpaste.de/GL4y
basically getting an error. I know I"m just approaching it wrong, but trying to StringAgg the qs from MatchEvents into the main match
@rare oar an error is very descriptive
yeah I tried to nest it so its more readable
I honestly don't know. Let me cancel my changes I've been experimenting and paste this origjnal back in here and see
ok
to be honest it looks like it points to the delimiter parameter of StringAgg
wh
ngl django is meh lol
i cant see anything wrong, maybe my inexperience
sounds like a complicated query though
21
django's just weird lol
its gotta be the aggregate function doing something I don't know about
StringAgg must be referencing it or something
oof
Hi all
Need some help with Django. I'm learning it by making a blog app. Following "Django 2 by example" book.
Internal Server Error: /blog/2019/5/19/post-3/
Traceback (most recent call last):
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/vm/PycharmProjects/Example/mysite/blog/views.py", line 43, in post_detail
comment_form = CommentForm()
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/forms/models.py", line 285, in __init__
raise ValueError('ModelForm has no model class specified.')
ValueError: ModelForm has no model class specified.
This is the full error I'm getting
The file it refers to is views.py, i've made some changes to it to allow comments on posts
Here's the section I've made changes to.
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
If I get it right, the error is pointing at the line:
comment_form = CommentForm()
But frankly I don't understand what is wrong with it and how it is related to "ValueError: ModelForm has no model class specified."
can someone please help me?
sure what's up
^
does the modelform meta have a model attribute
@frigid egret i think you need to pass something as CommentForm()
can you post commentForm code?
1 sec
@slender knoll I have another form working fine. If that helps
class CommentForm(forms.ModelForm):
class Meta:
models = Comment
fields = ('name', 'email', 'body')
that's it?
@slender knoll
class Comment(models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='comments')
name = models.CharField(max_length=250)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
Here's class comment
i gave you the fix
wait
at least, I don't see it
try putting model=Comment
instead of models=Comment
@slender knoll don't be so harsh
some are new here
im not being harsh ? this is how i teach people at school
I don't get what "modelform meta" is.
it's clearly not something that's in the code i've posted.
@vagrant adder which file is it?
class CommentForm means "define new class accessible by using CommentForm name"
(forms.ModelForm) means "base our new class on the ModelForm class"
and in there, there is another class, called Meta
it has to be set or list iirc
class CommentForm(forms.ModelForm):
class Meta:
models = Comment #try putting model=Comment
fields = ('name', 'email', 'body')
Oh, got it... almost
now I gotta read on what's the difference between model and models.
cause it is confusing me rn
no
uh... where do I look then?
Thank you guys! ^_^

Hello guys!
hello
I don't know if it's a weird request but still.
I'm learning Django via the book "Django 2 by example"
I have a case here when I understand what this particular code given by the book is doing but I can't quite grasp HOW it does that.
Can someone be so kind to explain it to me in detail?
I could just skip through it cause it's working but I'd like to actually understand
I think it may be more related to Python in general rather than Django specifically
Can you take a look at least? @vagrant adder
yeah i can try
Ok, so here's the code
post_tags_ids = post.tags.values('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]
I have tags implemented and this next chapter is about filtering "associated" posts by looking at similar tags on other posts.
what do you not understand
I don't quite understand how that last line works. I can see the result but it's not 100% clear to me how it's being achieved
it just orders posts by given parameters
in this case these are 'same tags' and 'publish'
posts = Post.query.order_by(Post.date_posted.desc())
this is from my project^^
it orders posts by date posted
can't find what "annotate" does
Thanks. Google wound't give it to me somehow. Only gives a bunch of "data science" articles
Hello all! Am currently working on a Django project but got stuck in trying to add a 'next' parameter to url after user signed in via django's own allauth.
The idea is this, user tries to perform an action on the site in a page say 127.0.0.1:8000/addimage but isn't yet logged in, will be directed to the login page(either google or facebook social sign in) upon clicking on the link. Am trying to append the page where the user was(/addimage) to the sign in link that will be sent to either facebook or google depending on user's method so that upon sign in completion, user will be redirected back to the old page, in this case /addimage
Hi, trying to place circles within a radius of a point without overlapping for my html5 canvas game. Are there any algorithms or design methods for this or other similar 'spawning' patterns? Thanks.
Guys, i will start working a migration of a Django 1.10 project to version 2, any tips on how to do it?!
@red spear make a separate git branch that is django 2.x and make issues on everything that needs to get done so you dont get lost
Hi, can i ask PHP questions here?
@grand badge that's actually pretty amazing, ty
If anyone has more tips about it, I would love to hear it

Hi guys, I'm trying to send an extra parameter (url) to my serializer but it tells me that the url field is not declared in the 'fields' option
Code: https://dpaste.de/Zz1z
I've seen it can be done with context, but i can't get to make it work
is there a way to change the whole page on web ?
like on flask i have
@app.route("/")
def home():
return render_template("test.html")
@app.route("/test")
def home1():
return render_template("test1.html")```
can i do something to change the page from `test.html` to `test1.html` without changing the url
Can someone explain when websockets stop receiving frames? What's to stop an attacker from sending a variety of frames without the final code set? Is there a max amount of frames a websocket message can be made out of? I so what's that magic number?
is it possible to debug flask blueprint routes?
debug means what in this context?
good morning - I want to make a simple web app that captures input from a single form and automatically does some io stuff with the data received on that form. is Flask good for this or would I be better off using a different library?
IMO Flask is perfect for your task @reef rose ๐
I agree, Flask sounds great for that
I have a question I want to ask
How can I fix the top padding of the ul to match the example given
<!DOCTYPE html>
<html>
<head>
<title>Revision excrsise </title>
<link rel="stylesheet" href="tutorial_1/lab_pratice.css">
</head>
<body>
<h1>King of kongs</h1>
<p id= "intro">I'm male, 89 years old, and am a giant, empire state building climbing ape</p>
<hr>
<img src="https://s3.amazonaws.com/codecademy-blog/assets/da840950.jpg" alt="Gorrila image">
<hr>
<ul>
<li>interest</li>
<ul class="center">
<li>Bananas</li>
<li>climbing stuff</li>
</ul>
<li>Jobs</li>
<ol class="center">
<li>giant ape</li>
<li>web developer</li>
</ol>
<li>where i went to school</li>
<ol class="center">
<li>Diddy kong jr. High school</li>
<li>Donkey kong Sr. high school</li>
</ol>
<li>favorite quotes</li>
<ul class="center">
<li>"at first you dont succeed climb a giant building"</li>
<li>"A Banana in hand is worth two on a tree"</li>
</ul>
</ul>
</body>
</html>
hr{
background-color: green;
height: 20px ;
width: 70%;
}
img{
margin-left: auto;
margin-right: auto;
display: block;
size: 400x300;
border: 1px green;
}
h1{
text-align: center;
}
#intro {
text-align: center;
}
body{
text-align: center;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.padding-left-none{
padding-left: 1em;
text-align: center;
}
ul{
list-style: none;
display: inline;
}
ol{
list-style: none;
display: inline;
}
.center{
padding-top: 0px;
}
hmm I am not quite sure what you need to do here. Which one is the example and which is your site and what exactly do you need to match? ๐
the padding between the ul and nested ul
ah you don't want additional space after "interest" for example?
try ul.center { margin-bottom: 0; }
no that won't work
try changing your padding-top to margin-top in .center i think that'll do it
hmmmm still doesn't seem to work
hmmm are we sure that's the correct HTML part and you need just to fiddle the css?
@native tide what I mean is ... is this for some assignment or you're teaching yourself to HTML/CSS etc? The current way the lists are set is not great for accessing them with CSS. For example ul li will be applied for both levels and will mangle anything. I think there is a better way to write these, but I am not sure if that's what you need. ๐
mainly doing this for practice to understand the concepts
but it kind of bugging me
is there anything you could suggest on how to rewrite this
@native tide sorry I am at work, so I am answering slower I will have a look now
No worries
@native tide I would suggest don't go into two lists really, not needed at all in this.
<ol>
<li>Interest</li>
<li>Bananas</li>
<li>climbing stuff</li>
</ol>
<ol>
<li>Jobs</li>
<li>giant ape</li>
<li>web developer</li>
</ol>
<ol>
<li>where i went to school</li>
<li>Diddy kong jr. High school</li>
<li>Donkey kong Sr. high school</li>
</ol>
<ol>
<li>favorite quotes</li>
<li>"at first you dont succeed climb a giant building"</li>
<li>"A Banana in hand is worth two on a tree"</li>
</ol>
Okay
I would also suggest to use
li:first-child {
color: red;
}
this will change only the first element in all <li> elements so it will be easy for you to manipulate these
Guys i've been doing a migration of Django 1 to 2 however when i try to run the project i'm getting this error below:
[INFO][2019-05-23 18:18:45,510][autoreload][29927][140178872248128]Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/xunjin/pyenv/python3cp/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/xunjin/pyenv/python3cp/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/xunjin/pyenv/python3cp/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
raise _exception[0](_exception[1]).with_traceback(_exception[2])
TypeError: __init__() missing 1 required positional argument: 'code'
does anyone have an idea what it might be?!
Hi excuse me Does anyone know how to integrate Django with Angular
sounds like google time
@late gale , do you need to integrate Django with Angular? you can treat them as two seperate projects
Ik but Django is so bad in templates so i want to integrate it with Angular
Django is so powerful in backend while angular is powerful in frontend
i want to mix them
but i cant understand from google
that's why i am asking here
do you know how @native tide
there's probably a way to integrate them into a one project, but, personally, I wouldn't do that
why so what're the cons
if you want tu use django as a backend and angular as a frontend - make your django a rest app
and consume it with angular
typically yes
i want to integrate them then i gonna continue on learning both and updating the web app
typically? I'll assume you are new at angular. My advice: go through a decent Angular tutorial where you will, no doubt, learn about consuming rest apis
after that, go to django
where, instead of html, (default), you will have to return dictionaries
thank you
np, but ask if you have more questions, even if you think the questions are stupid
it's just that I think, you'll have a lot of problem if you tackle both at the same time
for Angular, I'd really recommend tutorials from Maximilian Schwarzmรผller
note: I haven't done any tutorials from him, but I've heard a lot of good things about his tutorials from multiple sources
Both
I'd say it depends what you want from it
if the goal is to learn, use both
but if you want to have a blog? use django
if the two tools are the only options
thanks
but if the goal isn't learning, there are better tools than django
nope i am not learning i want to make a professional blog and very responsive
if you don't want to learn prrogramming, I'd suggest looking at existing services
hi everyone
i need help with flask
im on windows 10 (yes, i know)
and am using VS Code
im following Cory Schafer's tutorial
but unfortunately, he uses MacOS
this is my code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, world!"
the name of my file is flasktestapp.py
when i try to do set FLASK_APP=flasktestapp.py and then flask run, it doesn't work
what should i be doing?
somebody please help
somebody help please
anybody
SOMEBODY
ANYOBDOY
sigh
@winged island buddy, you have to be more patient. Everyone here is a volunteer. I invite you to ask your question in a help channel, that might get you a quicker response
hey harbar yeah the web scene here isn't as fast
by flask run I think you mean a command?
oh nm flask run is a console command
This may help you: http://flask.pocoo.org/docs/1.0/tutorial/factory/
@timid arrow sorry I didnt notice your response, for example put a breakpoint on a route form post and check the object that I'm receiving, change its values, etc.
Maybe its me not understanding how flask works, I usually debug my .py scripts by running it on debug mode (I'm using spyder ide if that helps), doing that with flask just wont run the app.
You can't debug flask apps with breakpoints
@winged island if still needed: to use flask run in a directory you need your main file to be in myapp/init.py and set the flask app to myapp.
@vagrant adder then what's the approach to debug stuff?
use print statement
A lot
And i mean, A LOT
Since you can't just make a breakpoint, you need a lot of info to know what's happening
that's a bit and by bit I mean a lot underwhelming
print or pprint will do the job
@north swift to add to saki's print statements ... sometimes it will crash and you will still be able to see the print statement but you should have to scroll through all of the crash dump, so make sure you're reading from the top down when checking for the print statement, if it's not there, it crashed before that, if it's there it will give you better idea where crashed. ๐
any idea why the override threed.js doesn't seem to be getting used?
i tried dropping it to root and root/js
@fast escarp I mean, sure, but its the first time I dont get to play with the request data before sending the response
@north swift sure, I didn't mean it in a bad way, just helps overall whatever you're building. And if you're doing the front with JS for example alert and console.log are your best friends really. ๐
my issue is that I need to start a process on a post request and personally I dont think printing everything is a good way to find errors
hmmm why is that? what do you think it will be better approach?
just allow us to stop on the request part and debug normally as other languages?
I'm used to java (spring dev) and I can literally go step by step on everything and modify data on the go if I need it
I know, that would be great really
I'm actually used to do it on python overall too
I do 90% of my python work on a temp file loading stuff as I need
Yeah, but not always the best approach in Python
never had to run debugger with flask, but I think you still can do it, why not.
it just wont start the app
I mean, here is tutorial on how to set it up in VS code
so it's definitely can be done
guess I'll try that later but I dont really want to move away from spyder
I doesn't' matter which IDE to use
it's all about running flask app with specific command line args
and that is it
hmmm I wonder if that will be a problem since I use flask-socketio
will give it a try when I get some spare time, now I sadly must attend this meeting
instead of print statements, use the logging module
I use the Django Debug Toolbar and it is super helpful
Also it does look like there is a flavor of the "Debug Toolbar" for Flask
I'm trying to serve my flask application using uwsgi, I did the tutorial and got it working but now trying to get my actual flask app and running into road blocks because I have it configured as a package instead of running from a single file (I think thats the right terminology), in the pocoo docs for uwsgi it says to run something like this:
$ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app
but this doesn't seem to be working, I'm not sure why it says to use a sock here but I made one anyway, it keeps saying that my package name doesn't exist, i have been running it like this, but have tried different configs as well and nothing recognizes correctly:
uwsgi -s /tmp/flask_audit.sock --manage-script-name --mount /app/py_sox=flask_audit:app
I'm not sure what i'm doing wrong but it feels to me like i'm not even on the right track because this is nothing like the tutorial I followed
My app's index.py lives in /app/myapp/flask_audit and the root dir for the whole app is /app/myapp
I've been running it in development with flask run on a specific port but need to move it to a web server now
Hello
waddup
I moved to django from php, i just used django template to display a table from database which has numbers in it, i want every column of that table to have sum total please anyone can guide. I searched all over but everything i find closes to that it can't be done in template i have to use filter or annote in views.py
Thanks
@rugged pecan please help me sir
I cannot help, I apologise
@everyone
hehe
Anyone please help
@native tide Could you show a snippet of your current views and template?
Since a sum wouldn't be in the database, you would have to calculate it first I'm views and then provide the data as an additional argument to your template while rendering.
This is very difficult i ha e tons of tables
I want to use like {{entries.amount.sum}}
Is there a way?
@still briar i solved it by using aggregate function but that is very time taking because i have like 1000 tables and this means i would be using aggregate 1000 times sepately in views
Usually if you want to pass that kind of data to your template, you would do it like ```py
sums = ...
return render(request, 'something.html', { 'sum': sums })
What does your view function in views.py look like?
Thanks to everyone i finally found a library
Django-tables2
@still briar I am talking about automation, thats what django is about, i create models and django automatically creates db, forms and tables now yay!
urlpatterns = [
path('admin/', admin.site.urls),
path('chat/', include('chat.urls'))
]
urlpatterns = [
url('<str:room_name>/', views.room, name='room'),
url('', views.index, name='index'),
]
hi guys I am just going thru the django channels tutorial but it is written in django 1. something and i am currently using django 2.2 and I ran into some issues while trying to write the equivalent syntax
so the first urlconf is for my mainproject direcotry and teh second one is for an app. When i type in the url chat/someroomname shouldnt the views.room function be called? When I type chat/someroomname the views.index is called instead and I am confused as to why
It looks correct to me. Try going to chat/someroomname/ with a slash at the end.
Normally, an include could look like this, where you fetch the list from your app.
urlpatterns = [
path('<page_slug>-<page_id>/', include([
path('history/', views.history),
path('edit/', views.edit),
path('discuss/', views.discuss),
path('permissions/', views.permissions),
])),
]
@zealous igloo
I do algorithm design in my day to day job (math degree, working in augmented reality), so I'm not much of a programmer.
Two years ago I took a short web dev course with Google App Engine using python and jinja, urllib2, webapp2.
Now I want to privately set up a small website from which users can make REST/RPC calls for crypto to an unrelated node. I want to stick to Google Web Engine and Python. The page itself will be minimal w.r.t. to storage required.
It should e.g. enable people to broadcast payments to the bitcoin network (web wallet).
The web engine is just to deploy that web page conventiently. It will have some light weigth interface
What's the options I can go for here? Is jinja serious enough for my demands?
I have some friends handling the network communication with Twisted/Klein. Is the suitable? But I also don't see people on the web using it. Does something like Flask do all things at once? What's other options.
@still briar sorry yeah i tried that thing and it doesnt work the views.index is caled rather than views.room when i do chat/someroomname/
Can you become a web developer without learning JavaScript
Not a great idea and you will learn it in industry anyways
I have not done js as my projects have never needed to be reponsive
You could become a backend developer and work with Python!
It's of course good to know javascript, but you don't have to be proficient. Nowadays it's all about frontend frameworks anyhow.
Hi all :)
I know Flask, HTML, CSS, Sass.
Anyone have any project ideas for me?
A search engine
Hi all
I have a problem implementing sitemap on my practice project
Am following the docs but apparently I'm missing something
Also there's something weird going on in urls.py
Here's the error that I've got:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute
self.check()
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check
for pattern in self.url_patterns:
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/vm/PycharmProjects/Example/venv/lib/python3.6/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/vm/PycharmProjects/Example/mysite/mysite/urls.py", line 25, in <module>
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
NameError: name 'sitemaps' is not defined
And the weird part in urls.py is that PyCharm highlights parts of code that seem to be totally fine.
can someone help me with this please?
hey guys
i really need help right now
so i created a website and bought a domain name on GoDaddy website
but i have no idea how to link my code to the website
i would really love to be helped right now
@frigid egret your not using that import anyway? and you have an s there is that supposed to be something else
Well yes except docs say that it has to be "sitemaps" specifically
If i try to change it to "sitemap" it doesn't render the page
can somone help me ?
@waxen cedar Which guides have you tried following?
@jade egret If you look at the docs, you'll see that I'm trying to do it exactly as in the example. And it seem to be simple enough.
can you post a link, so im looking at the same thing
can someoen help me ?
@waxen cedar be patient please
okay
The sitemap view takes an extra, required argument:ย {'sitemaps':ย sitemaps}.sitemapsย should be a dictionary that maps a short section label (e.g.,ย blogย orย news) to itsย Sitemapย class (e.g.,ย BlogSitemapย orย NewsSitemap). It may also map to anย instanceย of aย Sitemapย class (e.g.,ย BlogSitemap(some_var)).```
I'd say that would suggest you can put your PostSitemap there
Yes, and I did that, didn't I?
It may have something to do with my project structure. Because it says "unresolved reference sitemaps" when I hover over it
if you look further down you'll see examples.
@waxen cedar maybe try their website builder just to have the structure to look at, it seems you use ftp to add your webstuff
If I change path to "mysite.blog.sitemaps" there's no error but it fails to render the page
Yes, and I'm doing it just like in the example.
This is why I'm saying it might have something to do with the structure
oh god i dont have that much knowledge with web @jade egret
my website is online but idk how to add my script to it
Because I know it's not set up exactly the same way as suggested by docs, it's because of how PyCharm community edition handles django projects
have you changed it since? your sitemaps above is undefined, its not in the examples
how is it hosted atm? its running on gd?
i dont know any of those
i just know that i signed up on GoDaddy
and bought a domain
thats the link
i just dont know how to put that script inside of the page
what script?
@waxen cedar are you trying to host it directly from your machine?
You'll have to install a web server to do that. Like Apache for example
okay but idk how to use Apache
try googling apache web server setup
There's no simple answer to "how to use apache" I'm afraid. That's a complicated topic
okay
@jade egret can we go through it step by step cause I don't quite get what you mean
Ok but I don't want it to use static views only
I'd like it to generate the sitemap based on existing article pages.
This code given as initiation example should be working fine if I get it right:
from django.contrib.sitemaps.views import sitemap
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap')
Given that I've added sitemaps to my installed_apps
Am I getting it right?
Cause that seem to be the problematic part
try {"sitemaps": {"post": PostSitemap}}
path('sitemap.xml', sitemap, {"sitemaps": {"post": PostSiteMap}},
NameError: name 'PostSiteMap' is not defined
small m by bad
Oh right
Ok, it works. Thank you ๐
So it takes PostSitemap class and gets all items from it as separate entries, right?
havent a clue tbh, ive tried wrapping my head round django before and just couldnt do it, but yea it would seem to be making instances of that class as & when, not sure where that "post" label will come into play/be used
Hahah. Thank you anyway. It works now ๐
hey im back
i did apache and also ngrok
but how do i see my website now ?
nvm
i saw
it
just a weird freacking url
can I change it ?
Add an A record to your DNS (Domain Name System) zone file in the DNS manager of your account.
from here:
https://www.godaddy.com/community/Managing-Domains/DNS-newb-with-apache-server/m-p/120050#M23353
Yep, A record- Host: @ Points to: (the IP address) ย The host @ would be for your root domain (yourdomain.com), for a sub-domain type in what it should be (like 'Host: example'ย would make example.yourdomain.com). ย Apache would also need to be configured on what to do wit...
Hey guys im in need of a backend web dev for a site i want to make. Dm me for more info! ๐
i had the same question
and someone said learn flask if you are getting into web dev
But why
it is easier to understand and solve problems
Django site looks more professional than flasks
try googling it and see what fits your needs
it is not about what looks more professional
Which is better though
going through the django official tutorial and: ```py
Lookup by a primary key is the most common case, so Django provides a
shortcut for primary-key exact lookups.
The following is identical to Question.objects.get(id=1).
Question.objects.get(pk=1)```
How is this a shortcut?
In this case it isn't but if the model's PK field had a longer name then it would be
Hello all, I create my first project, and i have some trouble with Django.
I need create URL path, generated of more one Slug:
urls.py in applications
from django.urls import path
from . import views
urlpatterns = [
path('<category_slug>/<subcategory_slug>/', views.subcat_slug, name='subcategory'),
path('<category_slug>/', views.category, name='category'),
]```
But I get no URL's combinations I need
I need to have URL's <subcategory_slug> that are included with the composition available on the way <category_slug>, and it turns out that all subcategories are available with any combination of categories
models.py
class ProductCategory(models.Model):
category = models.CharField(unique=True, max_length=30, blank=None, null=False, default=None)
is_active = models.BooleanField(default=True)
slug = models.SlugField(unique=None, blank=None, default='')
class ProductSubCategory(models.Model):
subcategory = models.CharField(unique=True, max_length=30, blank=True, null=True, default=None)
category = models.ForeignKey(ProductCategory, max_length=30, blank=None, null=False, default=None, on_delete=models.PROTECT)
is_active = models.BooleanField(default=True)
slug = models.SlugField(unique=None, blank=None, default='')```
views.py
def category(request, category_slug):
category_slug = get_object_or_404(ProductCategory, slug=category_slug)
return render(request, 'products/category.html', locals())
def subcat_slug(request, subcategory_slug, category_slug):
subcats_slugs = get_object_or_404(ProductSubCategory, slug=subcategory_slug)
cats_slugs = get_object_or_404(ProductCategory, slug=category_slug)
return render(request, 'products/subcategory.html', locals())```
@pale fiber You forgot to check if the category is the subcategory's category.
It current fetches subcats_slugs and cats_slugs. Try checking subcats_slugs.category == cats_slugs
@still briar
Oh, thank you very much.
I check it before return function, and it all worked.
I am very grateful to you.
I make this. Thanks for your rectification, otherwise 500 error would come out, I did not know about it.
I think this need make all render function's?
Not sure what you mean.
There's a 404 error you can import and raise in your view function, in case you want to keep things consistent.
Hi all
I have a problem with PostgreSQL.
can't create a database because user fails authentication.
All threads on SO with similar problem are about already having both user and database. Which doesn't work for me because I only have a user.
postgres@ubuntu:/home/vm$ createdb -E utf8 -U blog
createdb: could not connect to database template1: FATAL: Peer authentication failed for user "blog"
did you create your user?
Yes, I have a user
also, try -u
I even created a second one just to be certain it worked
try -u instead of -U
yes
same result. "help" section also says it's high case -U
2.7.4
like that?
vm@ubuntu:~$ createdb -E utf8 -U blog blog
createdb: could not connect to database template1: FATAL: Peer authentication failed for user "blog"
Yea, tried
It results in a bunch of SO threads
And they are all about already having user and db. There are some fixes for that but I can't use them cause I don't have any db files to allow access to the user.
Like this one.
Also, somehow this is the only page I could find where someone has exactly the same problem. But it's really weird cause somehow it's on poker forums Oo
hmm
...and there's no answer there, ofcourse
try reinstalling postgres
reinstalling it
Same error =/
also I had to create user twice this time...
root@ubuntu:~# su postgres
postgres@ubuntu:/root$ createuser -dP blog
could not change directory to "/root": Permission denied
Enter password for new role:
Enter it again:
postgres@ubuntu:/root$ createuser -dP blog
could not change directory to "/root": Permission denied
Enter password for new role:
Enter it again:
createuser: creation of new role failed: ERROR: role "blog" already exists
postgres@ubuntu:/root$ createdb -E utf8 -U blog blog
could not change directory to "/root": Permission denied
createdb: could not connect to database template1: FATAL: Peer authentication failed for user "blog"
postgres@ubuntu:/root$
can someone help me with this please?
"could not change directory" is just a warning
the user was created only once
-U specifies the user to connect with, you likely wanted -O
see man createdb
what is everyone's opinion about deploying with azure?
Hi, I'm new to JS and web development in general, I wanted to make a textarea that expands as the user types with jquery, this is what I've come up so far js $("textarea").on("keydown", function () { $(this).css("height", "inherit"); const height = parseInt($(this).css("border-top-width"), 10) + parseInt($(this).css("padding-top"), 10) + $(this).scrollHeight + parseInt($(this).css("padding-bottom"), 10) + parseInt($(this).css("border-bottom-width"), 10); $(this).css("height", `${height}px`); });, but it straight up doesn't do anything, any suggestions?
Can you provide a jsfiddle, codepen, something similar?
mmh, sorry if this is a stupid question but what's jsfiddle and why would I need it?
It provides a minimal example and makes testing the JS easier
Cause you can put css, html, and js together on a page and then share a link with others
mmh
alright
https://jsfiddle.net/nq6g50z3/8/ I hope I didn't mess anything up, anyway, I would like the textarea inside the form to expand as the user inputs more text
so i am tyring to build a webapp that uses websockets and I was wondering about something
so i saw that i can use websockets on the client side with javascritp but at the same time, django also lets u use websockets with an extention called django channels. to create an app that uses websockets, would i have to use teh websocket API in javascript and django channels?
Does yarn have a feature wherein I can just store my node modules ( npm ) and fetch them if I'm offline -> the downloaded ones...
or it's built in npm ๐ there's a built in feature for that ?
so that I don't have to just to fetch modules from the internet, it's much faster
Maybe you can use the cache?
what is that ?
Well are you trying to use yarn or npm
Try this out
I believe you can set yarn's registry similar to how it's shown for npm here
uhm,, how do you know if modules was properly installed in the directory with yarn ?
error D:\www\docs\node_modules\node-sass: Command failed.
because i got that```
how do you know if I installed thiese node-modules properly via yarn
yo guys I get an Bad Gateway 502 error when trying to acces my website
I ran systemctl status nginx outpt is:
pi@web-server:~ $ systemctl status nginx.service
โ nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2019-05-28 17:53:15 CEST; 7min ago
Docs: man:nginx(8)
Process: 3556 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=1/FAILURE)
Process: 3484 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; -s reload (code=exited, status=0/SUCCESS)
Process: 3644 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Process: 3641 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Main PID: 3645 (nginx)
CGroup: /system.slice/nginx.service
โโ3645 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
โโ3646 nginx: worker process
โโ3647 nginx: worker process
โโ3648 nginx: worker process
โโ3649 nginx: worker process
May 28 17:53:15 web-server systemd[1]: Starting A high performance web server and a reverse proxy server...
May 28 17:53:15 web-server systemd[1]: Started A high performance web server and a reverse proxy server.
my configfile in /etc/nginx/sites-enabled is:
server {
listen 80;
server_name test-host.ddnss.de;
location /static {
alias /home/pi/html/static;
}
location / {
proxy_pass http://localhost:8000;
include /etc/nginx/proxy_params;
proxy_redirect off;
}
}
nah nvm I apologize myself for that one, was just one god damm typo
I'm using django and trying to use apache + mod_wsgi (following django's docs + corey schafer's deployment tut), but it's always a gateway timeout when accessing the page (accessing the static files are ok)
looking at apache logs, it mentions about Py_Initialize module not found: encoding, which yields some results on google but none have worked so far for me
does anyone have any personal advice on this matter?
Is there a way to catch Flask exiting with ctrl+c?
!ban @rapid magnet ping spam
:ok_hand: permanently banned @rapid magnet (ping spam).
Oh no
Raid? @mild bridge
seems like it
Anybody knows what IDE's can I use for jsp?
Vim or emacs
Atom for the win
I have hear of atom... I will try it... thanks
I am trying to install this build https://github.com/heroku/heroku-buildpack-chromedriver to heroku to use Selenium but I am getting this error Error: Could not publish 'heroku/chromedriver': 401, {"id":"unauthorized","error":"Unexpected error"}
you do heroku login in the console
i found out i need to do heroku create --buildpack https://github.com/heroku/heroku-buildpack-google-chrome.git but still wont work after i git push
wait it did work, well half worked.
these are the buildpacks but when i print out the logs it says i dont have the right chromedriver directory, this is the directory i put in /app/.chromedriver/bin/chromedriver
hm
made it work
@supple anvil
How
I thought I can't put buildpacks here so after like 15 tries i decided to try it and it worked
hey all weird issue with Django Debug Toolbar. The panels show, but the links don't work and the contents are printed below the page load. Any ideas?
Hey guys. I'm with a problem with django and rest framework.
I trying to make a relationship between users and group (default models in django) with rest framework.
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('url','username', 'email', 'groups')
class GroupSerializer(serializers.ModelSerializer):
users = serializers.SlugRelatedField(many=True, read_only=True, slug_field='users')
class Meta:
model = Group
fields = ('url','name', 'users')
but i'm getting a:
AttributeError at /api/groups/ 'Group' object has no attribute 'users'
Hey all, given I want to use filter to go over a reverse object relation, I know that if I want to explicitly filter on AND, I would put them in a single filter expression... example filter(a__b__c=1, a__b__d=2). I know if I want to do AS WELL AS, I could chain the filter. My question is about making custom managers. If I wanted to do something like MyObject.ranked().current_season().stats() Where ranked and current_season are filters, and stats is some type of annotation, is there any patterns for the first case to make a call to filter that works in the first example? In this case I would want ranked AND current_season stats instead of ranked AS WELL as current_season stats. I'm just trying to find the right way to nicely represent it in a manager. Sorry if this is confusing.
Is there a way I can reload a Flask page if an error occurs? an Internal Server Error
Because my web app is acting weird, sometimes I get a NameError and when i reload the page 1-3 times I dont get the error anymore and cant figure out why so..
Hi
Anyone know how to reduce django response time
Its around 0.15 ms for a simple html page without any css or ja
In php i am getting around 0.05 ms
Any clues?
That's python thing
does anyone here have experience with basic electron? i am having trouble figuring out how to turn my super basic django website to an electorn desktop app
How would I connect to a remote mysql db through an sshtunnel?
I'm trying with the following:
!codeblock tunnel = sshtunnel.SSHTunnelForwarder(
(host, 22), ssh_username=ssh_user, ssh_password=ssh_pw,
remote_bind_address=(localhost, 3306))
tunnel.start()
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{}:{}@{}:3306/{}'.format(db_user, db_pw, host, db)
but I'm getting the error:
OperationalError: (MySQLdb._exceptions.OperationalError) (1130, "Host 'my-ip' is not allowed to connect to this MySQL server")
(Background on this error at: http://sqlalche.me/e/e3q8)
!codeblock
Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.
To do this, use the following method:
```python
print("Hello world!")
```
This will result in the following:
print("Hello world!")
a couple lines before
Show me
Ok, so what, did you replace it with the "my-ip" string in the error message?
yep
Ok then
Why would I post my public ip :p
I just wanted to make sure that you hadn't copy-pasted an example and forgot to replace the IP with your real one
so thing is, this connection is allowed and working (I'm connected with mysql front with the same parameters)
I'm going to check right now just to make sure no one did revoke privileges and I'm wasting time
yeah It's totally working
And when you connect with MySQL front, you do it from the same IP?
Ok I think that's solved but its getting hardly stuck
I think it may be due to me trying to use the ORM mapping incorrectly typing... not sure
any async web devs here..?
having a real hard time finding the best way to debug async and await methods in my web application, doesn't seem like the good'ol PDB is working
Hi
Anyone know how to pass complex sql querys using django orm
Like distinct, inner join 4 to 5 tables
?
how to disable Flask errors from coming to my page just in console
or auto redirect to /
Anyone use hypothesis with django? What is the integration like these days? does it work ok?
Works great I justed go t hired to wirte a django application
@ancient zinc
what do you mean by auto redirect to /
hi guys
i am having trouble with flask-sqlalchemy
i am trying to update a PickleType column
try db.commit()
i have tried that, but still nothing. I will try one more time just to confirm it for you guys
thanks for the help !
also, is product your variable with data from db or is it a model table name
CurrentPrices = db.Column('CurrentPrices', db.PickleType, default={})
@vagrant adder
after you change your price, try adding it to db
so you can insert your new price into database too
actually no
sorry
wrong docs
@vagrant adder Thanks for helping !
does it work?
you mean db.session.add(CurrentProduct)
even though it has already been previousbly added
@vagrant adder
don't use commit(db)
i have a custom function
; )
lol
so it works everywhere else
but for soem reason i am not able to update this PickleType column
dude
try this
after you committed your data, try querying it again
commit(db)
then db.session.query() again
then print it