Reputation: 2949
I know Django automatically create a unique id for every model created. For example like this
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('email', models.EmailField(max_length=50)),
('language', models.CharField(choices=[('ur-PK', 'Urdu'), ('en-US', 'English')], max_length=15)),
],
But I want to get this id in views.py
file. How can I do this? I am using django model forms to enter data.
I tried this
request.POST['id']
But it throws an error
MultiValueDictKeyError at /
'id'
EDIT Views.py code
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST)
print(request.POST['id'])
lang=request.POST['language']
if form.is_valid():
#save form
Upvotes: 2
Views: 1783
Reputation: 121
You need to implement it in urls.py, For example:
path('<id>/', RecordDetails.as_view(), name='record_details')
And as for your code, you can get it from the 'request' or 'kwargs', Example:
class RecordDetails(generics.RetrieveAPIView):
"""
API endpoint that allows users to be viewed or edited.
"""
lookup_field = 'id'
def get_queryset(self):
request_id = int(self.kwargs['id'])
queryset = Model.objects.filter(id=request_id)
return queryset
Upvotes: 0
Reputation: 2018
In request.POST you will not get id because the record is not saved yet. so do this way
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST)
if form.is_valid():
record = form.save()
print(record.id) # this will print id
print(record.language)
Upvotes: 1