Skip to main content

Get the Reddit app

Scan this QR code to download the app now
Or check it out in the app stores
r/django icon
r/django icon

r/django

members
online

Updates to the Reddit protest and to /r/django moderation
MOD

Earlier this week, r/django went temporarily private (not visible to anyone except moderators) as part of a mass protest that thousands of other subreddits joined in. Then when the subreddit opened again, I put up a post explaining it and asking the community for input on how to proceed.

I summarized the issues in that post, and since then Reddit has not really taken action on them; there have been vague statements about accessibility and mod tools, but we've had vague statements about that stuff for close to a decade now, and no meaningful progress.

But that post is unfortunately no longer relevant, because Reddit has recently made clear that communities on Reddit do not have the right to make decisions for themselves. For more information, see:

Mod teams which ran polls of their community are also reporting that they've been messaged by Reddit admins who allege "brigading" and apply pressure to ignore poll results if the vote goes in favor of closing down a subreddit (but, curiously, Reddit admins don't seem to have any concerns if a poll goes in favor of staying open).

So no matter the result of the poll I posted recently, it seems likely that Reddit, Inc. would step in to force r/django to remain fully public forever. Your voices and votes don't matter -- Reddit now operates on the "one man, one vote" policy, where CEO Steve Huffman is the one man and has the one vote.

Which brings me to this post. I've been a volunteer moderator here for many years, cleaning up spam and the occasional bit of flame-war that flared up, and trying to help this place be a somewhat useful resource for people who use and like Django. But it's no longer tenable or tolerable given the recent actions of Reddit.

So I'm stepping down as a moderator of r/django, effective immediately.

This subreddit will remain open and public no matter what I or anyone else does, but I personally will no longer be a moderator of it, a subscriber to it, or a participant in it; instead I plan to shift my participation to the other official spaces of the Django community.


Need help with creating custom validators for a Serializer in Django REST framework Need help with creating custom validators for a Serializer in Django REST framework
REST framework

I am writing a serializer for a complicated put API with a large validate function. To simplify the logic and make it more readable, I want to create validators for individual fields (I want to make my serializer class as small as possible and hence don't want to write individual validate methods for each field). I am passing context to my serializer from the view and each of my fields share a common context. I want to use that context in the validator to perform the required checks.

This is how I am attempting to create custom validators:

My validator class:

class MyCustomValidator:
    requires_context = True

    def __call__(self, value, serializer_field):
        context = serializer_field.context
        print(f"got this context: {context}")

my serializer:

class MySerializer(serializers.Serializer):
   my_field = serializers.IntegerField(required=True, validators=[MyCustomValidator()])

sending context in my view:

def get_serializer_context(self): 
    context = super().get_serializer_context() 
    context.update({'test_context': {'key': 'value'}}) 
    return context 

But when I am calling this API, I get the following error: __call__() missing 1 required positional argument: 'serializer_field'

Can someone please tell me what am I missing here?

Thank you...




Integrating issue between django and react Integrating issue between django and react

hello my team is building full stack web app using django and react .

i am working on Django and others are working on react .

now we have started integrating them and we are getting error.

i have diagnosed the problem little bit and i found that the error is with static file and src link in frontend , because it always gives me "not Found Error" . so the issue might be with linking .

anyone hear has any knowledge or experienced such problem pls help , as deadline is near

https://preview.redd.it/integrating-issue-between-django-and-react-v0-yn94d4mzui9d1.pnghttps://preview.redd.it/integrating-issue-between-django-and-react-v0-cpzw37mzui9d1.png


Race condition with Gunicorn in production Race condition with Gunicorn in production

I'm looking for a solution, my code is -

class MyView():
    value = MyModel.objects.get(id=1).integerValueField
    otherTask() #takes around 1 second (assume)
    updatedValue = value + 1
    MyModel.objects.filter(id=1).update(integerValueField=updatedValue)
    return

Multiple Gunicorn workers accessing this view in production can lead to the failure of my logic for the concurrent users. How do I deal with it?

Can you all provide a valid link to understand the topic?



Help Needed: Flutter App Not Sending Headers to Django Rest Framwork Backend Help Needed: Flutter App Not Sending Headers to Django Rest Framwork Backend

I'm facing an issue with my Flutter app where the headers I'm trying to send to my Django backend aren't being received.

When I use Postman to send a request to my Django endpoint, the headers are received perfectly. However, when I make the same request from my Flutter app, the headers are missing.

  • Backend: Django Rest Framework (hosted on Azure Web Service)

  • Frontend: Flutter

when debug request header i made CustomJWTAuthentication

    class CustomJWTAuthentication(JWTAuthentication):
        def authenticate(self, request):
                header = self.get_header(request)
                logger.info("header : ")
                logger.info( header)
    
                if header is None:
                    logger.info( " header is None:")
                    return None

it print header is None

https://preview.redd.it/help-needed-flutter-app-not-sending-headers-to-django-rest-v0-80fv91riaf9d1.jpg

the flutter code

https://preview.redd.it/help-needed-flutter-app-not-sending-headers-to-django-rest-v0-jdoe1zwlaf9d1.jpg

update :

i found the problem I've identified the issue—Flutter app was sending the request with HTTP instead of HTTPS



Seeking feedback on Django bursaries board Seeking feedback on Django bursaries board

Hello, r/django community,

I've built a Django-based bursaries board and I'm looking for advice on architecture, performance, and best practices. While the code is private, I'd appreciate general feedback on my approach.

Project overview:

  • A platform for students to find info for bursaries

Tech stack:

  • Backend: Django 4.2

  • Frontend: Bootstrap 5 with custom CSS tweaks

  • Database: PostgreSQL

  • Deployment: Railway with Docker

  • CDN/Proxy: Cloudflare

Areas I'm seeking advice on:

  • Caching strategy: With Cloudflare as a proxy, what's the best approach to implement caching? Should I use Django's caching framework in addition to Cloudflare's caching?

  • Scaling concerns: As the platform grows, what should I consider for scaling? Are there any Django-specific optimizations I should consider?

  • How to deal with Seo working with Django, I've read about sitemaps and robots.txt. What other Django-specific SEO techniques should I consider?

https://sabursaries.site/





What attracted you to django? What attracted you to django?

When I was previously working in some company, I used django for their internal project. I merely knew name of this framework & nothing else. When I went further on, I realised how simple & fun it was to use django, i.e. DB connection, simplicity of customizing authentication etc. Things were gr8.. And I read news about Elon Musk buying Twitter and rebranding it to "X". I suddenly thought how easy & fun it would be to change all things if Twitter engineers were using django for their backend as well as frontend. (It might sound strange tho.) That's when I decided to make a career as Python backend developer. So what was "turning point" for you to get attracted to django framework??



You're given a take home coding test for a new job, do you include unit tests? You're given a take home coding test for a new job, do you include unit tests?

I'm currently looking to hire a mid-level Django dev to help with the project I work on. We ask for a pretty simple CRUD application to create and manage users, its nothing crazy and should take a half decent Django dev an less than an evening to complete. Unit tests are not explicit in the requirements but we use their prescence to check for best practices.

If you were to do this test would you bother to write unit / integration tests? We've had a bunch of people apply and they just don't seem to do it.


How to not write atrocious APIs with Django Rest Framework? How to not write atrocious APIs with Django Rest Framework?

I recently wrote an API with django which does a lot of things, and it got me thinking that I really have a big gap in my django/ django rest framework knowledge. It is basically creating User instances for a staff user. The API is supposed to take role and different subject ids which will be used for the SubjectTeachers model. Then, after creating a user, it sends email to the user's email through a celery task. It also handles email already being sent, and just resends it based on if the user changed their password or not.

The thing is, I don't think I'm handling this in any good way. There are no use of serializers, functions, just a big ass function doing a lot of things. I want to know how would you handle it in a proper way, following proper conventions provided by django and django rest framework. There is no proper error handling, half ass validations.

Please provide me with your insights, resources on how I should properly approach building APIs with django rest framework, and how this API should have been created.

```python

class InviteStaffApiView(APIView):
    permission_classes = [IsAdminUser]
    def get_object(self, staff_id):
        try:
            staff = Staff.objects.get(id=staff_id)
            return staff
        except Staff.DoesNotExist:
            return None
    def post(self, request, *args, **kwargs):
        staff_id = kwargs.get("staff_id")
        role = kwargs.get("role")
        subjects = request.data.get("subjects")
        staff = self.get_object(staff_id)
        if not staff:
            return Response({"detail" : "Staff not found"}, status=status.HTTP_404_NOT_FOUND)
        PasswordReset.objects.filter(user__email=staff.email).delete()
        if staff.user:
            if staff.user.has_usable_password():
                return Response("Staff already has an account", status=status.HTTP_400_BAD_REQUEST)
            else:
                # Resend invitation if staff has an account but no usable password
                token_instance = PasswordReset.objects.create(
                    user=staff.user,
                    token=generate_random_token(),
                    expires_in=timezone.now() + timedelta(days=1),
                )
                send_password_reset_link.delay(staff.email, token=token_instance.token)
                return Response({"detail":"Invitation has been resent to the staff"}, status=status.HTTP_201_CREATED)
        with transaction.atomic():
            user = User.objects.create(email=staff.email, first_name = staff.first_name, last_name = staff.last_name,contact_number=staff.contact_number)
            user.set_unusable_password()
            user.save()
            staff.user = user
            staff.role = role
            staff.save()
            subjects_instances = [SubjectVariation(user = user, subject = subject) for subject in subjects]
            SubjectTeachers.objects.bulk_create(subjects_instances)
        token_instance = PasswordReset.objects.create(
            user=user,
            token=generate_random_token(),
            expires_in=timezone.now() + timedelta(days=1),
        )
        send_password_reset_link.delay(staff.email, token=token_instance.token)
        return Response({"detail" : "Invited Staff successfully"}, status=status.HTTP_201_CREATED)
class InviteStaffApiView(APIView):
    permission_classes = [IsAdminUser]

    def get_object(self, staff_id):
        try:
            staff = Staff.objects.get(id=staff_id)
            return staff
        except Staff.DoesNotExist:
            return None

    def post(self, request, *args, **kwargs):
        staff_id = kwargs.get("staff_id")
        role = kwargs.get("role")
        subjects = request.data.get("subjects")
        staff = self.get_object(staff_id)
        if not staff:
            return Response({"detail" : "Staff not found"}, status=status.HTTP_404_NOT_FOUND)


        PasswordReset.objects.filter(user__email=staff.email).delete()

        if staff.user:
            if staff.user.has_usable_password():
                return Response("Staff already has an account", status=status.HTTP_400_BAD_REQUEST)
            else:
                # Resend invitation if staff has an account but no usable password
                token_instance = PasswordReset.objects.create(
                    user=staff.user,
                    token=generate_random_token(),
                    expires_in=timezone.now() + timedelta(days=1),
                )
                send_password_reset_link.delay(staff.email, token=token_instance.token)
                return Response({"detail":"Invitation has been resent to the staff"}, status=status.HTTP_201_CREATED)

        with transaction.atomic():
            user = User.objects.create(email=staff.email, first_name = staff.first_name, last_name = staff.last_name,contact_number=staff.contact_number)
            user.set_unusable_password()
            user.save()
            staff.user = user
            staff.role = role
            staff.save()
            subjects_instances = [SubjectVariation(user = user, subject = subject) for subject in subjects]
            SubjectTeachers.objects.bulk_create(subjects_instances)

        token_instance = PasswordReset.objects.create(
            user=user,
            token=generate_random_token(),
            expires_in=timezone.now() + timedelta(days=1),
        )
        send_password_reset_link.delay(staff.email, token=token_instance.token)
        return Response({"detail" : "Invited Staff successfully"}, status=status.HTTP_201_CREATED)

Recommendations for setting up small team django development environment Recommendations for setting up small team django development environment
Apps

My wife was a software developer prior to hanging up her compilers to raise the family. Recently she went back to work as a professor at the community college teaching python / Django / C++ / database / systems analysis. She also has a side hustle that has a Wordpress / Woocommerce site as well as an Etsy storefront which she runs with a business partner.

In an effort to "walk the walk and talk the talk", she wants to develop a Django / PostgreSQL site to handle "back office" type functions for the shop (product management, inventory, sales tracking, etc).

The site will only be used internally, so no public users, but the business partner will need access as well, so will need to host it externally - Knownhost is our hosting provider for the Wordpress site, but in looking into this a little further, leaning towards something like pythonanywhere / digital ocean / Heroku / other as a the hosting provider.

Any recommendations / pointers for how to set up the development environment for 2 - 3 people and get this off the ground would be greatly appreciated. Going with the "use what you know" mantra, we'll be using vscode and git.

For a foundation to build on, currently looking at Cookiecutter Django. Security is obviously a concern, so hopefully this combined with pythonanywhere / et all gives us a leg up on covering those bases

Thanks for your time.


Copy model instance to prefill form? Copy model instance to prefill form?

I am making a recipe application. I want to be able to copy an existing recipe and make edits to create a new recipe. How I can prefill a form/edit view using an existing model instance and then save the data into a new model instance?

Here is my current model structure, it's implementation assumes that a recipe is composed of pre-existing ingredients and, potentially, other user generated recipes.

Models.py

class Ingredient(models.Model):
    """Base ingredient class"""
    name = models.CharField(max_length=500)
    ...

class Recipe(models.Model):
    """Base recipe class containing instructions and description"""
    name = models.CharField(max_length=500)
    ...
    ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')
    sub_recipes = models.ManyToManyField('self',
                                         through='RecipeSubRecipe',
                                         symmetrical=False,
                                         related_name='parent_recipes')

class RecipeIngredient(models.Model):
    """Junction table for instances of recipes and ingredients"""
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='recipe_ingredients')
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    quantity = models.FloatField()
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE)

class RecipeSubRecipe(models.Model):
    """Junction table for recipes containing other recipes"""
    parent_recipe = models.ForeignKey(Recipe, related_name='parent_recipe_set', on_delete=models.CASCADE)
    sub_recipe = models.ForeignKey(Recipe, related_name='sub_recipe_set', on_delete=models.CASCADE)
    quantity = models.FloatField()
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE)

I use forms and formsets to handle adding and editing recipes and ingredient/sub recipe fields. However, my copy view runs into issues with form_valid.

Views.py

class RecipeCopyView(CreateView):
    model = Recipe
    form_class = RecipeForm
    template_name = 'coster/recipe_form.html'
    success_url = reverse_lazy('coster:recipes')

    def get_initial(self):
        initial = super().get_initial()
        original_recipe = get_object_or_404(Recipe, pk=self.kwargs['pk'])
        initial['instructions'] = original_recipe.instructions
        initial['output_quantity'] = original_recipe.output_quantity
        initial['output_unit'] = original_recipe.output_unit
        initial['is_wet'] = original_recipe.is_wet
        return initial

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)

        if self.request.POST:
            data['ingredient_formset'] = RecipeIngredientFormSet(self.request.POST)
            data['sub_recipe_formset'] = RecipeSubRecipeFormSet(self.request.POST)
        else:
        # Prefill the new form 
        original_recipe = get_object_or_404(Recipe, pk=self.kwargs['pk'])
        data['ingredient_formset'] = RecipeIngredientFormSet(instance=original_recipe)
        data['sub_recipe_formset'] = RecipeSubRecipeFormSet(instance=original_recipe)
        # Copy the instance
        original_recipe.pk = None

            # Clear the instances for the formsets to avoid validation issues
            for form in data['ingredient_formset'].forms:
                form.instance.pk = None
            for form in data['sub_recipe_formset'].forms:
                form.instance.pk = None

        return data

    def form_valid(self, form):
        context = self.get_context_data()
        ingredient_formset = context['ingredient_formset']
        sub_recipe_formset = context['sub_recipe_formset']

        if ingredient_formset.is_valid() and sub_recipe_formset.is_valid():
            self.object = form.save()
            ingredient_formset.instance = self.object
            sub_recipe_formset.instance = self.object
            # Save formsets with the new recipe instance
            ingredient_formset.save()
            sub_recipe_formset.save()
            return redirect(reverse('coster:recipe_detail', kwargs={'pk': self.object.pk}))
        else:
            return self.render_to_response(self.get_context_data(form=form, ingredient_formset=ingredient_formset,
                                                                 sub_recipe_formset=sub_recipe_formset))

The copy view is able to prefill the form correctly. The problem arises when I go to save. The page refreshes and this bullet point appears above each ingredient:

(Hidden field recipe) The inline value did not match the parent instance.

Do I have to create a full copy and save to the database before I can let the user edit the recipe? If the user cancels, how I can determine that they cancelled and then delete the copy?

Let me know if I need to share my forms.py or anything else.




Favourites chrome extension for Django Admin Favourites chrome extension for Django Admin

I was getting very tired of searching for and scrolling through links in my admin page. To solve this problem I built a chrome extension that allows you to add a list of favourite links to the top of your django admin home page. Find the extension here.

The extension runs locally and will be free forever! Hope this is helpful for you.

Example of favourites links:

Favourites chrome extension for Django Admin

Embed quicksight dashboard into Django Embed quicksight dashboard into Django

Hi all,

We have an AWS quicksights dashboard that another developer has set up.

He’s passed me the url, I can load it up ina browser.

They have given me a bit of html with an iframe and the URL to the dashboard.

However, I just get the grey screen saying it can’t be accessed.

In quicksights I’ve added the domain for embedding it.

Still no joy, I’m getting an error regarding the Content Security Policy which I’ve added a meta tag to the page, and added the aws link to the CSP in the settings file.

Still no joy, has anyone tried doing this? I think I might be missing a setting in AWS, but might be going down the wrong path with setting CSP or just missing the wrong policy