Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the config file in TravisCI to run Django?
I am new to TravisCI and have written the following text in .travis.yml: language: python python: - 3.6 env: - DJANGO=2.0.2 script: - python manage.py test I am trying to run a build for a Django-project. The build runs, but for some reason it fails because TravisCI thinks it is a Ruby-project. This is not strange as, when I press "view config", I see that it is written for Ruby (also see screenshot below): { "language": "ruby", "group": "stable", "dist": "trusty", "os": "linux" } Does anyone know how to change this config-file to fit for Django? So that my .travis.yml file can run correctly? -
Django Admin DateTime field - combine now/today?
On Django Admin, if your model has a DateTimeField, this is displayed as 2 inputs, one for date and one for time, with a Today link next to the date which sets to current day, and a Now link next to time, which sets the current time. This means if a user wants to set the date & time to the current date and time, they have to click 2 links. Is there any way to just have one link that sets both? -
Django unique_together is not working
class model_name(models.Model): pk = models.AutoField(primary_key=True, auto_created=True) field1 = models.ForeignKey(model1, on_delete=models.CASCADE) field2 = models.ForeignKey(model2, on_delete=models.CASCADE) field3 = models.ForeignKey(model3, on_delete=models.CASCADE) field4 = models.IntegerField() class Meta: unique_together= (('field1', 'field2', 'field3'),) db_table = "table_name" whenever I give data from Django admin app it says that it already exists. it works fine there but when I give it manually it starts taking duplicates. I have added the unique_together constraint but it still takes the duplicates for particular fields. what should I do to stop taking the already existing data? I use mysql database Any solution is appreciated. Thanks. -
Django Rest Framework updating nested m2m objects. Does anyone know a better way?
I have a case when user needs to update one instance together with adding/editing the m2m related objects on this instance. Here is my solution: class MySerializer(...): def update(self, instance, validated_data): actions_data = validated_data.pop('actions') # Use atomic block to rollback if anything raised Exception with transaction.atomic(): # update main object updated_instance = super().update(instance, validated_data) actions = [] # Loop over m2m relation data and # create/update each action instance based on id present for action_data in actions_data: action_kwargs = { 'data': action_data } id = action_data.get('id', False) if id: action_kwargs['instance'] = AdditionalAction.objects.get(id=id) actions_ser = ActionSerializerWrite(**action_kwargs) actions_ser.is_valid(raise_exception=True) actions.append(actions_ser.save()) updated_instance.actions.set(actions) return updated_instance Can anyone suggest better solution? P.S. actions can be created or updated in this case, so i can't just use many=True on serializer cause it also needs instance to update. -
Configure OIDC with Google Oauth
I am trying to use the Oauth server from google with mozilla-django-oidc. However I don't know exactly what should I use in these parameters OIDC_OP_AUTHORIZATION_ENDPOINT = "" OIDC_OP_TOKEN_ENDPOINT = "" OIDC_OP_USER_ENDPOINT = "" Currently I am trying this: OIDC_OP_AUTHORIZATION_ENDPOINT = "https://accounts.google.com/o/oauth2/auth" OIDC_OP_TOKEN_ENDPOINT = "https://accounts.google.com/o/oauth2/token" OIDC_OP_USER_ENDPOINT = "http://127.0.0.1:8000/oidc/callback/" But I am getting HTTPError: 400 Client Error: Bad Request for url: https://accounts.google.com/o/oauth2/token Any idea what I am doing wrong? -
How to Conditionally render a Link Column with Django Tables 2?
With the following table when returning the BoundColumn it is plain text and not html. class CarHistoryTable(tables.Table): edit = tables.LinkColumn( 'Car:update', kwargs={'pk': A('id')}, orderable=False, text='Edit' ) def render_edit(self, record, value, bound_column): if record.state != Car.NEW: return '' return super().render_edit() Ideally I want to return an empty text for Cars that are not NEW state. For other cars I would like to render the edit link. -
Django account_activation_token.check_token always return False in constant_time_compare()
I have an ActivationTokenGenerator that create a token that will be used for account verification that will be send by email. For example I configured it like this with parameters including timestamp, id, and user active status: from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class ActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) account_activation_token = ActivationTokenGenerator() Then I use the account_activation_token for generating token in a verification email I sent with a send_mail. @classmethod def send_email(cls, request, user): current_site = get_current_site(request) mail_subject = 'Activate your Poros account.' message = render_to_string('email_verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() Everything looks perfect email sent with a token that included inside a url with pattern like this: url(r'activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), and looks like this in the email: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} then when the link clicked it will call this activate view: from django.http import HttpResponse from django.contrib.auth import login from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from accounts.utilities import account_activation_token from accounts.models import User def activate(request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) print(id) user = User.objects.get(pk=id) print(user) except(TypeError, ValueError, … -
Django pagination erorr, getting redirected to first page
I have been struggling with this for few days now. I finally found the issue. I have a Course model from which I display all my courses. I also have a filter of those courses with whom I can display them sorted by faculty. I wanted to have a pagination for those courses filtered by faculty, so I added it. Problem is, if I click on next page, I get redirected to all courses page. Why is that happening ? Can my jQuery script have something to do with that ? I use it to display courses by faculty. https://i.imgur.com/Ft4qeX2.png <div class="jumbotron"> <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> </div> {% if courses1 %} {% for faculty in faculties %} <div id="fac_{{ faculty.pk }}_tab" style="display:none;"> <h3> {{ faculty.name }} Courses</h3> <ul> {% for department in faculty.department_set.all %} {% for study in studies %} {% if study.department == department %} {% for course in courses1 %} {% if course.study_programme == study %} <li> <a class="first" href={{ course.slug }}>{{ course.name }}</a> </li> {% endif %} {% endfor %} {% endif %} {% endfor %} {% endfor %} </ul> … -
Django admin search by foreign key too slow
I have two models in Django: class Dog(models.Model): nick = models.CharField(max_length=30, db_index=True) class Bark(models.Model): date_of_bark = models.DateTimeField(default=datetime.utcnow) pet = models.ForeignKey('Dog', related_name='bark_dog', on_delete=models.CASCADE) In admin form, I want to search all the Barks of a specific Dog: class BarkAdmin(BaseAdmin, BaseActions): paginator = MyPaginator list_display = ('id', 'date_of_bark', 'pet') search_fields = ('pet__nick, ) In my database, every Dog has millions of Barks. The problem is that every search takes a lot of time: Load times (aprox): Load of table : Instant Search results: 15 seconds In order to improve the time, I ordered the search field: class BarkAdmin(BaseAdmin, BaseActions): paginator = MyPaginator list_display = ('id', 'date_of_bark', 'pet') search_fields = ('pet__nick, ) ordering = ('pet__nick',) And now we have these load times (aprox): Load of table : 15 seconds Search results: Instant How can I improve both times simultaneously? -
python3+django2: attempted relative import beyond top-level package
I have a directory structure as: -code |-helper.py |-django_site |-manage.py |-polls |-views.py In views.py I did: import sys sys.path.append("..") from ..helper import * def index(request): do_something So when I run python manage.py runserver, I have the error "ValueError: attempted relative import beyond top-level package". How should I resolve the problem? Thanks a lot, -
How to add the operations before the result
I have 338 classes and for each classes 6 operations. If i am clicking on any class name it is directly showing the data of only one operation. How can I add the option so after clicking on the operation it will give me the respective data related to that operation. I'm working on Django and HTML. Below is my code: <nav1> <ul> {% block content1 %} {% for class in response_data %} <li><a href= "/{{class}}/" name='class' value={{class}}>{{class}}</a></li> {% endfor %} {% endblock %} </ul> </nav1> <div class="btn-group btn-group-lg"> <button type="button" class="btn btn-primary">Enumerate</button> <button type="button" class="btn btn-primary">Get</button> <button type="button" class="btn btn-primary">Invoke</button> </div> -
Django select a valid choice error when populate select in the template
I get a validate error when I create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) then I populate the select in the template using ajax: $.ajax({ url: '/endpoint/load_areas/', type: 'post', dataType: 'json', data: { 'postcode': postcode }, headers: { 'X-CSRFToken': "{{ csrf_token }}" }, success: function (data) { var ret = JSON.parse(data.result); for (x in ret) { $("#area_select").append(new Option(x, ret[x])); } }, error: function(data) { alert("error"); } }); Finally, when I submit the form I get the following error: area_sp: Select a valid choice. 26835 is not one of the available choices. Any idea? -
How to incorporate data from two distrinct sources in a single serializer?
I'm trying to serialize some objects whose data is stored in 2 databases, linked by common UUIDs. The second database stores personal data, so is run as a segregated microservice to comply with various privacy laws. I receive the data from db2 as a decoded list of dicts (rather than an actual queryset of model instances) How can I adapt the ModelSerializer to serialize this data? Here's how I can get the data: # returns a list of dict objects, approx representing Person.__dict__ personal_data_list = Microservice.objects.custom_filter(uuid__in=uuids) Here's an example serializer that I'm trying to use, with ??? showing where I don't know how to link the personal_data_list into the source attribute: class PersonSerializer(serializers.ModelSerializer): personal_stuff = serializers.CharField(source='???', read_only=True) class Meta: model = Person fields = ('uuid', 'personal_stuff') def get_personal_stuff(self, obj): return obj.get('personal_stuff') I've shown the microservice field I'm interested in above as personal_stuff. I don't know if there's a nice DRF way to link the two. I definitely don't want to be sending (potentially thousands of) individual requests to the microservice by including a single request in get_personal_data. The actual view just looks like this: class Persons(generics.ListAPIView): model = Person serializer_class = PersonSerializer def get_queryset(self): self.kwargs.get('some_filter_criteria') return Person.objects.filter(some_filter_criteria) Where should the … -
Can't able Retrieve data from JSON file using Angular js
I am not able Retrieve data from JSON file using Angular js. Am trying to get the json data from URL using click function in angular js and also i got the empty row output in table . var app =angular.module('sampleapp', []) app.controller("tablejsonCtrl", function ($scope, $http) { $scope.jsonclick = function () { var url = "http://127.0.0.1:8000/static/waste/test.json"; $http.get(url).then( function(data) { $scope.students = data; }); } }); <!doctype html> <html lang="en" ng-app="sampleapp"> <head> {% load staticfiles %} <!-- <meta charset="utf-8"> --> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'waste/angular.min.js'%}"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="{% static '/bootstrap/js/app_ang.js'%}"></script> <div class="col-sm-12" ng-controller="tablejsonCtrl"> <button class="clickbutton" value="10" ng-click="jsonclick();">Show-json</button> <table rule="all" class="table table-bordered table-hover "> <tr> <th>Name</th> <th>Price</th> <th>Description</th> <th>Calories</th> <th>isbest</th> </tr> <tr ng-repeat="stuednt in students"> <td>{{stuednt.name}}</td> <td>{{stuednt.price}}</td> <td>{{stuednt.description}}</td> <td>{{stuednt.calories}}</td> <td>{{stuednt.isbest}}</td> </tr> </table> </div> </body> </html> -
trying to convert this mssql query to django
I've been trying to convert this query SELECT coalesce(SUM( PortFixedIncApp.PrincipalBalance + (PortFixedIncApp.PrincipalBalance * PortFixedIncApp.DailyInterestrate * DATEDIFF(day, PortFixedIncApp.LastDateOfInterestAccruals,'2016-02-05')) + PortFixedIncApp.InterestBalance),0 ) AS MarketValue FROM PortFixedIncApp WHERE (PortFixedIncApp.TransStatus = 'Active') AND PortFixedIncApp.AccountNo='3051010000401' AND (PortFixedIncApp.EndDate <='2016-02-05') and this is what I tried to do in django Portfixedincapp.objects.filter(Q(transstatus="Active")& Q(accountno="{0}".format(custaccountno))& Q(enddate__lte=today)).aggregate(market_value=\ Coalesce(Sum(F("principalbalance")+(F("principalbalance") * F("dailyinterestrate") * arrow.get(F("lastdateofinterestaccruals")).date() - today) + F("interestbalance"), output_field=models.IntegerField()),0)) I get this error when i run can't parse single argument type of '<class 'django.db.models.expressions.F'>' -
Securing production Django App
I am new to the deployment aspect of Django applications. I will probably use Heroku or PythonAnywhere for eventual deployment of my application. However, before I do this I need to achieve two specific tasks. When in deployment the python files in fact any files must not be able to be modified externally. (So compression?) If possible I'd like to be able to package my Django project into one .exe file. (If even possible at all). I have read about .pyc files I think this may be an option but if anybody could offer up some options to me and or explain the ins and outs of .pyc files that would be a great help. -
django2 + python3: TemplateDoesNotExist
I know there are multiple questions on this site about this problem, but I cannot find a solution. I am using Python 3.6 (anaconda) + django 2.0.2 on Windows 10. I am following the tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial03/ Here is my views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import * def index(request): content = 'abcxyz' context = {'content': content} return render(request, 'polls/index.html', context) I created a file index.html in the folder polls\templates\polls My settings.py: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_site.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have a problem of 'TemplateDoesNotExist' - it seems to me that django tries to look for a template in django.template.loaders.app_directories.Loader: /mnt/e/workspace/capec-processing/code/django_site/polls/templates/polls/templates/polls/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/user_name/anaconda3/envs/capec/lib/python3.6/site-packages/django/contrib/admin/templates/polls/templates/polls/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/user_name/anaconda3/envs/capec/lib/python3.6/site-packages/django/contrib/auth/templates/polls/templates/polls/index.html (Source does not exist) I am not sure what did I do wrong, because I followed the tutorial on … -
Set value of a model field that is not part of model form
I have a model like this class Income(models.Model): value = models.DecimalField(max_digits=10, decimal_places=2) remitted = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) I have a form like this class EditIncomeForm(forms.ModelForm): class Meta: model = Income fields = ("value", ) def clean_value(self): value = self.cleaned_data["value"] if self.value < self.remitted: raise forms.ValidationError("Error message") return value Now in the modelform, how do I update the value of the remitted field? I can't seem to be able to access the remitted field this way. I'm on Django 2.0 -
Django ModelChoiceField choices not updating
Well, I'm stuck in that problem for quite long now. Went to read some question / answers and blog, and at this point I don't understand why this is not working. I'm gonna make my example as simple as possible. Let's say I have a ModelMultipleChoiceField : myfield = ModelMultipleChoiceField( queryset=SomeObject.objects.none(), label='', widget=forms.CheckboxSelectMultiple( attrs={ 'class': 'mtlz-checkbox-group', 'label': 'some label: ' } ), required=False ) I set my queryset to none cause I need to compute the result dynamically. Note that this is in a ModelForm and that this field is a field of my object that I needed to custom (with some custom widget). Well now i'm changing the queryset in the __init__() method : def __init__(self, *args, **kwargs): super(EquipeForm, self).__init__(*args, **kwargs) self.base_fields['myfield'].queryset = self.method() Here self.method() is a method that's computing my queryset, and it's working fine. So, whatever, the choices were not getting updated except when I refresh (just pressing f5, not cache and stuff). Continuing my reading, I read that self.base_fields['myfield'].widget.choices were cached and so I had to force the "refresh" too in my init : def __init__(self, *args, **kwargs): super(EquipeForm, self).__init__(*args, **kwargs) self.base_fields['myfield'].queryset = self.method() self.base_fields['myfield'].widget.choices = self.base_fields['myfield'].choices Using a pdb, I saw the choices were … -
Django What really is compress and decompress in MultiValueField
For past 6 - 7 hours I have been stuck on understanding how actually these things work. Actually right now I am working on creating dynamic multiValueField Forms by using Formset factory and setting max_num to some value. I am able to create dynamic form but when it comes to extracting data from form then I am not able to understand that how I can decompress values from MultiValueField When I try to iterate over forms and print them, then I notice that compress method is called but how can I explicitly call it. In simple words how it actually works ? -
NoReverseMatch with Regex when Trying To create Email from Template that takes an url as the parameter
I'm trying to send email from Django using gmail to gmail. with a send_mail: @method_decorator(csrf_exempt, name='dispatch') class AuthenticationView(View): @classmethod def send_email(cls, request, user): current_site = get_current_site(request) mail_subject = 'Activate your Poros account.' message = render_to_string('email_verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() Then I set url patterns for my app like this below: from django.conf.urls import url from django.urls import path from .views.activation import activate from .views import UserView, ProfileView, AuthenticationView urlpatterns = [ path('users/', UserView.as_view()), path('auth/', AuthenticationView.as_view()), path('profiles/<str:pk>/', ProfileView.as_view()), url(r'activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), ] and will included by the project urls: from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls'),) ] and the activate view is coming from an activate() like this below: from django.http import HttpResponse from django.contrib.auth import login from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from accounts.utilities import account_activation_token from django.contrib.auth.models import User def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. … -
Search endpoint with ViewSet & Routers in Django-REST-FrameWork
Views.py class ClientViewSet(ModelViewSet, GetOrRaiseMixin): serializer_class = ClientSerializer queryset = Client.objects.all() def list(self, request): serializer = ClientSerializer(self.queryset, many=True) return JsonResponse(serializer.data, status=HTTP_200_OK, safe=False) def retrieve(self, request, pk=None): client = self.get_or_raise('Client', pk) serializer = ClientSerializer(client) return JsonResponse(serializer.data, status=HTTP_200_OK) def create(self, request): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=HTTP_200_OK) else: return JsonResponse({'error': 'Invalid'}, status=HTTP_400_BAD_REQUEST) def destroy(self, request, pk=None): client = self.get_or_raise('Client', pk) client.datetime_deleted = datetime.now() client.save() return JsonResponse(serializer.data, status=HTTP_200_OK) Urls.py router.register('clients', ClientViewSet, base_name='clients') urlpatterns = [ path('api/', include(router.urls)), ] Problem Above works great for standard behaviour like create / retrieve_all / retrieve_by_id / update_by_id / delete_by_id. But what I want is to add an additional enpoint for search_&_retrieve. For example: /api/clients/search/?title='John'&age='32' etc. So generally I need 5 endpoints: Create/Retrieve/Update/Delete/Search Can I achieve that with "ViewSet+Routers" concept or I need to do something else ? -
get user role and add that to jwt payload
I have user login Serializer like below I want to add user role to my jwt payload when user is authenticated how can I access user info for example "is_stuff" field in my validate function ? user object contain <QuerySet [<User: admin>]> class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only=True) username = CharField(required=False, allow_blank=True) email = EmailField(label='email address', required=False, allow_blank=True) class Meta: model = User fields = [ 'username', 'email', 'password', 'token', 'is_staff', ] extra_kwargs = { "password": { "write_only": True } } def validate(self, data): user_obj = None email = data.get('email', None) username = data.get('username', None) password = data.get('password') if not email and not username: raise ValidationError("email or username is required!") if '@' in username: email = username user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() # user = user.exclude(email__isnull=True).exclude(email__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this username/email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("password is incorrect") payload = jwt_payload_handler(user_obj) payload["role"] = ??? data['token'] = jwt_encode_handler(payload) return data view: class UserLoginApiView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
Django Signup form validation
i have signup form in django which has only 3 fields(username ,password and confirm password) created using default userCreationForm with default input fields validations.Signuppage now i want to write test case for those validation logic in picture. how to write it? i have done basic tests which are as follows tests.py class SignUpPageTests(TestCase): username = 'sampleuser' email = 'sampleuser@email.com' def test_signupStatusCheck(self): resp = self.client.get('/accounts/signup/') self.assertEqual(resp.status_code, 200) def test_signupViewName(self): resp = self.client.get(reverse('signup')) self.assertEqual(resp.status_code, 200) def test_signupViewFile(self): resp = self.client.get(reverse('signup')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp,'signup.html') def test_signupFormTest(self): self.newuser = get_user_model().objects.create_user( self.username,self.email ) self.assertEqual(get_user_model().objects.all().count(),1) self.assertEqual(get_user_model().objects.all() [0].username,self.username) self.assertEqual(get_user_model().objects.all()[0].email,self.email) Signup.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Sign up</button> </form> {% endblock %} -
Serializer for inherited model
I have following models declared: class Parent(models.Model): active = models.BooleanField(default=False) class Child(Parent) name = models.CharField(max_length=100, unique=True) and serializer: class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = ('active', 'name') At glance everything seems to be ok, it's correctly generated in the browsable api. Neverthless when I want to update both fields only 'active' is updated. When I do put in return I receive correct resonse: { "active": true, "name": "foo" } But the name field is not updated at all. I went further and tried to implemented custom update method in the serializer: def update(self, instance, validated_data): print(str(type(instance))) return instance After that in a put response I'm receiving only active field ?: { "active": true, } And on console even more astonishing: rest_1 | <class 'applic.models.Person'> I'm completely lost :) Why on earth serializer treats explicitly provided Child model as a Person ? How to force ChildSerializer to work on Child model ? Thank you in advance Piotr