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...
I am a beginner to backend development and databases,
I followed a few tutorials and built a blog app and chat app.
I was trying to build an e-commerce website backend using Django and PostgreSQL on my own but I'm messing up everything.
Please list good resources to learn Django and backend development.
What's the best practice for scaling a Django app?
• Django + Elastic Beanstalk
• Django + Docker + Fargate
• Django + Kubernetes + Docker + EKS
• Django + Docker + ECS
Have you guys tried all four? which one works the best when handling a large amount of traffic?
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
For people who completed the Django for Beginners book by Williams Vincent, what was your first project after completing the book or what did you do next?
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?
I run an ecommerce platform, my users want to embed their stores (hosted by me) in their sites using iframes.
The problem is that iframes + incognito/Safari = bricked store, because cookies are blocked.
I was wondering if there's a workaround for using sessions without cookies?
Like passing around the session_key/sessionid as GET parameters in every action?
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
the flutter code
update :
i found the problem I've identified the issue—Flutter app was sending the request with HTTP instead of HTTPS
I want to be able to add a project to the list of projects on the sidebar and if the element on the left that lists projects as cards is activated, directly add a card for the new project. I'm using HTMX for the requests to my back and I don't know how to do it.
Hello, 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?
Let's say I have 100+ pages, all with a similar but different structure to them e.g. text blocks, images and interactive sections. Would Wagtail be worth it at this point, or is it only worthwhile if each page has a generic strucute?
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??
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.
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)
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 . 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.
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.
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 .
The extension runs locally and will be free forever! Hope this is helpful for you.
Example of favourites links:
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
Hello everyone,
I am currently creating a CV writing web application using HTML, CSS, and JavaScript . for front end and Django for backend. However, I have reached a point where I cannot proceed because I do not know how to integrate CV templates into my Django project. Can anyone provide insight on how I can do this?