Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Production setup for celery
How can i setup Celery in Production Server using aws or digitalocean and broker as redis or rabbitmq. Please elaborate more on how we can resilience over the connection refused error while the broker is down. -
Passing Variable (View --> Template --> View)
Problem: I want to generate a random number, and ask the user to calculate the addition of these two. Then, I want to evaluate the number and see if the solution is correct. My issue: I can do everything except the evaluation bit, as the values of the random numbers change! HTML file: <p> What is {{ a }} + {{ b }} ? </p> <form action="{% url 'form_handle' %}" method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> FORM file: class MyForm(forms.Form): num1 = forms.CharField(max_length=20) VIEW file: def form_handle(request): if request.method == 'POST': form = MyForm(request.POST) # if post method then form will be validated if form.is_valid(): cd = form.cleaned_data num1 = cd.get('num1') #num2 = cd.get('num2') #result = cd.get('result') if float(num1) == float(a + b): # give HttpResponse only or render page you need to load on success return HttpResponse("Good job!") else: # if sum not equal... then redirect to custom url/page return HttpResponseRedirect('rr/') # mention redirect url in argument else: a = random.randrange(5,10); b = random.randrange(10,20); form = MyForm() # blank form object just to pass context if not post method return render(request, "rr.html", {'form': form, 'a': a, 'b':b}) The error I get is "local variable 'a' referenced before assignment". … -
Django - Url Dispatching - Page Not Found
I am very puzzled as to why the URL dispatcher is try to look for an empty path although a url was specified for it? Does it imply that it is unable to find the specified url and therefore trying to find the default. This happens when I try to POST and HttpResponseRedirect searches for an empty path instead of following the specified path. Assume that the other. Using Django version: 2.0 Thanks in advance! main/urls.py (ROOT_URLCONF) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('app/', include('shorterner.urls')) ] shorterner/urls.py from django.urls import path from . import views urlpatterns = [ path('request/', views.RequestView.as_view(), name="request"), path('list/', views.IndexView.as_view(), name="list") ] shorterner/views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.conf import settings from django.urls import reverse from django.views import View, generic from .models import Urls import requests import json from .forms import SubmitUrlForm class RequestView(View): form_class = SubmitUrlForm initial = { 'url': ''} template_name = "shorterner/request.html" context_object_name = 'url' def form_valid(self, form): return super().form_valid(form) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): input_url = form.cleaned_data['url'] short_url = google_url_shorten(input_url) print(input_url) print(short_url) … -
Ideal page is not shown
Ideal page is not shown. I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] return render(request, 'top.html',{'content':content}) def detail(request,pk): content = POST.objects.order_by('-created_at')[:5] return render(request, 'detail.html',{'content':content}) in top.html <div> {% for item in content %} <h2>{{ item.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <div> <h2>{{ content.title }}</h2> <p>{{ content.text }}</p> </div> in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('detail/<int:pk>/',views.detail , name='detail'), ] When I access top method, top.html is shown.And when I click SHOW DETAIL url link, detail.html is shown.But in this detail.html,always content is same.I wanna make a system when I click this link, detail's content is changed each content.pk.But now my system is not my ideal one.Why does my system always return same content in detail.html?How should I fix this? -
About Django pk in urlpattern
I am new to Django, and I am reading one app on github: https://github.com/rogargon/myrecommendations/blob/web2-html/myrestaurants/urls.py#L18 There is one urlpattern like url(r'^restaurants/(?P<pk>\d+)/$', RestaurantDetail.as_view(), name='restaurant_detail') It revoke RestaurantDetail view, here: https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/views.py#L36 class RestaurantDetail(DetailView): model = Restaurant template_name = 'myrestaurants/restaurant_detail.html' def get_context_data(self, **kwargs): context = super(RestaurantDetail, self).get_context_data(**kwargs) context['RATING_CHOICES'] = RestaurantReview.RATING_CHOICES return context Here I know pk is set to one number indicating the id of restaurant, but in the html model, https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/templates/myrestaurants/restaurant_detail.html, I didn't see any where using pk, but the page shows only the one restaurant. Could you how does pk work in this process? {% extends "myrestaurants/base.html" %} {% block title %}MyRestaurants - {{ restaurant.name }}{% endblock %} {% block content %} <span vocab="http://schema.org/" typeof="Restaurant"> <h1> <span property="name">{{ restaurant.name }}</span> {% if user == restaurant.user %} (<a href="{% url 'myrestaurants:restaurant_edit' restaurant.id %}">edit</a>) {% endif %} </h1> <h2>Address:</h2> <p> {{ restaurant.street }}, {{ restaurant.number }} <br/> {{ restaurant.zipcode }} {{ restaurant.city }} <br/> {{ restaurant.stateOrProvince }} ({{ restaurant.country }}) </p> <h2> Dishes {% if user.is_authenticated %} (<a href="{% url 'myrestaurants:dish_create' restaurant.id %}">add</a>) {% endif %} </h2> <ul> {% for dish in restaurant.dishes.all %} <li><a href="{% url 'myrestaurants:dish_detail' restaurant.id dish.id %}"> {{ dish.name }}</a></li> {% empty %}<li>Sorry, no dishes for this restaurant yet.</li> {% … -
NoReverseMatch at /app/^detail/3/$
I got an error,NoReverseMatch at /app/^detail/3/$ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['app/\^detail\/(?P[0-9]+)\/\$$'] . I wrote codes in urls.py urlpatterns = [ path('top/', views.top, name='top'), path(r'^detail/<int:pk>/$',views.detail , name='detail'), ] in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] return render(request, 'top.html',{'content':content}) def detail(request,pk): content = POST.objects.order_by('-created_at')[:5] return render(request, 'detail.html',{'content':content}) in top.html <div> {% for item in content %} <h2>{{ item.title }}</h2> <p><a href="{% url 'detail' pk %}">SHOW DETAIL</a></p> {% endfor %} </div> When I clicked url of SHOW DETAIL,this error happens.When I saw what's url I accessed ,it was http://localhost:8000/app/%5Edetail/3/$.I really cannot understand why %5Edetail is contained in url.How should I fix this?I did not write codes such a word was contained in url.What is wrong in my codes? -
Using multiple conditions in Django's Case When expressions
As per the Django documentation, its possible to use multiple conditions with the When clause. When(registered_on__gt=date(2014, 1, 1),registered_on__lt=date(2015, 1, 1),then='account_type') However, I am unable to use the same when using the Case clause. Case(When(registered_on__gt=date(2014, 1, 1),registered_on__lt=date(2015, 1, 1), then='account_type'), default='default') I end up getting the following error: TypeError: __init__() got multiple values for keyword argument 'then' Is there some way I can achieve this? Am I missing something here? -
Re-configuring allauth to fit custom specifications
I have a set of expectations I'm trying to achieve. I want a sign up, login, and forget password page. I also want to have social sign in using Twitter, Facebook, or Google. Another thing I want is to send a confirmation email to the user validating their account. I know I can do this with Django allauth, but allauth comes with extra features that I don't need. For example, I don't need the password reset and change email pages. I want to remove these pages and their corresponding functionality, but I'm afraid I might break the code if I do this. I was thinking about two solutions. One solution would be to go through the allauth templates and change some of the code to fit my specifications, but I feel like it would be very tedious because a lot of things might break if I remove some funcionality. The second solution I was thinking of doing was building on top of auth and using a custom User model and building custom login, sign up, and reset pages. Adding the required functionality and everything. I could also build the models to provide social login by copying allauth's templates. I am … -
Django how ImageField and BinaryField works for image
So i wanted to ask how does these 2 fields works. As my friend told me that his ios will sent byte format image to me, does it matter if i use imageField instead of BinaryField ? I did try adding a Binaryfield into my User models but when testing it out on django admin and also django rest framework api, it doenst work In django admin : the binaryfield did not appear in it In django rest framework : got an error that says editable is false for binary field. Setting the binaryfield editable=True also doesnt work. The documentation about Binaryfield in django is also not much. Can anyone please explain to me how does these 2 field work ? does sending byte format to the imagefield work ? -
Save downloaded image in django ImageField
I want to download an image and save as django ImageField. Where is my mistake? from django.core.files import File from urllib.requests import urlretrieve from .models import Photo r = urlretrieve("http://test.com/img/test.png", "./test.png") f = open("/tmp/test.png", "rb") django_file = File(f) img = Photo() img.name = "Test" img.logo.save("test.png", django_file, save=True) -
django: naming files, dirs, classes, etc
django 2.0 python 3.6.3 Hi, I have stubbed my toe on django. I have seen that models can be split out into individual files a la: |-- models | |-- __init__.py | `-- Profile.py I have also tried to do the same thing with views and forms. I ran into the case where I was importing a model and a view where the underlying file had the same name: from models import Profile from views import Profile but the code got confused over which "Profile" I was talking about. I decided to rename the files |-- models | |-- __init__.py | `-- m_profile.py |-- views | |-- __init__.py | `-- v_profile.py then do from models.m_profile import Profile from views.v_profile import Profile but now the migrations are messed up -- I get the error ModuleNotFoundError: No module named 'models'. Is there a better way to handle these things? -
CommandError: Can't find xgettext. django
I am making an app for my website with django and i need to ad persian language to my project. But when I tried to run following command django-admin.py makemessages and i get this error CommandError: Can't find xgettext. Make sure you have GNU gettext tools 0.15 or newer installed. i have installed python-gettext with pip and installed GetText for Windows and gettext.tools with nuget i saw some guys with problems similar to mine like this but they're solutions didn't help me what should i do? (i am using windows 7 64 bit and i am really noob in django ) -
Django: Display website name without using Sites framework
I want to render my website name in Jinja templates. Django's own docs on Sites state: Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way. I know I can still use it, but it seems like an overkill. I just want to pull a variable with my website's name (!= domain) in ANY template. I don't want to pass it in views either because that doesn't seem DRY enough. TIA -
I want to use the if statement based on the existence of a web page
So basically i have a complicated scenario. I am current using Django to build a website and i have current made two apps. Both apps have almost identical fields. The field I would want to focus on though is the Information field(which they both have and which i have auto generated with the help of the Wikipedia model) So the case here is that I want to create an if and else statement in the html in such a way that if the page i am hyperlinking to exists it would go to the link dealing with DetailView but if it doesnt exist I would redirected to the Create View I should also note that the two apps have their names linked with the help of the foreign key but when i try to open information links using the same name , they gave me different pks I dont feel like i explained my problem well enough but I hope someone can understand what i mean This is the Detail View Html {%extends "home.html"%} {%block head_title%} {{block.super}}{%endblock head_title%} {% block content%} <!-- verify authentication --> {% if request.user.is_authenticated%} <h3><a href="{%url 'InfoPedia:UpdateView' object.id %}">{{object.title}}</a></h3><br/> {% endif %} <ul type="disc"> <div class="container"> … -
Dictionary update sequence element #0 has length 1; 2 is required in Django
I'm using Python 3.5.4 with Django 2.0.0 final 0. I'm trying create a Django blog web application. I received error after I had created Django view and template. Here's my error: Internal Server Error: /blog Traceback (most recent call last): File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/middleware/common.py", line 60, in process_request if self.should_redirect_with_slash(request): File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/middleware/common.py", line 79, in should_redirect_with_slash is_valid_path('%s/' % request.path_info, urlconf) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/base.py", line 155, in is_valid_path resolve(path, urlconf) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/base.py", line 24, in resolve return get_resolver(urlconf).resolve(path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 496, in resolve sub_match = pattern.resolve(new_path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 496, in resolve sub_match = pattern.resolve(new_path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 345, in resolve kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required [01/Jan/2018 21:12:43] "GET /blog HTTP/1.1" 500 88570 Here's autisticstory/urls.py file: """autisticstory URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the … -
django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with no arguments not found
I have a fairly simple retrieve test: def test_user_retrieve(self): factory = APIRequestFactory() User.objects.create_superuser(username='test', password='Welcome2', email='test@test.com') user = User.objects.get(username='test') view = UserViewSet.as_view({'get': 'retrieve'}) url = reverse('core:user-detail') request = factory.get(url) force_authenticate(request, user=user) response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK) It gives the following traceback: Traceback (most recent call last): File "D:\Projects\enterpass\api\core\tests.py", line 54, in test_user_retrieve url = reverse('core:user-detail') File "D:\Python36\lib\site-packages\django\urls\base.py", line 88, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "D:\Python36\lib\site-packages\django\urls\resolvers.py", line 632, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with no arguments not found. 2 pattern(s) tried: ['api/v1/core/users/(?P<pk>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/v1/core/users/(?P<pk>[^/.]+)/$'] If I hit the URL using postman there's no issue: http://localhost:8000/api/v1/core/users/1/ The view is being registered via a router like so: app_name = 'core' router.register(r'users', views.UserViewSet, base_name='user') here is the part of the view that's pertinent: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes_by_action = {'list': [CanListUser], 'create': [CanCreateUser], 'retrieve': [CanRetrieveUser], 'update': [CanUpdateUser], 'destroy': [CanDestroyUser]} def retrieve(self, request, pk=None, **kwargs): try: instance = self.get_object() self.check_object_permissions(self.request, instance) serializer = UserSerializer(instance, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) except User.DoesNotExist: return Response(status=status.HTTP_204_NO_CONTENT) Found the solution but I'd love someone to explain for me based on this working view: def test_user_retrieve(self): factory = APIRequestFactory() User.objects.create_superuser(username='test', password='Welcome2', email='test@test.com') user = User.objects.get(username='test') view = UserViewSet.as_view({'get': 'retrieve'}) url = … -
Wagtail allow users to edit page
Is there a way in wagtail to allow specific users to access the admin interface and only be able to edit / create certain pages? Browsing around the docs I don't see anything like this discussed. Example: I want to take advantage of streamfields to allow users to create / edit page with dynamic content / layouts. However, I don't want the users to be able to access the entire interface to where they could change other parts of the site just this one specific page for editing / creating. How would I go about this? Add them to a group with editing permissions? But, since this is the wagtail admin.... Doesn't that require tehse users to be an "admin"? -
Updating package on Anaconda environment
Is there a way to update only the django package on the python 3 environment to version 2.0? My base version of python is 2.7.14. Anaconda 4.4.4. I created a new environment for python 3.6.3. I installed django 1.11.8 (as this is the latest version available for python 2.7) on both environments but I need django 2.0 on my python 3 environment. When I try: conda install django=2.0 PackagesNotFoundError: The following packages are not available from current channels: django=2.0 Current channels: https://repo.continuum.io/pkgs/main/win-64 https://repo.continuum.io/pkgs/main/noarch ... with a few more similar links Am I missing something? Is this even possible to do within an environment in the python 2 Anaconda? -
Django: How can I create a dynamic form that changes on user click?
I'm making a workout calendar website where a user can add workouts with varying amounts of lift, sets and reps, etc. Thus, I need a form that adds a field when a user clicks a button. I've made a template and some javascript to describe what it is I want to achieve exactly: url: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add_workout, name = 'add_workout') template: {% block hidden %} {% include "workoutcal/liftrow.html" %} {# To be used by Javascript #} {% include "workoutcal/cardiorow.html" %} {% endblock %} <form action="{% url 'add_workout' date.year date.month date.day %}" method="post"> <div class="row"> <div class="col-xs-2"> <p id="date">{{ date.year }}-{{ date.month }}-{{ date.day }}</p> <input type="hidden" name="date" value="{{ date }}"> </div> </div> <h2 class="col-xs-12">Lifts</h2> <div id="liftrows"> {% for i in range %} {% include "workoutcal/liftrow.html" %} {% endblock %} </div> <div class="row"> <div class="col-xs-0"></div> <label class="col-xs-2"><button type="button" id="addliftbutton">One more lift</button></label> </div> <h2 class="col-xs-12">Cardio</h2> <div id="cardiorows"> {% include "workoutcal/cardiorow.html" %} </div> <div class="row"> <label class="col-xs-2"><button type="button" id="addcardiobutton">One more cardio</button></label> </div> <div class="row"> <div class="col-xs-10"></div> <label class="col-xs-2"><input type="submit" id="submitbutton" value="Save Workout"></label> </div> </form> javascript: //Adding onclick to buttons document.getElementById('addliftbutton').onclick = addLiftRow; document.getElementById('addcardiobutton').onclick = addCardioRow; for (var i=0; i<setsBoxes.length; i++){ setsBox = setsBoxes[i]; setsBox.onchange = insertRepFields; } function addLiftRow(){ var liftRowElements = document.getElementById('liftrows'); var … -
How to solve inefficient code?
The following are my two serialization classes. #1 class CoverLetterSearchSerializer(serializers.ModelSerializer): application_type = serializers.SerializerMethodField() quarter_type = serializers.SerializerMethodField() class Meta: model = models.Coverletter fields = ( 'id', 'company', 'application_year', 'quarter_type', 'application_type', ) def get_application_type(self, obj): return obj.get_application_type_display() def get_quarter_type(self, obj): return obj.get_quarter_type_display() #2 class CoverletterListSerializer(serializers.ModelSerializer): application_type = serializers.SerializerMethodField() quarter_type = serializers.SerializerMethodField() class Meta: model = models.Coverletter fields = ( 'id', 'company', 'application_year', 'application_type', 'application_deadline', 'quarter_type', 'application_flag', 'pass_flag', ) I made two serializers for the data to show in VIEW. However, if I change the field of the model class used in the serializer, should I change the fields of this serializer class all the time? Please tell me about this problem. -
Removing Django allauth change email page
I'd like to remove the Django allauth change email page and all of its functionalities that come with it. I know I can make a template for allauth and use my custom pages and deleting that page and removing all the functionalities associated with it manually, but I was wondering if there was a better way to solve this. I am afraid once I start removing the change email page functionalities something will start breaking. Is there a way to remove this page without breaking anything? -
Bootstrap "default" navbar example inconsistent
While playing with Django, I've added a basic home-page example from the Bootstrap navbar example. My Django app simply redirects any link to the home page with the following template: {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> {# <link rel="icon" href="../../favicon.ico">#} <title>Navbar Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/navbar.css' %}" rel="stylesheet"> <script src="{% static "js/jquery.js" %}"></script> <script>window.jQuery || document.write('<script src="{% static 'js/jquery.js' %}"><\/script>')</script> <script src="{% static 'js/bootstrap.js' %}"></script> </head> {% load bootstrap3 %} {% bootstrap_javascript %} {% bootstrap_css %} <body> <div class="container"> <!-- Static navbar --> <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> … -
Do I need to create forms.py for my forms in Django?
I'm about to create a form in my website made in Django with elements that have complex input types from different plugins (like calendar plugins). Also, I'll be using a Validator plugin which validates the input before submission. My question is do I need to create forms.py and like model the form or can I just create the form manually? The former seems like a very hassle process. Which one is more efficient and recommended? -
Django rest nested serializer fails
My model relationships are: A 'Reader' will have a single 'Wishlist' and a 'Wishlist' will contain many 'Book's. I want to create an empty Wishlist automatically during Reader object instance creation. My Models: class Wishlist(models.Model): wishlist_id = models.AutoField(primary_key=True) class Reader(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30) address = models.CharField(max_length=80) dob = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) wishlist = models.OneToOneField(Wishlist, null=True, blank=True) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) which_wishlist = models.ForeignKey('Wishlist', related_name='my_wishlist', on_delete=models.CASCADE, null=True, blank=True) And serializer: class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' #depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library', 'wishlist') def update(self, instance, validated_data): instance.user.email = validated_data.get('user.email', instance.user.email) instance.user.password = validated_data.get('user.password', instance.user.password) instance.phone = validated_data.get('phone', instance.phone) instance.address = validated_data.get('address', instance.address) instance.dob = validated_data.get('dob', instance.dob) instance.which_library = validated_data.get('which_library', instance.which_library) instance.wishlist = validated_data.get('wishlist', instance.wishlist) instance.save() return instance def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() wishlist_data = validated_data.pop('wishlist') reader = Reader.objects.create(**validated_data) Wishlist.objects.create(reader=reader, **wishlist_data) return reader My view that handles the creation: @api_view(['GET', 'POST']) def reader(request, library_id): """ List all readers in a specific library, or create a new … -
How to store user customizable queries?
I would like to allow a bunch of my users to run arbitrary and periodical queries. So far, I've managed to create this model: class BasicQuery(models.Model): id = models.AutoField(primary_key=True) target_entity = models.CharField(max_length=255) target_field = models.CharField(max_length=255) operator = models.CharField(max_length=10) compare_value = models.CharField(max_length=10) active = models.BooleanField() run_every = models.ForeignKey(QueryFrequency) and the function which executes it : def rule_runner(rule): target_entity = rule.target_entity fieldname = rule.target_field val = rule.compare_value if rule.operator: cmd = '{}.objects.filter({}__{}={})'.format(rule.target_entity, rule.target_field, rule.operator, rule.compare_value) else: cmd = '{}.objects.filter({}={})'.format(rule.target_entity, rule.target_field, rule.compare_value) return eval(cmd) But because of the eval(cmd), the code is way too dangerous to go to production, no matter how many tests I'll do before calling this function I'll never feel safe about it. Any suggestions on how I can achieve this purpose in a clean way?