Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django viewflows - Defining an API flow
I've an API endpoint, /api/create/. This creates a new entry in the DB depending upon the payload received from the client. Payload - { 'field1': 'value1`, 'field2': 'value2`, 'field3': 'value3`, 'field4': 'value4`, 'type': 'A' } Now depending on the type, I've a specific workflow. For eg:- Type A needs to perform certain tasks before saving the data, Type B has its own set of operations. I don't have any UI, just the requests coming over the POST request. How can I use django-viewflows for such a use-case? -
Django raise not getting called
//forms.py : //This is the forms part of my app. from django import forms from django.contrib.auth import ( authenticate, login, get_user_model, logout, ) User=get_user_model() class UserLoginForm(forms.Form): username=forms.CharField() password=forms.CharField(widget=forms.PasswordInput) def clean(self): username=self.cleaned_data.get('username') password=self.cleaned_data.get('password') user=authenticate(username=username,password=password) if not user: raise forms.ValidationError("This user does not exist") if not user.check_password(password): raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean() // views.py : //views part where in , i used the UserLoginForm created in the form. from django.shortcuts import render from django.contrib.auth import ( authenticate, login, get_user_model, logout, ) from .forms import UserLoginForm def login_view(request): if request.method=='POST': form=UserLoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get("username") password=form.cleaned_data.get("password") return render(request,"accounts/home.html") else: form=UserLoginForm() return render(request,"accounts/login.html",{"form":form}) def register_view(request): return render(request,"form.html",{}) def logout_view(request): return render(request,"form.html",{}) //login.html : //login.html which opens up as home page. <div> <form method='POST' action=''>{% csrf_token %} <input type="text" name="username" placeholder="Username"/> <input type="password" name="password" placeholder="Password"/> <input type="submit" value="Login"/> </form> </div> There are no errors, but neither the raise errors show up on invalid //stuff nor the page redirects to home.html on valid user. Please help me fix the problem. I am unable to find the problem. -
How to get selected radio button choice in django form?
I've a form class ScoreUpdateForm(forms.Form): answer_id = forms.IntegerField() given_score = forms.FloatField() CHOICES = [('calculated_score', 'Calculated Score'), ('given_score', 'Given Score')] final_score = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) I want to get values of the selected choice in my view after the post. -
Accessing data in GET form and posting to results page (Django)
I'm trying to create a form that takes inputs and uses these inputs to create an output that's posted to a results page. I've searched everywhere and can't understand how to post the data (in the case below, 'country' and 'culture') to the results_view. # view.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from form.forms import InputForm def get_list(request): if request.method == 'GET': form = InputForm(request.GET) if form.is_valid(): country = form.cleaned_data['country'] culture = form.cleaned_data['culture'] return results_view(form) else: form = InputForm() return render(request, 'form/index.html', {'form': form}) def results_view(form): text = form.restaurant c = {'output' : text} return render(form, 'form/results.html', c) and # forms.py from django import forms class InputForm(forms.Form): country = forms.CharField(label='country', max_length=100) cuisine = forms.CharField(label='cuisine', max_length=100) How can I access the inputs and use them as the text in 'results_view'? Additionally, if I want to pass these results as an input argument for another python function (say a function that maps country name to latitude and longitude), how can I incorporate this into views.py? Thanks a lot! -
How do I display the views output on my template in tabular rows?
I am using Django as my web framework. I have written a views function like this.. to fetch a list of all items under the keys UserId and AccountNum from an AWS DynamoDb table : def dsctbl2(request): dynamodb=boto3.client('dynamodb', region_name='us-west-2') response = dynamodb.scan( TableName='User-Account') filtered = response['Items'] length = len(filtered) for k in range(length): accnum = filtered[k]['AccountNum']['S'] uid = filtered[k]['UserId']['S'] f = dict(AccountNum=accnum,userID=uid) rows = [] for k,v in f.items(): rows.append(k) rows.append(v) return render(request,'useradd.html',{"rows": rows}) The rows variable yields a set of lists like this : ['AccountNum', '873627867348', 'userID', 'abc'] ['AccountNum', '873627867348', 'userID', 'def'] ['AccountNum', '038683828978', 'userID', 'ghi'] ['AccountNum', '581889263266', 'userID', 'jkl'] ['AccountNum', '581889263266', 'userID', 'mno'] ['AccountNum', '581889263266', 'userID', 'pqr'] ['AccountNum', '581889263266', 'userID', 'stu'] ['AccountNum', '977201296795', 'userID', 'vwx'] ['AccountNum', '232686542773', 'userID', 'yza'] I need to display these values in my table in my HTML template. The HTML table snippet is below : <div class="mytable"> <table style="width:96%" class="table table-responsive"> <thead id="head" class="mdb-color lighten-4"> <tr> <th></th> <th class="th-lg">Account #</th> <th class="th-lg">User Id</th> </tr> </thead> <tbody> <tr> <th scope="row"></th> <td>{{rows.AccountNum}}</td> <td>{{rows.UserId}}</td> </tr> </tbody> </table> </div> But when I hit that html page in my browser , I can see only the table headings 'UserId' and 'AccountNum'. Why aren't the UserId and AccounNum values getting … -
Python Django error : version GLIBC_PRIVATE not defined
I have a python Django project. When I run its manage.py script as manage.py unserver, I get following import error. ImportError: /home/xxxxx/Projects/Dev/yyyy/ENV/new_env/lib/python2.7/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init, version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference What may be the reason? -
Keeping a computed model field up-to-date via QuerySets
Preface: Let's assume we are working on a DB that stores issues of magazines. Those issues usually do not have a 'name' per se; instead a whole bunch of attributes (release year, serial number, release months, etc.) will contribute to the name the user may later on identify the issue with. Depending on the attributes available per issue, this name will be calculated based on a pattern. For example: an issue from the year 2017 with number 01 will get the name: 2017-01. An issue from the years 2000 and 2001, and the months Jan and Feb will get the name 2000/01-Jan/Feb. The attributes can be changed at any time. It is expected that the user can also do queries based on this name - so simply displaying the computed value (through __str__) is not enough. What I have done so far: For a long time, I actually calculated the name every time __str__ was called on the issue's instance. It was the quick and dirty (and slow) way. Querying for the name was very slow and rather complicated and unreliable as it required 'reverse-engineering' the __str__ method and guessing what the user was trying to search for. Then I … -
jwt rest framework returning user id with token
I'm using jwt-rest-framework for user authentication, and I would like to return a user_id with token. There are some examples on how to do it when using django-rest-framework, so according to this example I've tried to override ObtainJSONWenToken jwt view and did the same thing from rest_framework.authtoken.models import Token from rest_framework.response import Response from rest_framework_jwt.views import ObtainJSONWebToken # Create your views here. class CustomObtainJSONWebToken(ObtainJSONWebToken): """ Return user id with token """ def post(self, request, *args, **kwargs): response = super(CustomObtainJSONWebToken, self).post(request, *args, **kwargs) token = Token.objects.get(key=response.data['token']) return Response({'token': token.key, 'id': token.user_id}) But the Traceback is pointing out to the token it self: Traceback: File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.5/contextlib.py" in inner 30. return func(*args, **kwds) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/home/copser/.virtualenvs/iToucan-BackHand/lib/python3.5/site-packages/rest_framework/views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "/home/copser/Documents/iToucan-BackHand/iToucan/itoucan/rest_auth/views.py" in post 15. token = Token.objects.get(key=response.data['token']) The question is what is the proper way of returning user_id with the token, … -
Is there any module in python for converting markdown to pdf
In my application, I want to give the response in PDF format. Tried one module markdwon2pdf, that didn't work -
How to provide proper request body to serialize Django Generic Foreign Key?
I have a generic model called 'Phone': (my_project/apps/phones/models.py) class Phone(Model): owner_name = CharField(max_length=50) number = CharField(max_length=20) content_type = ForeignKey(ContentType, on_delete=CASCADE) object_id = PositiveIntegerField() phone_object = GenericForeignKey('content_type', 'object_id') I also have a model called 'Client': (my_project/apps/clients/models.py) class Client(Model): employee = ForeignKey(Employee, on_delete=CASCADE) title = CharField(max_length=50) phones = GenericRelation(Phone) I also have a serializer for 'Client': (my_project/apps/clients/serializers.py) class ClientSerializer(ModelSerializer): id = IntegerField(read_only=True) employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True) title = CharField(required=True) I followed drf-documenation (http://www.django-rest-framework.org/api-guide/relations/#generic-relationships), and as I understood I need to put custom class in the same file, so here is how my clients/serializers.py looks like: (my_project/apps/clients/serializers.py) class ClientSerializer(ModelSerializer): id = IntegerField(read_only=True) employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True) title = CharField(required=True) class PhoneObjectRelatedField(RelatedField): def to_representation(self, value): if isinstance(value, Client): serializer = ClientSerializer(value) else: raise Exception('Unexpected type of phone_object') return serializer.data For requests I am using PostMan, so here is my request to Create new Client with phone number: But it does nothing, new Clients can be created successfully but they just don't contain any phone numbers, please help! -
django connection to mongo and postgres
Hi there i need to connect to mongo and postgres in django to do crud operations on it here is the code of the project that it´s on git hub. here is the file where i made the conections to mongodb isn´t working https://github.com/defStacker/shop_Django/blob/master/untitled/settings.py this is the link of the project https://github.com/defStacker/shop_Django -
Django - Channels 2.0: Unable to connect to consumer
I'm doing some tests before migrating from Channels 1.x to 2.x; my original code ingests the values of csv files into the database. However I'm currently unable to establish a connection to the consumer. settings.py ASGI_APPLICATION = "UbiosData.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } routing.py from channels.routing import ProtocolTypeRouter, ChannelNameRouter from .consumers import TestConsumer application = ProtocolTypeRouter({ "channel": ChannelNameRouter({ "somename": TestConsumer, }), }) consumers.py from channels.consumer import SyncConsumer class TestConsumer(SyncConsumer): def websocket_connect(self, event): print("websocket_connect") self.send({ "type": "websocket.accept", }) def websocket_receive(self, event): print("websocket_receive") self.send({ "type": "websocket.send", "text": event["text"], }) def test_send(self, message): print("Entering consumer") print(message["text"]) views.py def test_channels(request): channel_layer = get_channel_layer() print(channel_layer) channel_layer.send("somename", { "type": "test.send", "text": "test" }) return render(request, "data/data_index.html") Result of print statement in the test_channels function: RedisChannelLayer(hosts=[{'address': ('localhost', 6379)}]) The print statements in the consumer are not executed, and I get no error message. I'm using Python 3.5.3, channels 2.0.2 and channels-redis 2.0.2 -
How do I use python's cprofile with Django on the development server?
I tried using the Python tool cProfile. If I do unit tests on my files (I usually have a set of test routines if the module is invoked from the CLI in python) then doing python -m cProfile -o outputfilename myfile.py gives me meaningful output I can examine from within the Python interactive mode after importing cprofile and doing the usual stuff, leading to stats.print_callers('foo') giving meaningful reports about functions with 'foo' in them. However, if I try to do this with the Django server, by doing python -m cProfile -o outputfilename manage.py runserver and using the web app, I get a load of stuff in the file...but I can't find the references to my actual code/function calls. All of the profiling seems to be loaded with endless Django internals. In fact, it looks to me like Django uses the builtin exec() function a whole lot, and I am led to believe my code is getting executed via that path and doesn't get captured. First off, is this how Django works on the development server, and is it the same for production? That seems like using exec() a lot is a major potential security issue. But, more important, how can … -
generic relation model declaration
Just a quick noob question. Do I need to have content_type, object_id, and content_object every time I use GenericRelation in models? I get the concept behind generic relation but I'm confused on how to implement it. Below is the setup. Address - a generic content type; to be used in different models. Company - a simple model that uses address generic content type. Person - a simple model that uses address generic content type. Is it essential to have these 3 attributes in all models? Thanks in advance! -
How do i get field data from "through" ManyToMany object?
I have been having trouble on how to get that "group" data in ProductInsideCombo, this is a ManyToMany object that is linked with "through". I need to get the "group" data, Please help. This is what i tried: for one_product in the_product.products_inside_combo.all().order_by('products_inside_combo__id'): try1 = one_product.group # fail try2 = one_product.products_inside_combo__group # fail too! product_id = one_product.id These are my two models: @python_2_unicode_compatible class ProductInsideCombo(models.Model): parent = models.ForeignKey('Product', related_name='+') child = models.ForeignKey('Product', verbose_name="Products inside the combo", related_name='+') group = models.CharField( max_length=255, choices=( ('group_1', 'Group 1'), ('group_2', 'Group 2'), ), default='group_1', ) def __str__(self): return str(self.id) @python_2_unicode_compatible class Product( models.Model ): name = models.CharField(verbose_name="Name"), max_length=255) slug = models.SlugField(verbose_name="Slug"), max_length=255, unique=True) price = models.PositiveIntegerField(verbose_name='Price', null=True, blank=True) sale_price = models.PositiveIntegerField(verbose_name="Sale Price", null=True, blank=True) products_inside_combo = models.ManyToManyField('self', through='ProductInsideCombo', symmetrical=False, help_text="Only for Combo Products", blank=True) created = models.DateTimeField(default=now) modified = models.DateTimeField(editable=True, auto_now=True) def __str__(self): return "%s" % (self.sku, ) class Meta: verbose_name = "Product" verbose_name_plural = "Products" -
django - InstagramClientError: (404) Unable to parse response, not valid JSON
I have been given the task to replicate a django web app to make it run on a server and a vm running ubuntu server 16.04. Followed all necessary steps to set up the existing django project. After running the command python manage.py runserver it runs with no issues. When I browse to localhost:8000 it throws the aforementioned error: ERROR django.request handle_uncaught_exception Internal Server Error: / Traceback (most recent call last): File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/xenomader/slowtours_testenv/slowtours-bak/front/views.py", line 99, in home medias = insta.get_feed() File "/home/xenomader/slowtours_testenv/slowtours-bak/api/insta.py", line 13, in get_feed medias, next_ = api.user_recent_media(user_id=1304858935, count=8) File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/instagram/bind.py", line 197, in _call return method.execute() File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/instagram/bind.py", line 189, in execute content, next = self._do_api_request(url, method, body, headers) File "/home/xenomader/slowtours_testenv/env3/local/lib/python2.7/site- packages/instagram/bind.py", line 131, in _do_api_request raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status']) InstagramClientError: (404) Unable to parse response, not valid JSON. A few people have had similar issues in the past but I just don't see any answer that suits me to solve this problem. I am a junior software developer and I am completely new to python … -
How to insert a videos on a web page using django framework?
I want to create a web page using Django which has a videos inserted into it. Can some one please help me in creating such a page from the start? -
Using wagtail + intermediate / through tables for M2M relations
Is there a way of deferring creation of intermediate through tables on a ParentalManyToManyField of a Page model in wagtail? Basic example: class MyPage(Page): field = ParentlManyToManyField(ModelB, through='OrderedModelB', ...) field2 = ParentalManyToManyField(ModelC, through='OrderedModelC', ...) class OrderedModelB(models.Model): page = models.ForeignKey(MyPage) field = models.ForeignKey(ModelB) order = models.PositiveIntegerField() class Meta: ordering = ['order'] From the example above what I'm trying to do should be pretty clear... I have a page which can consists of ManyToManyField's - which require ordering. But, to do this you have to create the intermediate table... However, since pages can go under moderation you wouldn't want to create these intermediate relations on "publishing" the page. As I understand it this would cause querying the pages (ordered) M2M relations to always return the most recent - which may not be approved or in a draft. So, how can you preserve these relationships + wagtails page revision system? Even then.. You'd still want users editing their pages to see the updated orders they specify which makes this a bit more difficult? -
Installing and using panda library in django application
I am trying to build the front-end structure of the energy usage user interface for my university. This requires retrieving data about each building's energy usage that is stored in excel sheets. Unfortunately, when I try to load the excel sheets, I get the following error even though I have already installed pandas: "import pandas as pd ModuleNotFoundError: No module named 'pandas'" When I tried to reinstall it in the same folder as my project, I even got: "OSError: [Errno 13] Permission denied: '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'" Please advise on how to resolve this problem. -
How to set a jinja2 variable a value from another variable
In {% set form.username = user.get_username %} I want to make form.username equal to the user's username, so when the form is sent, I know who sent it. However, it raises the error: "Did you forget to register or load this tag?" If I replace this line with {{forms.username}} it works, but it makes necessary for the user to fill the form himself, with whatever he wants, allowing him to chose write some username that is not his. file.html (is included in the home.html): <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% set form.username = user.get_username %} {{ form.file }} <button type="submit">Upload</button> views.py: from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from data.models import UserData from data.forms import UserDataForm def model_form_upload(request): if request.method == 'POST': form = UserDataForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = UserDataForm() return render(request, 'data/ranking_index.html', { 'form': form }) models.py: from django.db import models class UserData(models.Model): username = models.CharField(max_length=40) file = models.FileField(upload_to='userdata/') uploaded_at = models.DateTimeField(auto_now_add=True) forms.py: from django import forms from data.models import UserData class UserDataForm(forms.ModelForm): class Meta: model = UserData fields = ('username', 'file', ) -
Treating a model as an instance of imported class in Django
I have a class for manipulating certain data. In that class I calculate and validate the data. Then, is there a way to apply this calculation and validation to an instance of Django model? I came up with two methods. 1.Make another class to connect model and imported class. 2.Write validation and calculations directly in models.py. Which is better? Is there another good way? If 2 is good, how to do that? Here is a very simple example. # in models.py class Person(models.Modes): name = models.CharField() gender = models.CharField() age = models.IntegerField() # in other files class AboutPerson:# I want to apply this class to above model instance. def __init__(self, name, gender, age): self.name =name self.gender = gender self.age = age def validate_age(self): return self.age >= 20 I wish you could understand my poor explanation... Thank you for helping me. -
From Django, serve PDF to browser with #page=[] setting in URL
I am stuck trying to pass a parameter to a PDF rendered in the browser from Django. I think I want to serve the pdf with #page=[page_num] appended to the url the browser sees it at. This is my attempt at doing this in urls.py (note that I'm still on Django 1.11.4 and so haven't migrated to re_path for these url patterns): url(r'^files/(?P<path>.*)#page=[(?P<page_num>d+)]$', serve, {'document_root' : settings.MEDIA_ROOT}, name='file_url') This is the link in the template: <object id="pdf" width="100%" height="900" data="{% url 'knowledge_manager:file_url' document.ref_file.name document.last_open_page %}" type="application/pdf" > </object> The associated view for the whole page is a generic.DetailView. The error I'm getting is a 'no reverse match' for two parameters aimed at a two-field r.e. Reverse for 'file_url' with arguments '('documents/AutonomyinEvolution.pdf', 4)' not found. 1 pattern(s) tried: ['knowledge_manager/files/(?P.*)#page=[(?Pd+)]$'] It was working fine before I tried to add the page number. Is it worth persisting with this approach or is doing it with say javascript more realistic? -
Django: Can not understand TIME_ZONE configuration
I have tested some timezone configuration to better understand about how django timezone works. But still cannot understand how it works. Have some questions and need your helps Q1. from django.utils import timezone from datetime import datetime 1. TIME_ZONE='UTC', USE_TZ=True - datetime.now() => 2018-02-13 23:26:01.576493 // naive.. 2. TIME_ZONE='Asia/Seoul', USE_TZ=True - datetime.now() => 2018-02-13 23:26:01.576493 // tzinfo=<DstTzInfo 'Asia/Seoul' KST+9:00:00 STD> => Why in 'UTC' case return naive datetime object...? As like in 2, I think it should return the tzinfo=<UTC> object... Q2. from django.utils import timezone from datetime import datetime 1. TIME_ZONE='Asia/Seoul', USE_TZ=True - timezone.now() => 2018-02-13 23:25:32.768780 // tzinfo=<UTC> object 2. TIME_ZONE = 'Asia/Seoul', USE_TZ = False - timezone.now() => 2018-02-14 08:24:04.810045 // naive => why does timezone.now() returns tzinfo=<UTC> object in first case, even though I set the TIME_ZONE as 'Asia/Seoul'? Q3. 1. TIME_ZONE = 'Asia/Seoul', USE_TZ = False - timezone.localtime() => ValueError: localtime() cannot be applied to a naive datetime Why does it occur error even though I set a TIME_ZONE? Additionally, cannot understand what exactly USE_TZ is (its role..etc) even after reading django official docs. I think that official documentation is like, easy to read only for the one who already knows what those are.. T_T -
JS Trouble iterating over an HTMLCollection
This should be pretty straight forward. I have a loop, which works, and a variable collecting html code with getElementsByClassName. var inputs = document.getElementsByClassName('inputfile'); if (inputs) console.log(inputs); Output HTMLCollection [] 0: <input id="id_avatar" class="inputfile" name="id_avatar" data-multiple-caption="{count} files selected" multiple="" type="file"> id_avatar: <input id="id_avatar" class="inputfile" name="id_avatar" data-multiple-caption="{count} files selected" multiple="" type="file"> length: 1 It successfully finds the html piece I'm looking. Next I try to feed it through a loop. Array.prototype.forEach.call(inputs, function(input) { console.log("running"); var label = input.nextElementSibling, labelVal = label.innerHTML; }); This does not work. The loop is completely looked over, and is never executed. However if I feed var herp = ["1"]; into the loop, I will see the console print log "running". What is going on? Var inputs is valid to iterate over. Why is it being ignored and/or treated as empty? Thanks in advance. -
Update/put request in Django rest framework
I am new to Django rest framework and trying it for a new project I am working on. So based upon the official tutorial , I am trying to create several get/post/put requests but with put request but I am getting the following error. Expected view ExampleModelView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. Here are my necessary files: models.py class ExampleModel(models.Model): foo_field = models.CharField(primary_key=True, max_length=15) bar_field = models.CharField(max_length=30) last_updated_by = models.CharField(max_length=15) last_updated_on = models.DateTimeField() class Meta: managed = True db_table = 'example_db' unique_together = (('type', 'key'),) serializers.py class ExampleSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields= ('foo_field','bar_field','last_updated_by','last_updated_on') urls.py url(r'^get_reference_master/$', views.ExampleUpdateView.as_view()), url(r'^update_reference_master/(?P<type>\d+)/$',views.ExampleUpdateView.as_view()), views.py class ExampleCreateView(generics.CreateAPIView): serializer_class = ExampleSerializer queryset = ReferenceMaster.objects.all() class ExampleUpdateView(generics.UpdateAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer I think the problem I might have is that I have a composite key. I tried other generics(CreateAPIView & ListAPIView) and they work fine absolutely fine.Do I need to update the def_update method. Do I need to change anything in serializers.py? This is an existing JSON object that I got from my GET request and was trying to update: { "foo_field": "john", "bar_field": "doe", "last_updated_by": "batman", …