Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Email codes from a defined list using Django and dealing with concurrency
I have a simple Django Rest server api that gets a post request by another app (a payment processing client). Every post triggers an email with one access code already defined by this model: class AccessCode(models.Model): code = models.CharField(max_length=64, blank=True) sent = models.BooleanField(blank=True, default = False) The general idea is for my view to query this model, get the top AccessCode, mark it as sent and send the email. Obviously I need to deal with concurrency. I'm thinking on a pessimistic approach, querying the database inside an atomic transaction and using select_for_update. class send_code(APIView): def post(self,request): with transaction.atomic(): code = AccessCode.objects.select_for_update().filter(sent=false).first() code.sent=True account.save() // send email with the code return True The thing is, during one active transaction, I don't really understand how the next requests will wait for the query to be release. Will this approach work with parallel post requests without expecting a lot of them to be rejected? -
differentiate object vs instance
some one call model object, some one call model instance. any one tell me what is the difference between this two with example. model.py '''' class Todo(models.Model): name = models.CharField(max_length=100) due_date = models.DateField() def __str__(self): return self.name '''' forms.py '''' class TodoForm(forms.ModelForm): class Meta: model = Todo fields = ['name','due_date'] '''' views.py '''' def todo_list(request): todos = Todo.objects.all() context = { 'todo_list':todos } return render(request, "todoApp/todo_list.html", context) '''' CASE 2: consider this example code.(comment = form.instance) what is form instance ? '''' class PostDetailView(DetailView): model = Post def post(self, *args, **kwargs): form = CommentForm(self.request.POST) if form.is_valid(): post = self.get_object() **comment = form.instance** comment.user = self.request.user comment.post = post comment.save() return redirect('detail', slug=post.slug) return redirect('detail', slug=self.get_object().slug) '''' -
Django: OperationalError at /admin/store/customer/ no such column
enter image description here I'm getting the following error when I make changes in the admin page: OperationalError at /admin/store/customer/ no such column: store_customer.email In the admin page, there is a Customer column, where I can add or edit customer's information. I was able to access the admin page but whenever I click to the Customer s page it gives me an error. Please feel free to comment for any suggestions or advice. I'm still fairly new to Django workframe. Here are my codes below: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False,null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True, blank=False) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer … -
Django project 'Improperly Configured: Requested settings INSTALLED APPS' Error
I need help to solve this error which raises when I try to run any python script with Django code. This is the error: ****PS C:\Users\pebr6\Desktop\tutorial> & c:/Users/pebr6/Desktop/pythonEnvironments/1.0/Scripts/Activate.ps1 (1.0) PS C:\Users\pebr6\Desktop\tutorial> & c:/Users/pebr6/Desktop/pythonEnvironments/1.0/Scripts/python.exe c:/Users/pebr6/Desktop/tutorial/aplicaciones/principal/models.py Traceback (most recent call last): File "c:/Users/pebr6/Desktop/tutorial/aplicaciones/principal/models.py", line 5, in <module> class Person(models.Model): File "C:\Users\pebr6\Desktop\pythonEnvironments\1.0\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\pebr6\Desktop\pythonEnvironments\1.0\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\pebr6\Desktop\pythonEnvironments\1.0\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\pebr6\Desktop\pythonEnvironments\1.0\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\pebr6\Desktop\pythonEnvironments\1.0\lib\site-packages\django\conf\__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before acces**sing settings.****** My project structure is the following: Project structure This is my apps configuration on settings.py: Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'aplicaciones.principal', ] The manage.py file has the next code inside: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tutorial.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc … -
Access Foreign Key Field in Django
This is my models.py file: class Appointment(models.Model): time = models.TimeField(auto_now_add=False, auto_now=False, null=True, blank=True) date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) employees = models.ForeignKey(User, on_delete=models.CASCADE, null=True) location = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.location class Patient(models.Model): first_name = models.CharField(max_length=60, null=True) last_name = models.CharField(max_length=60, null=True) appointments = models.ForeignKey(Appointment, on_delete=models.CASCADE) def __str__(self): return self.first_name In views.py I am trying to access the first_name of a Patient object, based on Appointment. So, for example, let's say that I have an appointment with a known id, and I want to get the first_name of the patient who has that appointment. How would I do this in Django? I know only how to access a patient's appointment, but I can't figure out how to access an appointment's patient. -
Thumbnails don't load after moving to S3
The thumbnails (sorl-thumbnails) in my django app no longer load after I setup my S3 bucket to host both my uploaded media files as well as my static files. I get errors like this: ModuleNotFoundError at / No module named 'app' Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.6 Exception Type: ModuleNotFoundError Exception Value: No module named 'app' Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 973 If I turn off debug mode (THUMBNAIL_DEBUG setting), none of the media images load but the static images, css, and javascript load just fine. Settings.py: # Amazon S3 settings and variables AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = '******' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' AWS_S3_CUSTOM_DOMAIN='%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage' STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) storage_backends.py: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False If I change DEFAULT_FILE_STORAGE back to storages.backends.s3boto3.S3Boto3Storage, the errors go away for some of the pages but not all. The uploaded media images still don't show up though. I can get the … -
Messy Urls When Using Regex
Im using django allauth and originally users could visit their profiles by visiting website/profile, the urls.py being path('profile/', include('users.urls')). I later decided that I want users to view other users profiles so figured Id need to change the urls.py to path(r'^profile/(?P<user_id>[\w-]+)/$', include('users.urls')). The thing is, now when a user visits a profile, instead of a nice, clean url like website/profile/user1 it's something like this website/%5Eprofile/(%3FP1%5B%5Cw-%5D+)/$. This may not be a problem, but id prefer a clean url in the address bar of my website, and think it may a sign that my implementation is incorrect. Thank you. -
How delete 'empty' model instances (to which no one refers to)
I have two models: class Parent: .... class Child: owner = models.ForeignKey(to=Parent) apart from using pre_save signal on Child is there a way in Django to delete 'Empty' parents: those to which no children belong, for instance when a child is detached from a Parent and reattached to another one, so that the initial parent gets 'childless'? -
defectdojo remote database connection
Trying to connect defectdojo (docker-compose install) to remote MySQL5.7 and postgresql databse always fails setting the environment variables (DD_DATABASE_HOST, user,password etc.) does not help changing variables in docker-compose.yml occurs this error stacktrace ========================================================================================== File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 408, in get uwsgi_1 | self.model._meta.object_name uwsgi_1 | django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. Does anyone installed defectdojo with a remote MySQL or postgresql successfully ? Or is there a way to configure it with setup.bash ??? -
Leaflet draw not working with Django - shape never finishes
My Django app just started having a weird problem where when I try to draw a shape on a map with Leaflet and Leaflet draw, the shape never finishes. That is, when I click and drag to draw a shape, the shape draws, then when I release the mouse, the shape looks finished but a new shape immediately starts drawing (with the mouse released). If I press "esc" the shape looks finished. But, the web console has the error: MouseEvent.mozPressure is deprecated. Use PointerEvent.pressure instead. leaflet.js:5:268 I tried updating django-leaflet from pip. I'm not sure where else leaflet.js would be coming from (it's not a static file). I'm using a MacBook, tried with track pad and USB mouse. Anyone know how this started happening and how I can fix it? Bizarre that it was working and now is not without me changing anything. Here's some relevant code: {% load leaflet_tags %} {% leaflet_css %} {% leaflet_js %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css"/> <script src="http://leaflet.github.io/Leaflet.draw/leaflet.draw.js"></script> map.on(L.Draw.Event.CREATED, function (e) { console.log('created'); //Never prints to console var type = e.layerType; var layer = e.layer; map.addLayer(layer); geoJSON_obj = layer.toGeoJSON(); if (type === 'circle') { var rad = layer.getRadius(); geoJSON_obj.properties.radius = rad; } var jsonObj = JSON.stringify(geoJSON_obj); … -
Django static file updates on browser
I am currently using django and matplotlib to display charts on the web page. The way I use matplotlib is I save the chart as a static file in Django then load it in the view templates. This chart is drawn with the data in the database which gets updated on regular basis. However, the problem I'm facing is that the chart image won't get updated unless I stop running the Django server, perform collectstatic and re-run the server. Is there a way to update the static image on the server during runtime? Thank you in advance. -
getting 403 Forbidden for every update of a post in django
i am trying to create an updateView using class based view to my blog_post whenever i hop in to any post-detail and to the update url like is http://127.0.0.1:8000/pages/blog/15/update/ i get a 403 Forbidden error in which i only want each users to update their blogpost which they wont be able to update other users blogpost but my tesc_func is not applying what i asked for tho i am using CustomUser model so i dont know if that will change the way i will write in my tesc_func here is my code, views.py class BlogUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Blog fields = ['title', 'categories', 'overview', 'thumbnail', 'summary'] def form_valid(self, form): form.instance.user = Doctor.objects.get(user=self.request.user) return super().form_valid(form) def test_func(self): blog = self.get_object() if self.request.user == blog.user: return True return False urls.py path('blog/<int:pk>/update/', BlogUpdateView.as_view(), name='blog-update'), -
Python/Django - Uploading large files to CDN speed issues
I am building an app that allows users to upload video submissions for specific events. The video file is handled with django-videokit which uses ffmpeg and mediainfo to get the dimensions, length, mimetype, and create a thumbnail. It then sends the video to a celery task to create an mp4. I am using a digitalocean droplet, nginx, and gunicorn to serve the website. Originally, I was storing, serving and processing all the videos from the droplet. I recently moved my static and media files to a Spaces bucket and use django-storages. It seems like a sacrificed a lot of speed on the uploads for what I think is the "greater good". After moving to the CDN, when the file upload reaches 100% the page sits idle with the loading wheel while I assume it sends the file to the CDN? What is the best way to manage storage and processing of large video files? Is there a way to store them locally and then set up an overnight celery task to move them to the CDN? -
Django Rest Framework serializer is ignoring the model instance im trying to serialize
I´m trying to create an instance of a serializer on a POST request, but it is ignoring the model instance im passing as the first argument if request.method == 'POST': if string_pk in reviewed_user_pk: reviewed_user = User.objects.get(pk=user_pk) review = Review(author=user, reviewed_user=reviewed_user) serializer = ReviewSerializer(review, data=request.data) I get user instance from the request: try: user = request.user except user.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) The problem here is that the instance of Review which has both user instances (author and reviewed_user) is being ignored by the ReviewSerializer, here is the serializer: class CreateReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = ['author', 'reviewed_user','title', 'rating', 'comment', 'date_published'] The oter fields in request.data are being serialized but not the Review instance, what can be causing this problem? the error i get from serializer.errors is the following: { "author": [ "This field is required." ], "reviewed_user": [ "This field is required." ] } Here is the complete function view: @api_view(['POST']) @permission_classes((IsAuthenticated,)) def api_create_review_view(request, user_pk): #user_pk is the pk of the reviewed_user try: user = request.user except user.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) reviewed_user_pk = user.worked_with.split(',') string_pk = str(user_pk) data = { } if request.method == 'POST': if string_pk in reviewed_user_pk: reviewed_user = User.objects.get(pk=user_pk) review = Review(author=user, reviewed_user=reviewed_user) serializer = ReviewSerializer(review, data=request.data) … -
MEDIA_URL not working in Django templates
I'm building a project in Django 3, but the images aren't linking in the files. All images are store in a folder called media & here's the HTML for my logo for example - <a class="navbar-brand" href="{% url 'index' %}"> <img src="{{ MEDIA_URL}}logo.png" height="70" class="pr-4" alt="Site logo"> Then I've this in my settings - STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in my project level URLS I've got - from django.conf import settings from django.conf.urls.static import static + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Make Heading Width Match The Table Below
I have a <h2> tag above a <table> and a @media (max-width: 1500px) in my css file. When the screen is small, the table overflows from its div, popping out further than the elements above. This is fine. My problem is that Id like the <h2> above it to match the width of the table. Please see the image for clarification. html <div id="notifications"> <table class='notifications_table'><div> <h2 class='notifications_heading'>Notifications</h2> {% for notification in queryset %} <tr> <td>{{ notification.actor }}</td> <td>{{ notification.verb }}</td> <td>{{ notification.timestamp|date }}</td> </tr> {% endfor %} </table> </div> css #notifications { float: right; width: 500px; position: relative; margin-right: -840px; } @media (max-width: 1500px) { #notifications { float: right; width: 260px; margin-right: -290px; margin-top: 290px; } } .notifications_heading { background: #79aec8; } .notifications_table { width: 100%; } https://imgur.com/kVZHq29 Thank you. -
Send to different emails based on ChoiceField
I want to have my contact form send to different emails based on the department the user chooses. Right now I'm just trying to print the department the user has picked but I'd like to set up some conditionals to send to different emails based on the department value. This gives me KeyError at /contact/ 'DEALERSHIP ENQUIRIES' forms.py from django import forms class ContactForm(forms.Form): DEPARTMENT_CHOICES = ( ('SALES ENQUIRIES', 'Sales Enquiuries'), ('DEALERSHIP ENQUIRIES', 'Dealership Enquiuries'), ('JOB ENQUIRIES', 'Job Enquiuries'), ('ALL OTHER QUESTIONS', 'All Other Questions'), ) name = forms.CharField(max_length=255) sender_email = forms.CharField(max_length=255) phone = forms.CharField(max_length=255) subject = forms.CharField(max_length=255) department = forms.ChoiceField(choices = DEPARTMENT_CHOICES, widget=forms.Select(), required=True) message = forms.CharField(required=True, widget=forms.Textarea(attrs={'rows': 8})) views.py def contact_view(request): form = ContactForm if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = f'Message from {form.cleaned_data["name"]}' message = form.cleaned_data["message"] sender = form.cleaned_data["sender_email"] phone = form.cleaned_data["phone"] department = form.cleaned_data["department"] print(form.cleaned_data[department]) context = { "form": form, } return render(request=request, template_name='main/contact.html', context=context) -
How to redirect to external link without quiting current domain?
I want to redirect to external link without quiting current domain link. Following is an example of my question : https://translate.google.com/translate? depth=1&hl=ar&prev=search&rurl=translate.google.com&sl=en&sp=nmt4&u=https://bookboon.com/ As you can see the main website here is google translate and second is bookbone.com How can we do that with python using a framework like Django2.0? Thank you. -
django filter multi select list in admin
I have a django model with a self referencing many to many field as below. class Product(ModelBase): name = models.CharField(max_length=1000) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) alternatives = models.ManyToManyField('self', symmetrical=False, blank=True) I am not particularly happy with the django admin form which lists the options for alternatives as a multi-select list box, as with a large number of products it will become tedious to select an alternative product or products. Is there a way I can enrich this user experience, I have looked at django-advanced-filters but it doesnt work with django 3. Essentially, if I could have a typeahead search to filter through the items in the list and also limit the initial list based on the category selected. Thanks for the help. -
fakeredis between multiple django views
I have a test which involve multiple Django views It seems that the fakeredis isn't shared between multiple views I tried running the following code: import fakeredis from testfixtures import Replacer class TestWithFakeRedis(TestCase): def setup_redis(self, test_func): fake_redis = fakeredis.FakeStrictRedis() with Replacer() as replace: replace('app1.views.redis_connection', fake_redis) replace("app2.views.redis_connection", fake_redis) replace("app2.views.redis_connection", fake_redis) test_func(fake_redis) def test_something(self): def test_func(redis_connection): # some testing coded here pass self.setup_redis_and_kafka(test_func) the fakeredis can't be passed between multiple views and it's something that I need Thanks in advance, Nadav -
Django Admin: Possible to add element on list_display?
I've got a model which is fairly simple. I would like to be able to add elements to this quickly through the admin list_display page. Is this possible? class QlLevel(models.Model): points = models.PositiveIntegerField(default=0, blank=False, null=False) level = models.PositiveSmallIntegerField(default=0, unique=True, blank=False, null=False) qp_earned = models.PositiveIntegerField(default=0, blank=False, null=False,) In admin.py I've got: class QlLevelAdmin(admin.ModelAdmin): list_display = ['id', 'level', 'points', 'qp_earned'] list_editable = ['level', 'points', 'qp_earned'] admin.site.register(QlLevel, QlLevelAdmin) This gives me ability to edit in the list_display page. How can I also add some TabularInlines of the same class? (currently getting error: 'Accounts.QlLevel' has no ForeignKey to 'Accounts.QlLevel' when I try to add inlines = [QlLevelInline]) -
Adding Pagination to Django-Photologue
At the moment Photologue is showing me 4 rows with 5 pictures on each row. I tried modifying it so I only see 5 pictures at once. I tried using paginate_by = 5 and put it in views.py and urls.py. But neither worked. Can anyone offer suggestions on how to customize the number of rows and columns that are shown? views.py from photologue.views import PhotoListView from braces.views import JSONResponseMixin class PhotoJSONListView(JSONResponseMixin, PhotoListView): paginate_by = 5 def render_to_response(self, context, **response_kwargs): return self.render_json_object_response(context['object_list'],**response_kwargs) urls.py from django.urls import path from .views import PhotoJSONListView from photologue.views import GalleryListView urlpatterns = [ path(r'^photolist/$', PhotoJSONListView.as_view(paginate_by=5), name='photologue_custom-photo-json-list'), path(r'^gallerylist/$', GalleryListView.as_view(paginate_by=20), name='photologue_custom-gallery-list'), ] -
Is there a way to restrict access to django webpages unless accessed through a specific link?
I'm trying to build a multiple choice web application using django web framework. Is there any way to make a webpage accessible only through a specific link? -
Multiple (same) Many-To-One raltions in same model
I got a model Device. Each Device has 3 sensors which have there own color, status etc.. So I created a class Sensor where I need to store all the sensor data. Now I want in my Device model an attribute for each sensor that is connected with the Sensor model so I can retrieve the data. What's the best way to do this? Doing it like this?: in Device model for each sensor: light_sensor = models.ForeignKey( Sensor, on_delete=SET_NULL, blank=True, null=True, ) or in Sensor model: class Sensor(models.Model): device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="devicesensor" ) status = models.CharField(max_length=25, blank=False) color = models.CharField(max_length=25, blank=False) -
Django Token and Session auth
I was creating a Login For Custom User model is work fine with django , now i try to convert into Rest . It is creating the token but it doesnot return the token and Session is also blank (generation token but serializer.data is blank) enter image description here (Session db is empty) enter image description here django Serializer.py class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=False, allow_blank=True, write_only=True, label="Email " ) password = serializers.CharField( required=True, write_only=True, style={'input_type': 'password'} ) class Meta(object): model = User fields = ['email', 'password'] def validate(self, data): email = data.get('email', None) password = data.get('password', None) if not email: raise serializers.ValidationError("Please enter email to login.") user = User.objects.filter(Q(email=email)).exclude(email__iexact="").exclude(email__isnull=True).distinct() if user.exists(): user1 = authenticate(email=email, password=password) if user1 is not None: if user1.is_active: token, created = Token.objects.get_or_create(user=user1) data['token'] = token else: raise serializers.ValidationError("Account not active.") else: raise serializers.ValidationError("Invalid credentials.") else: raise serializers.ValidationError("This email is not valid.") return data Django view.py class UserLogin(views.APIView): permission_classes = (permissions.AllowAny, ) serializer_class = UserLoginSerializer def post(self, request): serializers = self.serializer_class(data=request.data) print(serializers) if serializers.is_valid(raise_exception=True): print("data", serializers.data) return Response(serializers.data, status=status.HTTP_200_OK) return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)