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
Structuring a ForeignKey/M2M Query to build Context to send to Template

I have been stuck on this for a while... I am able to format the data the way I want in the view using loops and nested queries, but I can't quite figure out how to pass it to my template. I think I can build the data the way I want manually using a list of dictionaries, but I am assuming there's a better way to "chase" all the relationships to deliver everything in one data structure. I saw "through" mentioned, but could quite get it working.

​

Here's are my Models:

https://preview.redd.it/b6dv7ydc1hda1.png?width=1792&format=png&auto=webp&v=enabled&s=abb21dcaca96bfcba040ec9a593d6c40b87e0917

Here's my View which shows that I can print want I want to eventually show in the template, but how do I structure it in my view to send to HTML, since I can't run the nested query for registrations in my template.

https://preview.redd.it/1do12xua1hda1.png?width=1646&format=png&auto=webp&v=enabled&s=b36a38abc1973a95889fbc043f89ef7f3596a2ef

Any suggestions?

/r/django
https://redd.it/10i3fai
Uvicorn, Async DRF views and Thread count

I have recently started using ADRF to create a mini application. This application uses class based views and built on Django 4.1. The below is the code for my only view:
    class FooAPIView(AsyncGenericAPIView):
async def get(self, request, format=None):
await asyncio.sleep(1)
await Foo.objects.acount()
return Response(status=status.HTTP_200_OK)

I went on to check if this still uses Python threads, so I made hundreds of request (lets say X) using curl with curl `http://127.0.0.1:8000/api/v1/foo/` & curl `http://127.0.0.1:8000/api/v1/foo/` & curl `http://127.0.0.1:8000/api/v1/foo/`... . in that instance I noticed, the debugger showed me X number of ThreadPool executors.

Then I used both uvicorn to run asgi server and the runserver command to measure the threads using htop, I didn't really see a difference.

So how can I make sure the async API implementation has got the ability to service hundreds of connections without using Python threads?

What am I missing here?

/r/django
https://redd.it/10i3a4z
Need help running Django at a local machine after deploying it

I'm using Digital Ocean app platform to host my website but after following the settings from the end of [this documentation](https://docs.digitalocean.com/tutorials/app-deploy-django-app/) from the website (at the end of step 2), there's something I think I'm missing cause I have deployed the app following the guide but now I can't run it on my local machine.

The error comes from this snippet, throwing the Exception "DATABASE\_URL environment variable not defined"

elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic':
if os.getenv("DATABASE_URL", None) is None:
raise Exception("DATABASE_URL environment variable not defined")
DATABASES = {
"default": dj_database_url.parse(os.environ.get("DATABASE_URL")),
}

Any clue?

/r/django
https://redd.it/10i23de
Django based Micro-service oriented project

Hello everyone,

I have built a micro-service oriented Django project. It uses Django-Rest-Framework for building REST APIs and DRF_simplejwt for token authentication. Each service is dockerized and I used NGINX as an API Gateway to route API requests to different services.

Check out the project at https://github.com/Abhra303/pr-assign. If you like the project, drop a ⭐️. If you have any suggestions or opinion, feel free to share with me. Thanks :)

/r/django
https://redd.it/10hsi6b
Dealing with content pages

I’m still pretty new to Django. I’ve figured out how to use it for data (product catalogs, spec sheets, etc), but I’m not really sure how to best use it for a simple about page.

It seems kind of weird to make an app and singleton model specifically for a single page. What if there are a series of cards that I want displayed one day, then don’t need them the rest? Sure I can just remove them from the model, but I feel like I’m doing it wrong. I could also create a “pages app”, but because Django has no block builder I’m pretty relegated to WYSIWYG editors. So the pages all have to be very similar and pretty boring.

How do you guys approach stuff like this in Django?

/r/django
https://redd.it/10hbul5
ModelChoices with Select2 Widget - How to provide initial?

I've printed the widgets \_\_dict\_\_, so I can have a better overview

{
'model': None, 'queryset': None, 'search_fields':
['ticker__icontains', 'company__icontains'], 'max_results': 25, 'attrs': {}, 'choices': [], 'i18n_name': None, 'uuid': '43fe50ef-052a-4128-ba06-008a08c2bdfc', 'field_id': 'IjQzZmU1MGVmLTA1MmEtNDEyOC1iYTA2LTAwOGEwOGMyYmRmYyI:1pIvd4:u9IioxidlmRNmxYFIcP26crofoamfgZgXHhmD5U0hcQ',
'data_view': 'django_select2:auto-json', 'data_url': None, 'userGetValTextFuncName': 'null', 'is_required': False
}

Is there any possibilty of providing an initial value? The following is the \_\_init\_\_ of the form which currently uses TickerSearchWidget:

def __init__(self, *args, request, **kwargs):
self.request = request
super().__init__(*args, **kwargs)
print(self.fields["stocks"].widget.__dict__) # result above this block
self.fields["stocks"].widget.initial = self.initial.get("stocks")

# self.initial.get("stocks") refers a list of ids for a class Stock
# I've recognized that the widget utilizes the instance ids
# So self.initial.get("stocks") is f.ex. [123, 227, 821]

The Widget:

class TickerSearchWidget(ModelSelect2MultipleWidget):
search_fields

/r/django
https://redd.it/10h3o6o
B2B/SaaS applications: Seeking some advice on best practices

Seeking some advice/resources on building a user model in Django that reflects a B2B-style application. An example of successful implementation or conceptually-similar applications would be incredibly helpful.

I am building an application that is attempting to reflect B2B functionality - Users can have Membership on one (or more) Teams. Teams can be created by any User upon purchase of at least one product. A Team (more specifically a Team owner role) can purchase Services and associate them with the Team. A Team admin role can create roles custom to the Team and define permissions for those roles, and add one or more roles to a User’s Membership. Users who have Membership on multiple Teams (and who may have different roles/permissions on each of those Teams) can switch Team environments, which will deactivate the Team permissions assigned to the session and activate the permissions assigned to their Membership on the new Team. An authenticated User may have multiple Memberships, but they may only have one set of Membership permissions active at any point in time.

The biggest challenge I have is being able to assign groups/permissions to an object that is not User, but that is related to User, and being

/r/django
https://redd.it/10gxgyo
How to code a template so that section 1 automaticially links to discussion a in wagtail? I am using topic 1,2,3 for organization and navigation using page.get_parent and a drop down menu in the discussion pages. I want to make it so section 1 navigation always links to discussion a.

/r/django
https://redd.it/10h9f27
Authentication using phone number and social networks in Django

Hello,
I'm wondering if there's a way to implement authentication with phone number and social networks with tokens ?
If yes Can you please show some examples or articles to do it ?
Cheers

/r/django
https://redd.it/10gvsph
For loop not working

Hello guys. yesterday i wrote an application using for loop that worked exactly as I wanted it to work, but today when I opened it up without changing a thing it is not working. and this is happening every time I try to make something similar. i also tried inspecting the page but I only see an empty div while there is actually for loop inside it. any help would be appreciated. thanks

https://preview.redd.it/b7whn4cugeda1.png?width=276&format=png&auto=webp&v=enabled&s=ef2ba520d250c5311e1f09004b097d36d2fca8bd

https://preview.redd.it/dly4y7cugeda1.png?width=813&format=png&auto=webp&v=enabled&s=37272ffb649dbfc385bbec608581a5d4d792af8d

/r/djangolearning
https://redd.it/10hrgt9
Need help adding a simple calendar visual

I have written a simple blog app in django that works well and I enjoy using it. Each post has a title and a date of when posted and a rating for content complexity (high med low).

I want to create a sort of mini calendar view that shows a month's calendar grid with each day cell colored according to the complexity of the post something like (red yellow green).

I can't find any easy way to draw the calendar grid on the homepage of the site and fill in the cell (day's) color. Does anyone have any examples for something similar? Maybe someone made a fitness app that has a simple view only calendar showing "cheat days" colored in green or something?

All the examples I find online are fairly complex and I don't want to add all that to my code to create like a full feature scheduling or event calendar with user entry on the calendar itself. I just want it to visualize the month's comments complexity at a glance a month at a time and be readonly.

Thanks!

/r/djangolearning
https://redd.it/10huxdu
Django-filter; creating a variable which I can set from my view function

I have a filter which can be used to filter the products on brand(s), which looks like this:

class SortFilter(django_filters.FilterSet):
ORDER_BY_CHOICES = (
('-discount_sort', 'Hoogste korting'),
('-new_price', 'Hoogste prijs'),
('new_price', 'Laagste prijs'),
)


order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES,
method='filter_by_order',
empty_label=None)
brand = django_filters.ModelMultipleChoiceFilter(queryset=Product.objects
.order_by('brand')
.filter(categorie='eiwitten')
.values_list('brand', flat=True).distinct()
, widget=forms.CheckboxSelectMultiple)
q = django_filters.CharFilter(method='multiple_field_search', widget=TextInput(attrs=
{'placeholder': 'Zoek..'}))


class Meta:
model = Product
fields = ['brand', 'q']


def filter_by_order(self, queryset, name, value):
return queryset.order_by(value)


def multiple_field_search(self, queryset, name, value):
return queryset.filter(
Q(title__icontains=value) | Q(categorie__icontains=value) |
Q(brand__icontains=value)
)

def eiwit(request):
#print(request.GET.getlist('brand'))
# filter alleen eiwitproducten
eiwit_list = ['eiwitten']
eiwit_filter = Q()
for item in eiwit_list:
eiwit_filter = eiwit_filter | Q(categorie=item)


brand_list = request.GET.getlist('brand')
brand_filter = Q()
for b in brand_list:
brand_filter = brand_filter | Q(brand=b)


products = models.Product.objects.filter(eiwit_filter).filter(brand_filter)
product_amount = len(products)


# sorteer filter
filtered = SortFilter(
request.GET,
queryset=products
)


# paginator
paginator = Paginator(filtered.qs, 12)
page = request.GET.get('page')


/r/djangolearning
https://redd.it/10hov5o
delete or hide?

i was thinking on implementing a boolean field in my models to set the record as hide whenever someone click delete,instead of entirely deleting a record.i beleive this would be a safest way to recover a record whenever a mistake happens.whats your opinion?

/r/djangolearning
https://redd.it/10ht1vu
I can’t open a web browser after running the server. Is an internet router a common culprit? Is port forwarding commonly needed by web developers?

The problem is solved . This is a Coursera Class Lab issue . The Django class environment doesn’t work for me. I have to do the exercises with VScode installed on my computer . Thanks!

/r/djangolearning
https://redd.it/10hqscy
Flatliner: turn python programs into one line of (still python) code

Ever wanted to turn your python program into a single line of code? No? Well now you can!

Introducing Flatliner, a python transpiler that turns python programs into a single line of code.

# What does it do?

Put simply, it can turn python programs like:

def func(a: int, b: int) -> str:
result = a + b
return f'{a} + {b} equals {result}'

print(func(5, 6))

Into a single line of (still python) code, without using any "cheats" like semicolons and string execution:

(lambda func: print(func(5, 6)))(lambda a, b: (lambda result: f'{a} + {b} equals {result}')((a + b)))

Running this line of code produces the same results as the original program:

>>> (lambda func: print(func(5, 6)))(lambda a, b: (lambda result: f'{a} + {b} equals {result}')((a + b)))
5 + 6 equals 11

# Demo!

https://reddit.com/link/10ijoep/video/a9qe9jwkhlda1/player

Demo code credits to a previous post. Link to demo if you want to try it yourself: here

# How does it work?

Very briefly, it first parses the input code into an AST, then it converts the last node into a

/r/Python
https://redd.it/10ijoep
Interfaces with Protocols: why not ditch ABC for good?

Hello, if one finds interfaces useful in Python (>=3.8) and is convinced that static type-checking is a must, then why not ditch ABC and always use Protocols? I understand that the fundamental idea of a protocol is slightly different from an interface, but in practice, I had great success replacing abc's with Protocols without regrets.

With abc you would write (https://docs.python.org/3/library/abc.html) :

from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def eat(self, food) -> float:
pass

Whereas with Protocols it's gonna be (good tutorial):

from typing import Protocol

class Animal(Protocol):
def eat(self, food) -> float:
...

Scores in my subjective scoring system :)

|Capability|ABC|Protocols|
|:-|:-|:-|
|Runtime checking|1|1 (with a decorator)|
|Static checking with mypy|1|1|
|Explicit interface (class Dog(Animal):)|1|1|
|Implicit interface with duck-typing (class Dog:)|0.5 (kind of with register, but it doesn't work with mypy yet)|1|
|Default method implementation (def f(self): return 5)|\-1 (implementations shouldn't be in the interfaces)|\-1 (same, and mypy doesn't

/r/Python
https://redd.it/10ikape
Differentiating what Python skills a data scientist would need vs. a developer/engineer

Hello all!

I’m currently working on my MS in Data Science and I’m learning a ton of Python. I’m comfortable with my understanding of the material we’ve learned so far, so I’m looking to work ahead and just make sure I have an excellent foundation.

I’m having a hard time trying to figure out what’s actually valuable to learn for someone trying to work in DS in the future. I don’t want to spend my time learning things that would be most useful for a Software Engineer or Developer when I could ensure my DS toolkit is very well equipped.

I know visualization, data cleaning and statistics are areas that are key to being a good DS, but I know they’re part of my masters curriculum. However, I’m not sure something like Data Structures and Algorithms would be a part of it. Would something like that be valuable to invest some time into? Any insight into other valuable topics would be awesome!

/r/Python
https://redd.it/10i2351
My first real useful python project. A rofi extension to help manage my latex notes/assignments

​

https://reddit.com/link/10ihl7r/video/luaxwa26ykda1/player

Here's the link. I need to update the README. But, I write all my notes and assignments in latex. I got this inspiration from here. So, I decided to rewrite everything using my own way of structuring things. Here are the features that it provides right now:

1. A nice way of opening/viewing notes/assignments.
2. A way of syncing my notes to the cloud.
3. A nice way of initializing all of my courses.
4. A nice way of seeing what class/lab I have next.

Here are some future ideas that I have in mind:

1. A way of creating notes/assignments via rofi. I also want to use the notion API since I use that as well.
2. When I initialize the courses, I want all those courses to be created on notion as well.

Could anyone provide any feedback on how I can improve this program? I'm currently working on adding more documentation to the code and updating the README with some nice videos/images. Other than that, is there anything that I can do to make the code run faster, or write stuff more efficiently?

Thanks!

/r/Python
https://redd.it/10ihl7r