Home > Back-end >  Django API Framework for POST not working?
Django API Framework for POST not working?

Time:10-07

I have the following code:

models.py

class DeviceDetail(models.Model):
    
    SUBNET_CHOICES = (
    ('16','16'),
    ('17', '17'),
    ('18','18'),
    ('19','19'),
    ('20','20'),
    ('21', '21'),
    ('22', '22'),
    ('23', '23'),
    ('24', '24'),
    ('25', '25'),
    ('26', '26'),
    ('27', '27'),
    ('28', '28'),
    ('29', '29'),
    ('30', '30'),
    )

    DEV_MODS =(
        ('Catalyst 9606R', 'Catalyst 9606R'),
        ('C9300L-48T-4X', 'C9300L-48T-4X')
    )

    
    mgt_interface = models.CharField(max_length=50)
    subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES)
    ssh_id = models.CharField(max_length=50)
    ssh_pwd = models.CharField(max_length=50)
    enable_secret = models.CharField(max_length=50)
    dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement
    DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables
    
    def __str__(self):
        return self.hostname

serializers.py

class DeviceDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = DeviceDetail
        fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod']

views.py

@api_view(['PUT'])
def update_device(request, pk=None):
    if pk != None:
        devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)
        devdserializer = DeviceDetailSerializers(devicedetail, data = request.data)
        if devdserializer.is_valid():           
            devdserializer.save() 
            results = {            
                "device_details" : devdserializer.data,
            }
            return Response(results, status=status.HTTP_201_CREATED)        
        return Response(devdserializer.errors, status=status.HTTP_400_BAD_REQUEST)

The code seems correct to me but whenever i tried to use Postman to do the PUT, i get error of 500. I dont understand why is this happening. For the code, I am using https://www.youtube.com/watch?v=B65zbFro2pU to guide me on how to code as I am new to this framework. Can anyone advise me on what to do to solve this error? Thank you very much.

Here is my traceback in powershell:

Internal Server Error: /devicelist/196/update
Traceback (most recent call last):
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "C:\Intern\django_swing\interface\views.py", line 1036, in update_device
    devdserializer.save()
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\serializers.py", line 200, in save
    self.instance = self.update(self.instance, validated_data)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\serializers.py", line 970, in update
    info = model_meta.get_field_info(instance)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\utils\model_meta.py", line 35, in get_field_info
    opts = model._meta.concrete_model._meta
AttributeError: 'QuerySet' object has no attribute '_meta'

CodePudding user response:

Use:
devicedetail = DeviceDetail.objects.get(DD2DKEY=pk)
instead of
devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)

Because filter will return a list of objects and get will return one object In your case, you are just updating one instance.

If you want to update all instances then use

devdserializer = DeviceDetailSerializers(devicedetail, data = request.data,many=True)
  • Related