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 give path to a static image url from dictionary?

Lets suppose my dictionary has a key value as ‘pic’: ‘imagesTwo/pic1.jpg’

How to render images in a static img tag? Cause the dictionary value may change.

/r/django
https://redd.it/zzay90
DRF reset password

Best way to reset password with Django Rest Framework?

1 django-rest-passwordreset library

2 djoser library

3 django-rest-registration library

4 implement my own (if you have an advice/hint is appreciated)

/r/djangolearning
https://redd.it/zywskv
Saturday Daily Thread: Resource Request and Sharing! Daily Thread

Found a neat resource related to Python over the past week? Looking for a resource to explain a certain topic?

Use this thread to chat about and share Python resources!

/r/Python
https://redd.it/zzfo96
[DRF] What's you preferred way of serializing FK as an object when reading but using PK when writing?

The title says pretty much everything.

I want to know the most common (or most comfortable) way of serializing related object when performing **READ** operations but having to specify PK of the related object when **writing**.

Let's say I have two models **File** and **FileType**:

class File(..):
type = ForeignKey('FileType'...)

What I'm used to do is to add another field called **type\_detail:**

class FileSerializer(..):
type_detail = FileTypeSerializer(read_only=True, source='type')

That way I can **WRITE** like this:

{type:45...}

But when I **READ** I get:

{type_detail: {OBJECT}, type:45}

Do you do it differently? If yes, how?

I don't like that I have two fields. I'd like to use one for both operations.

/r/djangolearning
https://redd.it/zz7rj8
Django generate thumbnail with MoviePy, problem with Path

How to get the absolute path to a video, that works in development (Windows) and production (Ubuntu), ive tried almost everything, here is the closest I've gotten to a solution, I am trying to generate a thumbnail for a video when its posted.

from pathlib import Path
BASEDIR = Path(file).resolve().parent.parent
def generate
thumbnail(instance):
filename = Path.joinpath(BASEDIR, 'media/videofiles')
print(filename)
thumbnail = VideoFileClip(str(filename)+instance.video.url)
name = instance.video.url + '.png'
time = random.randrange(60)
thumbnail.saveframe('media/uploads/thumbnail' + name, t=time,withmask=True)
instance.thumbnail = name

It never gives me a good path, its ether with '/' or with \\ .

MoviePy error: the file C:\Users\User 1\Desktop\django\lumen\media\video
files/media/uploads/videofiles/22/29/Elvis-IfICanDreamOfficialLivePerformancefcw0WKp.mp4 could not be found! Please check that you entered the correct path.

/r/django
https://redd.it/zzk4ow
Search Vector Array of Chars

Hey guys I'm trying to create a search vector column for several fields including 2 Arrays of chars:

tags_list = ArrayField(
models.CharField(
max_length=255,
null=True,
blank=True,
),
default=list,
null=True,
blank=True,
)
related_tags_list = ArrayField(
models.CharField(
max_length=255,
null=True,


/r/django
https://redd.it/zz9jc3
Django admin actions for list entries

Django admin comes with custom actions for entries in a list. It works for both one value or multiple but is there any way we can add actions exclusively to an entry in the list ?

Something like the Record actions in the picture below?

https://preview.redd.it/miqivlj8o09a1.png?width=1177&format=png&auto=webp&s=71d1fb7d09f9be9af59af7bccf889961e35c9023

/r/django
https://redd.it/zyxuh4
Normal flask-redis works, but flask-caching w/redis ignores password

When I run this app, it works:

import redis

r = redis.Redis(password='no peeking')

r.mset({'test': 'TEST'})
x = r.get('test')

print(x)

But this one fails:

from flask import Flask
from flaskcaching import Cache

app = Flask(name)

cache = Cache(app, config={'CACHE
TYPE': 'redis', 'CACHEREDISPASSWORD': 'no peeking'})

cache.add('test', 'TEST')
x = cache.get('test')

print(x)

with the error "redis.exceptions.AuthenticationError: Authentication required."

Any ideas?

/r/flask
https://redd.it/zzheaa
Does anyone know how I can fix this? I haven't used docker in the last few months (3-4) and yesterday I updated my docker and now this is happening. Now I don't know if is this because of an update or something else.

https://redd.it/zzx5dr
@pythondaily
I want to know how I can create a invoice of data obtained from database (admin panel) and print it using custom django functions



/r/django
https://redd.it/zzx9xl
Django redirect doesn't work when trailing slash is there.

So I have a url pattern which looks like this

urlpatterns = [
path('register-user/', views.registerUser, name='registerUser'),
path('register-vendor/', views.registerVendor, name='registerVendor'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('dashboard/', views.dashboard, name='dashboard'),
path('vendor-dashboard/', views.vendorDashboard, name='vendorDashboard'),
path('my-account/', views.myAccount, name='myAccount'),
]

and views

def myAccount(request):
user = request.user
redirectUrl = detectUser(user)
return redirect(redirectUrl)

def dashboard(request):
return render(request, 'accounts/dashboard.html')

def vendorDashboard(request):
return render(request, 'accounts/vendor-dashboard.html')

the detect user function detects and user type and returns respective URL

def detectUser(user):
if user.role == 1:
redirectUrl = 'vendor-dashboard/'

elif user.role == 2: redirectUrl = 'dashboard/'

elif user.role == None and user.is_superadmin:
redirectUrl = 'admin'

return redirectUrl

but when I see the website the URL is

/r/django
https://redd.it/zzspi2
Help with identifying Users uniquely without Log in

Hello I have built a simple quote website for fun using Django Rest Framework and React js and I want to add a LIKE function to it but I want it to be without Logging in.
How can i achieve this with Django? How can i uniquely identify the Anonymous User without asking for Login In.

/r/django
https://redd.it/zzt3gu
export to excel(.xls)

i am using python xlwt module to convert my database query into an excel sheet.everything works fine,but now i want to adjust my date coloumn as below

def tonerdetails_export_toexcel(request,id):
toner_model = find_toner_model(id)
fmt = '%Y-%m-%d %H:%M:%S'
response =HttpResponse(content_type='application/ms-excel')
response['Content-Disposition']='attachment; filename=TonerReport ' + str(toner_model) + '.xls'
wb=xlwt.Workbook(encoding='utf=8')
ws=wb.add_sheet('Toner Report')
row_num=0
font_style=xlwt.XFStyle()
font_style.font.bold=True
date_format = xlwt.XFStyle()
date_format.num_format_str = 'yyyy/mm/dd'
columns=['Toner Model','Issued To','Employee Name','Employee Designation','Date Dispatched','Status']
for col_num in range (len(columns)):
ws.write(row_num,col_num,columns[col_num],font_style)
font_style = xlwt.XFStyle()
rows=TonerDetails.objects.filter(toner_model_id=id).values_list('toner_model_id__toner_model','issued_to_id__name','employee_name',


/r/django
https://redd.it/zzp8f4
Flask run fail after Python update

I updated my Python from version 3.9.2 to 3.11.1 on a Windows 10 machine. I reinstalled Flask and other modules I needed for the new Python version through pip and it seems that my apps work as normal when I use python -m flask run. However just flask run still looks for the old (and now uninstalled) Python 3.9 and of course fails as the system can't find the files. How can I fix this? I tried uninstalling it and reinstalling it with no success.

One think I have noticed, but I have no idea if this relevant or not, is that the old Python was installed under C:\\Program Files while the new one is only installed in AppData/Local even though I installed it for all Users. Plus I can't change the installation path in the setup program, even when running it as Administrator.

/r/flask
https://redd.it/1002wun
Operational error after changing the operating system

Dear Flask developers,

\-I built my flask app on WSL(Windows Subsystem for Linux) without a problem and it is working on WSL.

\-In order to test my app on a server environment I copied my app to an OpenBSD virtual machine on Hyper-V.

\-Ran my app on the local network.

\-I tried to connect from a different machine to the server(OpenBSD VM). Connected without a problem.

\-There is a login screen in my app and when I try to login as a user I got an operational error:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: Users
SQL: SELECT "Users".id AS "Users_id", "Users".email AS "Users_email", "Users".password AS "Users_password", "Users".option_1 AS "Users_option_1", "Users".option_2 AS "Users_option_2", "Users".option_3 AS "Users_option_3"
FROM "Users"
WHERE "Users".email = ?
LIMIT ? OFFSET ?
parameters: ('test_1@test.com', 1, 0)
(Background on this error at: https://sqlalche.me/e/14/e3q8)

​

Traceback (most recent call last)

File "/home/user/.local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1900, in executecontext
self.dialect.doexecute(
File "/home/user/.local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 736, in do
execute
cursor.execute(statement, parameters)

Could

/r/flask
https://redd.it/zzuv8x