/r/django

Photograph via snooOG

News and links for Django developers.

News and links for Django developers.

New to Django? Check out the /r/djangolearning subreddit.

Django's Code of Conduct applies here, so be good to each other.

/r/django

126,855 Subscribers

1

User friendly django admin template

Hello folks Can someone suggest me a good template for replace django admin user interface Thank u

2 Comments
2024/04/14
04:10 UTC

5

Relearning Django..

Is there any good youtube channels or any other resources that will teach django from the scratch with a straight to the point approach? I kinda lost touch because its been a while since i worked on it consistently. I want to start from the very basics but wants to follow a tutorial with a fresh,efficient approach.

6 Comments
2024/04/14
02:09 UTC

5

HackerRank - Django Environment

I have an assessment in hackerrank platform for a backend developer role. There are two sections a 1. Backend question 2. Coding question

I'm very much familiar with the coding environment of hackerrank, but with the backend section i can see requirements saying it has Django 3 and DRF with an option to choose online IDE or offline with git. I'm not sure what to expect in this section.

I'm currently working as Django developer but I'm confused on how to prepare for the backend section. What kind of questions would be there, how to debug, how the code/api will be checked, the test cases. I'm a bit worried since there's only 1hr in total.

Any help would be much appreciated

10 Comments
2024/04/13
15:53 UTC

0

TinyMCE

Hello guys did somebody have implemented tinyMCE editor into admin panel?

2 Comments
2024/04/13
15:43 UTC

2

Feedback on API Design Strategy for a Django DRF Project with Dynamic User Roles and Customizable Endpoints

Hello everyone, I'm in the planning stages of a bigger project using Django REST Framework and am looking to have a flexible API architecture that serves specifically to the needs of different screens in the frontend while also having different user roles. User Roles see different fields on the screens and can also edit different fields or some can’t even see a screen.

  1. Endpoint Strategy:

I'm considering creating a dedicated API endpoint for each frontend screen. This approach aims to streamline frontend development by providing exactly the data each screen needs without additional overhead on the frontend side. The good thing would be that every Call would just send the needed data to the frontend and the user, not more data than needed. The Frontend would send a post request to this Endpoint as well and I could by role then figure out, which field is allowed to be overwritten by the users role.

  1. Dynamic Field Visibility Based on User Roles:

To handle varying access levels, I'm thinking about a model where each field in the database has a many-to-many relationship with user roles, determining field visibility. The idea is to dynamically adjust the API's response based on the user's role, directly from the database configuration.

  1. Frontend-Driven API Customization:

Another aspect I'm thinking of allowing frontend engineers to modify certain API structures dynamically (like adding fields or adjusting visibility through an API). This would involve creating a meta-model to represent all models and their fields. The frontend could potentially modify these settings to tailor the API responses to their current needs.

The models would look somehow like this:

Role:

name

Screen:

name,
access_roles (ManyToMany to Role)

ScreenField:

screen (ForgeinKey to Screen),
field (ForgeinKey to Field),
Access_roles_view (ManyToMany to Role),
Access_roles_edit (ManyToMany to Role)

Model:

name

Field:

key,
model (ForkeinKey to Model)

The Response would be filled with the ScreenFields of the requested screen.

In the past I always went to model way and used viewsets for the most part, but for special functions, like triggering something and so on.

In my mind the approach I describe here seems pretty flexible and safe. Im just a little worried because it has more database calls I think.

Would love to hear your insights or any alternative recommendations for managing such a system. I'm curious about the community's view on the maintainability and efficiency of this approach. How would you approach these challenges? Do you have concerns here?

If you have questions, of course ask me :)

Thank you!

0 Comments
2024/04/13
15:29 UTC

4

How to create a superuser on PAAS without using "createsuperuser" command ?

Hello. I am trying to use django in a PAAS environment 'clevercloud', which means I am using a python runtime & a managed MYSQL database. The support of CleverCloud told me they can't run "createsuperuser". I wonder if there is a workaround for that ?

8 Comments
2024/04/13
13:43 UTC

3

Circular Imports / Nesting Serializers

I have a project with a few apps and many modules in each app.

I refer to models with foreign keys and specify the related model as a string or ‘app.model’, this is great, no imports and it is clean.

There is often a situation or two where I need to nest a serializer from another module in a serializer and vise versa but I get circular imports.. as I can’t seem to refer to the nested serializer as a string like I can with model relationships, so the suggestions have been:

lazily import the serializer from the other module within the serializer then nest it, hyperlink to the other, or make a relationships module for handling inter-modular relationships.

I don’t like any of this but I have the relationships module the least..

Any suggestions? I am looking to keep things clean and consistent.

4 Comments
2024/04/13
11:27 UTC

1

Form with manually rendered inline formsets won't save

I have a weird [to me] Django issue with a form and associated inlineformset.

On on the template, rendering formsets in the manner below works

{{ dealer_part_formset.management_form }}

{% for form in dealer_part_formset %}

{{ form.as_p }}

{% endfor %}

However, I need to render the forms manually in a <table>. Rendering in this manner does not save the form and in fact, it does not even redirect.

{{ dealer_part_formset.management_form }}
{% for form in dealer_part_formset %}
<tr>
<td>{{form.item }}</td>
<td>{{form.qty }}</td>
<td>{{form.unit_price }}</td>
<td>{{form.discount_percent }}</td>
<td>{{form.discount_amount }}</td>
<td>{{form.amount }}</td>
<td>{{form.DELETE}} Del</td>
</tr>
{% endfor %}
The views, forms and models are already set-up properly and are everything is working excellent when the formset is rendered as_p, as_div, as_table, or as_ul.

What could be missing from my template? Thanks in advance.

0 Comments
2024/04/13
06:13 UTC

10

Job queue in django

Hello everyone. First off I'd start and say I'm a newbie in django, it's my first project (I'm been programming with Python for about a year)

I'm working on a website which offers PDF convertion (done via c# dll).

I'd like to have some sort of queue for convertion jobs, as its a fairly (computing wise) heavy task and I cant have 100 jobs running at the same time, so I want to make a queue system which will wait for it's turn and then run the function which submits and return the results to the client.

I don't want to submit the job for later processing and move on, I want to wait for the job to run, then return the results to the client.

I know celery can run jobs in a queue but I'm not sure if it's the right tool for this kind of task queue as from what I gathered (and I can be completely wrong on this, feel free to correct me) it's not meant to submit and wait for results, but rather to submit for later processing.

Any help will be appricated!

23 Comments
2024/04/13
05:25 UTC

2

Filter deep nested related_set in Django

There are two models:

class Subject(Model):
    categories = ManyToManyField(Category, related_name='subjects')

class Category(Model):
    parent = ForeignKey('self', related_name='subcategories')

This supposed to be translated into the following rest output:

[
    {
        ...,
        "categories": [
            {"subcategories": [{}, {} ... {}]},
            {"subcategories": [{}, {} ... {}]}
        ],
    },
    {
        ...,
        "categories": [
            {"subcategories": [{}, {} ... {}]},
            {"subcategories": [{}, {} ... {}]}
        ],
    }
]

The problem is to have set of subcategories for each category, subcategories that are in many to many relation with ancestor subject.

So far I think that queryset should be something like:

Subject.objects.prefetch_related(
    Prefetch(
        lookup="categories",
        queryset=Category.objects.filter(parent__isnull=True)
        .prefetch_related(
            Prefetch(
                lookup="subcategories",
                queryset=Subquery(
                    Category.objects.filter(
                        parent__pk=OuterRef("pk"),
                        subjects__id__in=OuterRef(OuterRef("pk")),
                    )
                )
            )
        )
        .distinct(),
    ),
)

But this gives the error:

AttributeError: 'Subquery' object has no attribute '_chain'

What is wrong with the queryset. What would be the correct way of doing that?

0 Comments
2024/04/13
04:41 UTC

1

Database access for specific routes

Hi all,

I just wondered what is the best way if i have a Django app that is handling a small amount of SQLite data. I have to mention that I was transferring a flask prototype which was using sqlalchemy which I didn't want to change so far. Most of my routes are using the same data. Accessing the database each time for the routes seems to be unnecessary. But putting the access in some kind of middleware seems even more unnecessary as this will access even for the routes which do not need the data at all. What is the correct machanism for that if I really use django ORM? Maybe this question seems stupid, but I'm new to django... Thanks in advance

1 Comment
2024/04/13
03:02 UTC

0

Django App GRPC has stopped working - "debug_error_string =grpc_message: "failed to connect to all addresses; ipv4:127.0.0.1:10009: Connection refused", grpc_status:14"

Strange one, wondering if anyone has some ideas that can help.

Running Django (version 4.2.11) GRPC to a Raspi Pi on my internal network.

Using - https://github.com/googleapis/googleapis.git

I have a phone with an app that can connect to the Raspi no problems from outside the network.

When I take my grpc code from views.py on my app (which is on my PC locally) and use it to create a py file on the Raspi itself, it works fine.

However if i copy back that test py file from the Raspi to my PC and run it from Django cli "python test.py" i get the "failed to connect to all addresses" error.

I've tried this on my LAN as well as from outside my LAN.

This is the code i run (which there obviously isnt an issue but posting for context):

import grpc

import os

import Raspiobject_pb2 as myChannel

import Raspiobject_pb2_grpc as myChannelrpc

import codecs

with open(os.path.expanduser(os.getcwd() + '/admin.macaroon'), 'rb') as f:

macaroon_bytes = f.read()

macaroon = codecs.encode(macaroon_bytes, 'hex')

#embeds encrytpted cert and creds (combined_cert) into stubbed channel, rather than having to pass macaroon each time

def metadata_callback(context, callback):

callback([('macaroon', macaroon)], None)

# build ssl credentials using the cert the same as before

cert = open(os.path.expanduser(os.getcwd() ).read()

cert_creds = grpc.ssl_channel_credentials(cert)

auth_creds = grpc.metadata_call_credentials(metadata_callback)

# combine the cert credentials and the macaroon auth credentials

# such that every call is properly encrypted and authenticated

combined_creds = grpc.composite_channel_credentials(cert_creds, auth_creds)

# Now I can pass in the combined credentials when creating a channel - see below

channel = grpc.secure_channel('localhost:10009', combined_creds)

stub = myChannelrpc.stubmethod(channel)

request = myChannel.method1(value=100)

response = stub.method2(drequest)

print("Output: ", response.payment_request)

Any ideas would be appreciated. My only other alternative at this point would be to build the same app in Flask or some other platform to see if that work?

Many thanks in advance.

0 Comments
2024/04/12
22:15 UTC

3

Project structure help

Im building an app similar to Backloggd or Letterboxd for a Uni project and I'm trying to decide what the architecture should look like.

My app will heavily rely on the IGDB API, since most of the data from the website will come from there. My partner in this project is learning frontend using React so my plan was to use DRF for backend and React for frontend. Here's my concern, the API that I will develop will depend on IGDB, that will mean that responses from my own API will take a longer time to respond, adding more wait time for the frontend.

Should I discard the idea and just use django for frontend or is there a better solution for this problem (request caching or smt)? We plan to add this project to our portfolios so we don't want to do anything that might be considered "bad".

3 Comments
2024/04/12
21:23 UTC

1

Is it possible to create a plugin system in Django

I've read about how django can't recognize apps which have been loaded when the server is already started. Is it possible to create a system in django where we can install and uninstall apps without restarting the server?

2 Comments
2024/04/12
20:33 UTC

1

extends and block content tag

I add {% extends x %} and {% block content %}tag page become messing

1 Comment
2024/04/12
17:47 UTC

0

ValueError at /accounts/signup/ Cannot query "echiye@gmail.com": Must be "User" instance

*Am using django-allauth for aunthentication and below is my custom user models. The password are not safe to the database because it will report incorrect password but the user will be created along with other necceasiry informations on the database entered during registrations are correctly saved rightly. password created using the createsuperuser is stored correctly too.*

Kindly help me out with the \ValueError at /accounts/signup/ Cannot query ["echiye@gmail.com](mailto:"echiye@gmail.com)": Must be "User" instance.``

class MyUserManager(UserManager):

"""

Custom User Model manager.

It overrides default User Model manager's create_user() and create_superuser,

which requires username field.

"""

def _create_user(self, email, password, username, first_name, phone_number, country, last_name, is_staff, is_superuser, wallet_address=None, private_key=None, **extra_fields):

if not email:

raise ValueError('Users must have an email address')

now = timezone.now()

email = self.normalize_email(email)

user = self.model(

email=email,

first_name=first_name,

last_name=last_name,

username=username,

is_staff=is_staff,

is_active=True,

last_login=now,

date_joined=now,

phone_number=phone_number,

country=country,

**extra_fields

)

user.set_password(password)

user.save(using=self._db)

return user

def create_user(self, email, password, **extra_fields):

return self._create_user(email, password, False, False, **extra_fields)

'''

def create_superuser(self, email, password, **kwargs):

kwargs.setdefault('is_staff', True)

kwargs.setdefault('is_superuser', True)

return self._create_user(email, password, True, True, **kwargs)

def create_superuser(self, email, password, **kwargs):

user = self.model(email=email, is_staff=True, is_superuser=True, **kwargs)

user.set_password(password)

user.save(using=self._db)

return user

'''

def create_superuser(self, email, password, **kwargs):

kwargs.setdefault('is_staff', True)

kwargs.setdefault('is_superuser', True)

user = self._create_user(email, password, True, True, **kwargs)

user.save(using=self._db)

return user

class User(AbstractBaseUser, PermissionsMixin):

email = models.EmailField(_('email address'), blank=False, unique=True)

first_name = models.CharField(_('first name'), max_length=40, blank=False, null=False, unique=False)

last_name = models.CharField(_('last name'), max_length=40, blank=False, null=True, unique=False)

username = models.CharField(_('user name'), max_length=40, blank=True, null=True, unique=False)

display_name = models.CharField(_('display name'), max_length=14, blank=True, null=True, unique=False)

is_staff = models.BooleanField(_('staff status'), default=False,

help_text=_('Designates whether the user can log into this admin site.'))

is_active = models.BooleanField(_('active'), default=True,

help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.'))

last_login = models.DateTimeField(null=True, blank=True)

date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

phone_number = models.CharField(max_length=11, blank=True, null=True)

groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True, related_name='user_related_groups')

user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True, related_name='user_related_permissions')

objects = MyUserManager()

USERNAME_FIELD = 'email'

REQUIRED_FIELDS = []

class Meta:

verbose_name = _('user')

verbose_name_plural = _('users')

db_table = 'accounts_user' # Specify a custom table name to avoid conflicts

abstract = False

def save(self, *args, **kwargs):

super().save(*args, **kwargs)

i got this error \ValueError at /accounts/signup/ Cannot query ["eaaa@gmail.com](mailto:"eaaa@gmail.com)": Must be "User"` instance.``

0 Comments
2024/04/12
16:52 UTC

5

Hey i deployed my first website

It is a clone of hackernews, Built in 3 days.

https://soni1.pythonanywhere.com/

How can I implement a upvote functionality where i can check that if a user has already upvoted, then he cant upvote or i make the upvote button disapper for him/her, here is my model.py file

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=255,blank=True)
    link = models.URLField(max_length=200)
    author = models.CharField(max_length=100)
    upvotes = models.PositiveBigIntegerField(default=0)
    time_added = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-upvotes','time_added']
        
    def __str__(self):
        return self.title
    
class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments',null=True)
    text = models.TextField()
    author = models.CharField(max_length=100)
    time_added = models.DateTimeField(auto_now_add=True)
    upvotes = models.PositiveBigIntegerField(blank=True,null=True)

    def __str__(self):
        return f"Comment by {self.author} on {self.post.title}"
    
    class Meta:
        ordering = ['-upvotes']
6 Comments
2024/04/12
15:59 UTC

0

Static files not load properly

Hi Need some help. Static files are not being rendered properly in my django project.

Server log

"GET /static/admin/css/responsive.css HTTP/1.1" 404

setting.py

STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
STATIC_ROOT = BASE_DIR / 'assets'

The static is in the root folder of the project. Any help will be appreciated.

7 Comments
2024/04/12
15:52 UTC

4

How to write test cases for the signin with google API.

Hello, Currently an API endpoint is created with the DRF framework and it accepts the access token from the front-end and then validate and other process happens.

But to test the API how to write testcases for this endpoint?

3 Comments
2024/04/12
11:54 UTC

0

why i am getting this error : raise ValueError("No handler for message type %s" % message["type"]) ValueError: No handler for message type websocket.connect WebSocket DISCONNECT /ws/ac/ [127.0.0.1:54780]

here is my code

from channels.consumer import SyncConsumer,AsyncConsumer,StopConsumer
class MySyncConsumer(SyncConsumer):
def websocket_connect(self,event):
print("Connected...",event)
self.send({
"type":"websocket.accept"
})
def websocket_receive(self,event):
print("received message",event)
# self.send({
#     "type":"text",
# })
def websocket_disconnect(self,event):
print("Disconnected",event)
class MyAsyncConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("Connected...", event)
await self.send({
"type": "websocket.accept"
})

async def websocket_receive(self, event):
print("received message", event)
async def websocket_disconnect(self, event):
print("Disconnected", event)
# raise StopConsumer()

1 Comment
2024/04/12
11:13 UTC

18

Hosting

So I know how to make an API in django and have hosted stuff on pythonanywhere successfully. However I am still not confident I can handle hosting when working on client projects (espcially since most stuff is paid so I can't just play arond and find out what to do). Where do I go to learn that specific part? (I like to use docker if possible and I like MySQL/Postgres as the DB engine)

Thanks in advance

26 Comments
2024/04/12
10:48 UTC

5

Are there many options when it comes to, autentication app....

Are there many options when we consider well maintained, multiple frontend serving, fast loading, secure, well documented, django authentication app for DRF backend ? What's your suggestion ? Its a small scale project, but expecting to serve 5000 users in a few months and scale up from there, it's an OS project, so I want to implement a robust system but something which have some scalability, wouldn't want to reimplement in a short period of time.

Thinking about simple-JWT now, fishing for recomendations here, thank you.

2 Comments
2024/04/12
03:20 UTC

1

Would like a bit of help for websockets (django channels)

Hello,

I have tried to use websockets for my django app, and its been a pain to be honest. When I open a chatroom the terminal keepts going like this:
[11/Apr/2024 20:26:57] "GET /ws/chat/110/ HTTP/1.1" 404 7450

Not Found: /ws/chat/110/

Not Found: /ws/chat/110/

Here is my routing.py file:
from django.urls import path

from . import consumers

websocket_urlpatterns = [

path('ws/chat/<str:room_id>/', consumers.ChatConsumer.as_asgi()),

]

Here is my asgi.py file:
from django.core.asgi import get_asgi_application

from channels.auth import AuthMiddlewareStack

from channels.routing import ProtocolTypeRouter, URLRouter

import chore_app.routing

import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'chore_pro.settings')

application = ProtocolTypeRouter({

"http": get_asgi_application(),

"websocket": AuthMiddlewareStack(

URLRouter(

chore_app.routing.websocket_urlpatterns

)

),

})

and the relevant part of my settings file:

# ASGI application configuration
ASGI_APPLICATION = 'chore_pro.asgi.application'

# Channels layers configuration for in-memory channel layer (suitable for development)
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}

(Channels is in the installed apps in settings.py)
Could someone please let me know why this isn't working and if any other things are needed to find this issue, thanks!

0 Comments
2024/04/12
00:46 UTC

1

Help with a project

I'm currently working on a university project, basically it's a jobs website for freelancers, my question is, should i use elasticsearch or the postgreSQL full text search, we're doing this project alongside a real business, they already own a job search website, so it's safe to think that there's going to be a lot of users and job offers if the website is finally deployed for them

0 Comments
2024/04/11
21:01 UTC

21

I needed to asynchronously trigger HTMX events in my project, so I made this

4 Comments
2024/04/11
20:55 UTC

1

Suggestion for a Feed Implementation

Hi Guys,

I am developing a social networking app wherein users can post in groups.

I would like to get your suggestions to implement a MyFeed page wherein the relevant posts for the user should appear. Following are the metrics I can think of.

  1. Groups the user follow
  2. Tags of the posts the user liked or shared

How do we implement this? Usually, we get the list of objects with the above filters. How to handle the offset when the different users see and refresh the post list?

0 Comments
2024/04/11
16:39 UTC

0

Automated Django code review tool

Free for open-source projects, has some useful Django comments and general Python ones also, highly recommend an install to cover simple mistakes sometimes missed when a human reviews.

Some examples would be:

  • Python test assertion corrects.
  • Pointing out unnecessary arguements in funcs/methods.
  • Python code optimisations.
  • Missing f-string code.
  • Checked-in breakpoints.
  • All of the best practices written on the official Django website.
  • Many more, I won't list them all :)

Here's the link https://codereview.doctor/features/python

2 Comments
2024/04/11
14:23 UTC

4

Freelancing

I want to start freelancing with Django but I'm not sure when to start. I already know how to connect APIs and databases. I am learning js and htmx and will possibly start learning React JS or some frontend framework.

5 Comments
2024/04/11
12:03 UTC

Back To Top