Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Direct assignment to the reverse side of a many-to-many set is prohibited. Use products.set() instead. Django REST Framework
I get the following error when I POST a new product with a category (the product information is formatted like this:) { "product_code": "testcode", "name": "testname", "quantity": 22, "price": 22, "categories": [{ "name": "Test category", "products": [], "categories": [] }] } the error Direct assignment to the reverse side of a many-to-many set is prohibited. Use products.set() instead. and when I use product.categories.set(**category) I get the following error set() got an unexpected keyword argument 'name' My models.py file from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) categoriesId = models.ForeignKey('self', related_name='categories',on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): product_code = models.CharField(max_length=255) name = models.CharField(max_length=255) price = models.IntegerField() quantity = models.IntegerField() categories = models.ManyToManyField(Category, related_name='products') my serializers.py file from rest_framework import serializers from products_and_categories.models import Product, Category from django.db import models class CategorySerializer(serializers.ModelSerializer): def to_representation(self, obj): if 'categories' not in self.fields: self.fields['categories'] = CategorySerializer(obj, many=True) return super(CategorySerializer, self).to_representation(obj) class Meta: model = Category fields = ("name", 'products', 'categories') class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Product fields = ("product_code", "name", "quantity", "price", 'categories') def create(self, validated_data): category_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) for category in category_data: product.categories.create(**category) return product Any idea what's going on ? -
consume Django Python service via WSO2 API manager
I'm using WSO2-2.5.0 and i want to know if WSO2 API Manager is compatible with Python based restful services or not. I have several webservices developed in Python. On Python service, I don't receive request body from WSO2. Actually the services are working fine and can communicate with them via REST Console. I debugged WSO2, it receives and sends payload to backend. I need to know how I can consume payload in Python services just like my Java services. -
Python - Django - modify fields in serializer
i have the following setup: I have a basic blog and article relation, where i get all blogs and its associated articles: class BlogSerializer(serializers.ModelSerializer): articles = ArticleSerializer(many=True, read_only=True) class Meta: model = Blog fields = ('id', 'name', 'articles') depth = 0 class BlogViewSet(ViewSetMixin, GenericAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer Now i want to keep things as the are, BUT: When the list view is called (e.g. api/blogs), only the ids of the articles should be shipped, so i extended my viewset to: class BlogViewSet(ViewSetMixin, GenericAPIView, ..): queryset = Blog.objects.all() serializer_class = BlogSerializer def get_serializer(self, *args, **kwargs): # pseudo code if self.context['request'].action == 'list': serializer = super(BlogViewSet, self).get_serializer(*args, *kwargs) serializer.fields['articles'] = serializers.PrimaryKeyRelatedField(many=True, read_only=True) serializer.is_valid() return serializer i just wanted to override the corresponding articles field with a PrimaryKeyRelatedField, so only id´s get shipped. But i get empty results(no blogs and articles at all) and i have no idea why... any ideas or suggestions? thanks and greetings! -
How to make django to recognize two urls?
I am totally new in Django and web programming and I do not even know how to ask this question precisely enough. Excuse me then if I am asking for something obvious. I am trying to put in the same folder app two different urls in one urls.py file. I noticed that Django does not recognize them and always open the first one. This is my app urls.py file: from django.conf.urls import url from second_app import views urlpatterns = [ url(r'^$', views.help, name='help'), url(r'^$', views.index, name='index'), ] This is my prooject urls.py file: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', include('second_app.urls')), url(r'^help/', include('second_app.urls')) ] and here is my views.py that is common for both pages: from django.shortcuts import render from django.http import HttpResponse def help(request): help_dict = {'help_insert':'HELP PAGE'} return render(request, 'second_app/help.html', context=help_dict) def index(request): my_dict = {'insert_me':'INDEX'} return render(request, 'second_app/index.html', context=my_dict) And now, when I am trying to request http://127.0.0.1:8000/help, everything works fine I can see the "HELP PAGE" but when I reqest http://127.0.0.1:8000/index nothing changes. How can I fix it? Thanks in advance! -
create() argument after ** must be a mapping, not list, Django REST Framework (implementing my own create method error)
when I am implementing this code-example on the documentation (I had to implement the create method myself because I have nested objects and inserting them is not supported by default) def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user https://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations I'm getting this error create() argument after ** must be a mapping, not list My implementation of the example on my project is the following : def create(self, validated_data): product_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) Product.objects.create(product=product, **product_data) return product the whole serializers.py file from rest_framework import serializers from products_and_categories.models import Product, Category from django.db import models class CategorySerializer(serializers.ModelSerializer): def to_representation(self, obj): if 'categories' not in self.fields: self.fields['categories'] = CategorySerializer(obj, many=True) return super(CategorySerializer, self).to_representation(obj) class Meta: model = Category fields = ("name", 'products', 'categories') class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Product fields = ("product_code", "name", "quantity", "price", 'categories') def create(self, validated_data): product_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) Product.objects.create(product=product, **product_data) return product my models.py file: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) categoriesId = models.ForeignKey('self', related_name='categories',on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): product_code = models.CharField(max_length=255) name = models.CharField(max_length=255) price = models.IntegerField() quantity = models.IntegerField() categories = models.ManyToManyField(Category, related_name='products') can anybody … -
Django ORM GroupBy Date Ranges
I need some help on creating a Queryset in Django. If not possible, I'd go with simple iterations in python to get my results, but I'd like to get my hands on these advanced queries and understanding this one would be a great start. Don't know if that would be possible, but thanks in advance. Say we have this simplified situation: class Sell(models.Model): sku = models.ForeignKey('Product', on_delete=models.CASCADE) value = models.FloatField() amount = models.FloatField() date = models.DateField(auto_created=True, blank=True) class Promo(model.Model) name = models.CharField(max_length=100) date_start = models.DateField() date_end = models.DateField() And to use examples, let's say we have: Sell - SKU001 - 40,00 - 2units - 05/1/2018 Sell - SKU004 - 20,00 - 2units - 12/1/2018 Sell - SKU003 - 10,00 - 2units - 05/3/2018 Sell - SKU004 - 20,00 - 1units - 17/3/2018 Sell - SKU005 - 30,00 - 1units - 25/3/2018 And for the Promo Instances: Promo - NewYear - date_start 01/01/2018 - date_end 01/03/2018 Promo - FunMarchSales - date_start 01/03/2018 - date_end 01/04/2018 My Django Query should get the date_ranges from Promo and use them to GroupBy the sells returning the earnings. Something like this: New Year - 120,00 FunMarchSales - 70,00 -
Django Python mod_wsgi: ImportError: No module named 'django'
I'm trying to set up a Django-Python environment in Ubunt16.04u server but I get the Apache error: "ImportError: No module named 'django'" I've installed Python 3.7, virtualenv (sudo pip install virtualenv), Django (pip install Django), mod_wsgi (sudo make install). Which could be the reason of the issue? //Apache Error Log File [Wed Nov 21 17:45:07.572605 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] mod_wsgi (pid=60818): Target WSGI script '/var/www/django_virtualenv/progetti_django/curriculum/curriculum/wsgi.py' cannot be loaded as Python module. [Wed Nov 21 17:45:07.572638 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] mod_wsgi (pid=60818): Exception occurred processing WSGI script '/var/www/django_virtualenv/progetti_django/curriculum/curriculum/wsgi.py'. [Wed Nov 21 17:45:07.572758 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] Traceback (most recent call last): [Wed Nov 21 17:45:07.572805 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] File "/var/www/django_virtualenv/progetti_django/curriculum/curriculum/wsgi.py", line 17, in <module> [Wed Nov 21 17:45:07.572812 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] from django.core.wsgi import get_wsgi_application [Wed Nov 21 17:45:07.572824 2018] [wsgi:error] [pid 60818] [remote 192.168.224.1:56398] ImportError: No module named 'django' //Apache Config File <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's … -
How to force/warn the way other developers treat some class/django model
We have a Django project and I came across this problem multiple times this year. I will simplify the example: class MyModel(Model): my_attr = .... ... def get_my_attr_safe(): if not self.my_attr: return somecalculation() return self.my_attr I want to force developers to use get_my_attr_safe() instead of my_attr. It's a huge and complicated model. My idea was to somehow override __getattribute__ and raise Exception if it's called directly but I don't think this would work. Moreover, Django, of course needs to call sometimes ModelFields directly so I can't just do it this way. I want to either raise Exception or make sure they will get the information that they have to use the method if possible. For example I need them to use the method everywhere in templates: {{ obj.get_my_attr_safe }} instead of {{ obj.my_attr }} The solution doesn't have to be Pythonic, maybe there is a way to do this using PyCharm only. It would be enough. -
How to check if Django ValidationError subclass was raised?
Let's assume I have a Django model: class MyDjangoModel(models.Model): name = models.CharField(max_length=200) attribute = models.IntegerField() class CustomValidationError(ValidationError): pass def clean(self): if self.attribute < 1: raise CustomValidationError("Attribute should be > 1!") if len(self.name) > 20: raise ValidationError("Name too long!") I would like to create model instance and validate it: inst = MyDjangoModel(name="Foo", attribute=0) try: inst.full_clean() except CustomValidationError as e: print("Hello!") But the code above will never print "Hello!" because full_clean method is raising only ValidationError. Can anyone suggest, how to call full_clean and check if ValidationError subclass exception was raised? -
djChoices download issue in CMD
I can't download djChoices from https://pypi.org/project/djChoices/ unsing pip install djChoices. I getting error in cmd ERROR -
Having a dynamic rest view duplicates the user-list url
(I have a custom user model) I do not understand why this is happening. These are my expected urls: python manage.py show_urls /api/v1/ rest_framework.routers.APIRootView api-root /api/v1/\.<format>/ rest_framework.routers.APIRootView api-root /api/v1/users/ users.views.UserCreateViewSet user-list /api/v1/users/<pk>/ users.views.UserViewSet user-detail /api/v1/users/<pk>\.<format>/ users.views.UserViewSet user-detail /api/v1/users\.<format>/ users.views.UserCreateViewSet user-list As soon as I include in my urls.py a view based on DynamicModelViewSet: from dynamic_rest.viewsets import DynamicModelViewSet class AggregateViewSet(DynamicModelViewSet): pass My user-list urls are duplicated: » python manage.py show_urls /api/v1/ rest_framework.routers.APIRootView api-root /api/v1/\.<format>/ rest_framework.routers.APIRootView api-root /api/v1/users/ users.views.UserCreateViewSet user-list /api/v1/users/ users.views.UserViewSet user-list /api/v1/users/<pk>/ users.views.UserViewSet user-detail /api/v1/users/<pk>\.<format>/ users.views.UserViewSet user-detail /api/v1/users\.<format>/ users.views.UserCreateViewSet user-list /api/v1/users\.<format>/ users.views.UserViewSet user-list This is my (simplified) urls.py: from django.urls include from rest_framework.routers import DefaultRouter # from consumption.views import AggregateViewSet router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'users', UserCreateViewSet) urlpatterns = [ path('api/v1/', include(router.urls)), ] Activating that from consumption.views import AggregateViewSet statement makes the problem appear. It does not even need to be registered to the router: just importing the view is breaking the urls. Why is dynamic-rest mangling the urls just by being imported? -
Django 1.11 - Use Model to query a clone table
I have a table core_people and a backup table: core_people_01 Is it possibile to use People Django model to make a query on the "clone" table? Something like this: People.objects.get(pk = 123).table("people_01") Im searching online without success. -
Django view rendered with formset errors causes a ton of queries
Is there a way to minimize the number of queries when a view is rendered with inlineformset_factory errors? class CustomerProductForm(forms.ModelForm): class Meta: model = CustomerProduct # m2m through fields = ('product', 'unit', 'price') CustomerTemplateFormSet = inlineformset_factory( Customer, CustomerProduct, fk_name='customer', form=CustomerProductForm) If product and unit are foreign keys (plus customer) a formset consisting of 50 forms rendered with errors will cause 50 duplicate queries for each field. Is there some way to optimize? -
Python - Django - Pass serializer and attribute as argument
currently i am dealing with this snippet: def to_representation(self, instance): representation = super().to_representation(instance) representation['categories'] = CategorySerializer(instance.categories, many=True).data return representation Now i would like to make the snippet representation['categories'] = CategorySerializer(instance.categories, many=True).data more generic, so i can pass any field and its corresponding serializer here, like: representation[config['field']] = config['serializer'](instance[getattr(instance, config['field'])]).data but it crashed totally, anybody ever dealed with this kind of generic setup? thanks and greetings! -
understanding QuerySet of Django Permissions
Am new to Django, have been working on linking some permissions to groups and then adding users to those groups. Have managed some of that so far, but am stuck on understanding exactly what is going on with the permissions. Here is my attempt so far: (Django-1.11.4-env) $ python manage.py shell Python 3.6.7 (default, Oct 25 2018, 13:09:20) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.auth.models import Permission >>> p = Permission.objects.all() then >>> p.values <bound method QuerySet.values of <QuerySet [<Permission: MyApp | user | Can add user>, <Permission: MyApp | user | Can write stuff.>, <Permission: MyApp | user | Can change user>, <Permission: MyApp | user | Can delete user>, <Permission: admin | log entry | Can add log entry>, <Permission: admin | log entry | Can change log entry>, <Permission: admin | log entry | Can delete log entry>, <Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | permission | Can add permission>, <Permission: auth | permission | Can change permission>, <Permission: auth | permission | Can delete permission>, … -
Django-storages does not see the GOOGLE_APPLICATION_CREDENTIALS environment variable.
I am using Django Storages to work with Google Cloud Storage to service static and media files. I have set the required GOOGLE_APPLICATION_CREDENTIALS, but django fails to see it, and returns an Attribute Error. you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. I also added the environment variable to /etc/environment/, tried export GOOGLE..., set the environment in my Gunicorn run command with a -e param, and specified it in a .env file alongside my manage.py, with my other secrets. I am using ubuntu 18. -
Populating a Postgresql database with an API from url
I am tasked with populating an existing database with info from a Jira API within a web app made with django/python. I am not asking for a full answer but just want to know where i should start. I have started thinking of retrieving data from the url serving JSON and putting that into a .csv file and then populate the table that way, but was wondering if there is a more efficient way of doing this. If there is any reference or advice you could give me on where to start that would also be great. -
Display Age from date of birth
I need help with displaying an age when I enter a date of birth. I have tried this JS method but I cannot get it to display. <div class="kidsFormCenter"> {% for kid in kids %} <table class="kidsTable kidForm"> <form action="{% url 'update_profile_kid' kid.id %}" method="post"> {% csrf_token %} <tr> <td>First name:</td> <td><input type="text" value="{{ kid.name }}" name="name"></td> </tr> <tr> <td>Date of Birth:</td> <td><input type="text" maxlength="10" value="{{ kid.dob }}" name="dob"></td> <td><input type="text" id="age" class="form-control" required readonly></td> </tr> <tr> <td>Gender:</td> <td><input type="text" maxlength="1" value="{{ kid.gender }}" name="gender"></td> </tr> <tr> <td><button class="btn btn-primary" formaction="{% url 'update_profile_kid' kid.id %}" type="submit">Edit</button> <form action="{% url 'delete_profile_kid' kid.id %}" method="POST"> {% csrf_token %}<button class="btn btn-info" formaction="{% url 'delete_profile_kid' kid.id %}" type="submit">Delete</button></td> </form> </tr> </form> </table> <br> {% endfor %} </div> And my age.js is $(function() { $('input[name="dob"]').daterangepicker({ singleDatePicker: true, showDropdowns: true }, function(start, end, label) { var years = moment().diff(start, 'years'); $("#age").val("You are " + years + " years old."); }); }); I want the age of the child to be displayed. -
Filter models with created date less than today's date
So i have a model, And i want to filter all models with created date less than today's date . For example Class Post(models.Model): created=model.DateField() view.py get_objects_with_date_lessthan_today_date=Post.objects.filter(created=) In my view i need to filter all models with created date less than today's date .Please i need help . In going about this logic -
Why django rest framework's serializer won't systematically validate model before save
When we compare code in django form and django rest framework's serializer, the last only validates fresh data from request, then launches immediately Model.save() instead of full_clean() used by django form. Sometimes we need to check data in actual model instance before save, but in this case, an override of serializer's run_validation/create/update should be used in order to call model instance's validation by self.instance.clean/full_clean/..., like class MySerializer(serializers.ModelSerializer): field = serializers.ReadOnlyField(source='xxx') class Meta: model = MyModel fields = (...) read_only_fields = (...) def run_validation(self, data=empty): self.instance.clean() return super(MySerializer, self).run_validation(data=data) Such that I feel discouraged to call model's validation in serializer. Maybe I'm using it wrongly, so what's the philosophy here ? Thanks. -
django deployment on GCP with kubernetes
I finally got my first django project and i need help in deploying it in GCP with kubernetes. i've never deployed any project before so it's a bit frustrating for me with the client nagging on my head. it's an E-learning platform so i want to use GCP with kubernetes (for CI/DI since there will be a lot of updates for the project) and Google cloud storage for storing media files. ps: this is my first question so be easy on me -
Django: Access form_kwargs in init
I defined form_kwargsand I am able to access them directly in my __init__ in forms.py. I expected to do organizer = kwargs.pop('organizer') etc. Can anyone explain me why it's possible that I access these kwargs directly even so they should be stored inside form_kwargs? I'm currently trying to replicate this behaviour to my class BaseReserveFormSet(BaseFormSet): but there I can't access them without kwargs.pop @cached_property def formset(self): ReserveFormSet = formset_factory( ReserveForm, formset=BaseReserveFormSet, extra=0 ) return ReserveFormSet( data=( self.request.POST if self.request.method == 'POST' else None ), initial=self.tickets, form_kwargs={ 'organizer': self.request.organizer, 'event': self.request.event, 'user_order_reference': self.request.session.get('order_reference'), 'discount_code_session': self.discount_code, } ) forms.py class ReserveForm(forms.ModelForm): class Meta: model = ReservedItem fields = ['ticket', 'quantity'] def __init__(self, organizer, event, user_order_reference, discount_code_session, *args, **kwargs): self.organizer = organizer self.event = event [...] -
Standard for application-specific template directories in Django?
I guess this is a question related to best practises in Django development. I'm trying to build a web service with a main page (base.html) that contains multiple apps. I would like to make the apps self-contained, so I've made a templates directory in each app, and would also like to take advantage of the template inheritance feature of Django to make this whole thing as fluid as possible. Now my concern is, where should I put the base.html in my project, so that the system knew where to find it? Also, what changes should I make in the settings.py file in order for the system to be able to connect the templates? Is there a standard or a known method that takes minimal effort for this sort of arrangement? -
How to list available authentication backends for a Django user?
I have a project that uses Python 3.6 and Django 1.11 where I use the built-in User model. The user objects are all inside the default database (which is postgres), but the project uses a second authentication backend because some users need to be authenticated against a legacy Oracle database. # settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', # new postgres DB 'project_config.auth_backends.OtherBackend', # legacy Oracle DB ] This works fine so far, but now I have 3 groups of users: some users can only authenticate in ModelBackend because they are not in the legacy DB (because they are new users). some users can only authenticate in the legacy DB; they have usr.has_usable_password() == False because they have not set their password in the new postgres DB yet. some users can authenticate in both backends, maybe even with different passwords in each one; this is because they changed their password in the new system, but by design that change is not transmitted back to the legacy DB (don't shoot me, the only way to change the password in the legacy DB is to do it manually through the user interface). For auditing purposes, I want to list all users and see which … -
How can I delete a records out of the django-database by using confirm in JavaScript?
I have a model named Actie in models.py. This is my template I rendered by a view. The context I passed: {'actie': Actie.objects.all(), 'user': request.user} Actie is just a model in models.py. {% for actie in actie %} {% if actie.actie_gebruiker.id == user.id %} <tr onclick="window.location.href={{ actie.id }}"> <td>{{ actie.id }}</td> <td>{{ actie.actie_naam }}</td> <td>{{ actie.actie_status.status_naam }}</td> <td>{{ actie.actie_aanmaakdatum|date:"d-m-y [ H:i ]" }}</td> <td>{{ actie.actie_einddatum|date:"d-m-y" }}</td> <td>{{ actie.actie_eindtijdstip|date:"[ H:i ]" }}</td> <td>{{ actie.actie_gebruiker }}</td> </tr> <a id="verwijderenButton" href="" onclick="bevestigVerwijdering();"><img class="icontje" src="{% static 'MyApp/verwijderen.png' %}"></a> <script> function bevestigVerwijdering() { var actie_id = '{{ actie.id }}'; var antwoord = confirm("Are you sure you want to delete this?"); if (antwoord == true) { document.getElementById('verwijderenButton').href = 'verwijderen/' + actie_id + '/'; alert(actie_id); alert(document.getElementById('verwijderenButton').href); } } </script> {% endif %} {% endfor %} Now what I want this code to do is that when I click on the image, that it deletes that specifc record out of the database. It deletes nothing when I don't click on the first record. It deletes the last record when I click on the first record. This is my view: def verwijderActie(request, id): Actie.objects.filter(id=id).delete() return HttpResponseRedirect('../../')