Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
How do I use/ access a foreign key in views in Django?

I am making a programing etymology site in Django. It will have the etymology/history of programing terms. or

For example the term LET (in ECMA6):
> Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic.

I am not clear on how to write views.

For instance, I want to return the term let and the text of the let terms. Let is in the Term table and text is in the Etymology table.

**EXAMPLE**

Here is what I would like to see returned for term_name=Let.

LET:

Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. Variables are considered low level entities not suitable for higher levels of abstraction, thus the desire of many language designers to introduce similar but more powerful concepts like in Clojure, F#, Scala, where let might mean a value, or a variable that can be assigned....



**MODELS**

Here are my models.

class Term(models.Model):
term_name=models.CharField(max_length=150)
term_type=models.CharField(max_length=150) #type of command
term_pub_date=models.DateTimeField('Term Pub Date')

def __str__(self):
return self.term_name

class Etymology(models.Model):
term = models.ForeignKey(Term, on_delete=models.CASCADE)
etymology_text=models.TextField()
classification=models.CharField(max_length=150) #prog or tool reference
etymology_votes = models.IntegerField(default=0)
# rating=
# user=
etymology_pub_date=models.DateTimeField('Ety date published')

def __str__(self):
return self.etymology_text[:50] + "..."


class Comment(models.Model):
etymology = models.ForeignKey(Etymology, on_delete=models.CASCADE)
comment_text= models.TextField()
comment_votes = models.IntegerField(default=0)
#rating=
#user=
comment_pub_date=models.DateTimeField('com pub date')

def __str__(self):
return self.comment_text[:50] + "..."

How do I write a view which accesses two tables at once. How would I write the view to return what I want to see from my models?

FYI:
Using Django 2.02 and Python 3.6. Also, I not highly experienced so simple


Citation:

JavaScript?, W. (2018). Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?.

/r/django
https://redd.it/8ad8pe
Django DRF + Djoser reset activation code

I have been successfully able to setup a Django app with Djoser token based authentication. I want to generate a activation code / url and make the user activate through that code / link for account activation or reset password.

The [Base Endpoints](https://djoser.readthedocs.io/en/latest/base_endpoints.html#user-resend-activation-e-mail) explains how to enable and utilize the activation using the endpoints. But how do I get to create the db models and generate activation code for the users? Am I missing something ?

/r/django
https://redd.it/evkr6d
KeyError: 'id' in django rest framework when trying to use updateorcreate() method



I am trying to update the OrderItem model using update_or_create() method. OrderItem model is related to the Order model with many to one relationship ie with a Foreignkey.

I am trying to query the orderitem object using id and update the related fields using default as you can see, but got this error.

My models:

class Order(models.Model):
user = models.ForeignKey(User, ondelete=models.CASCADE, blank=True)
ordered
date = models.DateTimeField(autonowadd=True)
ordered = models.BooleanField(default=False)
totalprice = models.CharField(maxlength=50,blank=True,null=True)
#billingdetails = models.OneToOneField('BillingDetails',ondelete=models.CASCADE,null=True,blank=True,relatedname="order")

def str(self):
return
self.user.email

class Meta:
verbose
nameplural = "Orders"
ordering = ('-id',)

class OrderItem(models.Model):
#user = models.ForeignKey(User,ondelete=models.CASCADE,

/r/django
https://redd.it/mfka4n
Setting up Django with uWSGI and nginx - I've been trying to figure this out for 5 days now. Please help...

I'm trying to set up nginx server with my django app and uWSGI, by following this tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html
I've been able to follow it up until the socket testing. The test itself doesn't produce an error, but localhost:8000 always returns 502 bad gateway error. I have been troubleshooting this for hours but can't figure out what I'm doing wrong.

/etc/nginx/nginx.conf:
```
#user http;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

events {
worker_connections 1024;
}

http {
include mime.types;
default_type application/octet-stream;
# load configs
include /etc/nginx/sites-enabled/*;
types_hash_max_size 4096;
server_names_hash_bucket_size 128;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;

location / {
root /home/<userprofile>/Projects/<project-name>/mymoon/journey/templates/journey/; # /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
```
/etc/nginx/sites-available/mymoon.conf
```
# mymoon_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
server unix:///home/Projects/<project-name>/mymoon/journey/journey.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
# the port your site will be served on
listen

/r/djangolearning
https://redd.it/sc7jt2
How to make a thread to make 100 concurrent request to db in Python ?

I want to simulate 120 people booking 120 seats all at once, how should I do that!!

This is what I am doing for the same

for i in range(120):
thread = Thread(target=book, args=(GetUser(i),)).start()
thread.join()

This is what my book function looks like:

def book(user): #user -> airline.User, seat -> airline.Seat
print(user1 + "with id " + str(user0) + " trying to book seat ")
seats = availableseats()
print("Total Available seats: " + str(seats[0]))

#selecting the seat at random
seat = random.randint(1, seats[0])
seat = GetSeat(seat)
print("Seat selected: " + str(seat[1]))
mycursor.execute("UPDATE seats SET USER
ID = " + str(user0) + " WHERE id = " + str(seat0))
mydb.commit()

But with this approach I am getting 2

/r/django
https://redd.it/ywqm7a
Runtime error: working outside of app context - confused by this

I've got the error above when I try execute a simple:
>User.query.all() #User is a model

This works fine on one device/environment. I can query in the app.py file, or from another file by importing app and User from app.py

I pushed to git, cloned the repo, and now I get this error when running the line above on a different device and environment. The app itself will run, but not the queries.

I'm confused as to why the same code would work on one env but not another, if it was dependency related wouldn't I be getting 'module not found' or something else, not this runtime error?

/r/flask
https://redd.it/z0wmuo
How to refresh a div without refreshing the whole page ?

I have a view that is used to block and unblock users. In my template all the users are listed inside a table. What I want to do is I want to refresh a specific portion of the div rather than the whole page while clicking block and unblock user. How to do that?

&#x200B;

views.py

&#x200B;

def block_user(request, id):

blocked_user = MyUser.objects.get(id=id)

blocked_user.is_active = False

blocked_user.save()

print("Blocked user is", blocked_user)

print("Is active status of blocked user is", blocked_user.is_active)

return redirect("usermanager")

&#x200B;

&#x200B;

def unblock_user(request, id):

user_to_unblock = MyUser.objects.get(id=id)

user_to_unblock.is_active = True

user_to_unblock.save()

print("Unblocked user is", user_to_unblock)

print("Is active status of blocked user is", user_to_unblock.is_active)

return redirect("usermanager")

&#x200B;

templates

<div class="page-title text-center mt-4 mb-3">

<h5>User List</h5>

</div>

<div class="page-subtitle ms-3 mt-5">

<p style="color: black;">All Users : {{no_of_filtered_users}}</p>

</div>

<div class="table-wrapper" id="user-table">

<table class="table ms-4 me-3">

<tr>

<th>#</th>

<th>Email ID</th>

<th>Customer Name</th>

<th>Mobile Number</th>

<th>Blocked Status</th>

<th>Actions</th>

</tr>

{% for item in users %} {% if not item.is_superuser %}

<tr>

<td>

<img src="{% static 'images/user.png'%}" style="height: 30px;" alt="head" />

</td>

<td>{{item.email}}</td>

<td>{{item.first_name}} {{item.last_name}}</td>

<td>{{item.mobile_number}}</td>

<td>

{% if item.is_active %} {{'Authorized'}} {% else %} {{'Blocked!'}} {% endif %}

</td>

<td>

{% if item.is_active %}

<button class="btn btn-sm btn-danger" onclick="blockUser();refreshDiv()" id="blockbtn" data-url="{% url 'blockuser' item.id %}">Block User</button>

{% else %}

<button class="btn btn-sm btn-success" onclick="unblockUser();refreshDiv()" id="unblockbtn" data-url="{% url 'unblockuser' item.id %}">Unblock User</button>

{% endif %}

</td>

</tr>

{% endif %} {% endfor %}

</table>

</div>

In scripts I have given a jquery function, but it does not seem to work. Please help me out.

&#x200B;

<script>

function refreshDiv(){
$('#user-table').load(location.href + "#user-table");

/r/django
https://redd.it/z9naoz
Cant register users using this view with REST (Invalid password format or unknown hashing algorithm)

@api_view(['POST'])
def register(request):
serializer=UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
#user=User.objects.create_user(username=request.data['username'])
#user.set_password(request.data['password']) #hash password
#user.save()
user=User.objects.get(username=request.data['username'])
token=Token.objects.create(user=user) #create token
return Reponse({"token":token.key, "user":serializer.data})
else:
return Response(serializer.errors)

Everything commented is something i tried before

imports:

from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

User serializer:

class UserSerializer(serializers.ModelSerializer):
class Meta(object):
model= User
fields = ['id','username','password','email']

&#x200B;

/r/djangolearning
https://redd.it/181xhg4
Send email with Flask

Hello everyone, does anyone know why I can only send emails to my email, which is where the app was created? When I try to send a message to another email, I don't get any error, but the email doesn't arrive. You can see the code in the pictures.

project.config'MAIL_SERVER' = 'smtp.gmail.com'
project.config'MAIL_PORT' = 465
project.config'MAIL_USERNAME' = 'my email'
project.config'MAIL_PASSWORD' = 'app password'
project.config'MAIL_USE_SSL' = True
project.config'MAIL_USE_TLS' = False

Or here:


def renderregistration():
message = ''
if flask.request.method == "POST":
email
form = flask.request.form"email"
numberform = flask.request.form["phonenumber"]
nameform = flask.request.form["name"]
surname
form = flask.request.form"surname"
mentorform = flask.request.form["mentor"]
#User.query.filterby(email =

/r/flask
https://redd.it/1kc4wv1
What could I have done better here?

Hi, I'm pretty new to Python, and actual scripting in general, and I just wanted to ask if I could have done anything better here. Any critiques?

import time
import colorama
from colorama import Fore, Style

color = 'WHITE'
colorvar2 = 'WHITE'

#Reset colors
print(Style.RESETALL)

#Get current directory (for debugging)
#print(os.getcwd())

#Startup message
print("Welcome to the ASCII art reader. Please set the path to your ASCII art below.")

#Bold text
print(Style.BRIGHT)

#User-defined file path
path = input(
Fore.BLUE + 'Please input the file path to your ASCII art: ')
color = input('Please input your desired color (default: white): ' + Style.RESET
ALL)

#If no ASCII art path specified
if not path:
print(Fore.RED +

/r/Python
https://redd.it/1p4ffmh