Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RelatedObjectDoesNotExist at /esacp/profile/ User has no profile in Django
So I have almost completed my Django app. But whenever I create the new user, his/her profile is not created automatically and when I open the profile after logging in, I get this error RelatedObjectDoesNotExist at /esacp/profile/ User has no profile My signals.py is below: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() My views.py of register() and profile() are below: from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your Student Account has been created! You can log in ESACP now.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your Profile information has been updated.') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } My forms.py is below: from django … -
Django - POST Form Data into API
I am new in Django and Working on the Django to POST form data to the AWS API for some automation. As i have create a form which is posting data into the database, but in the same scenario i want to post some data into the AWS API . can someone will help and guide how can we achieve this. Thanks -
How do I do a Django query on a Model, where I order by field A, but filter distinct on field B?
Suppose I have a Book table, where each book has an author field and a publishing date field. I would like to get the latest book by each author. I'm using PostgreSQL as the backend. The obvious (and wrong) solution would be: Book.objects.order_by("author", "-published_on").distinct("author").all() The problem is that while the result contains only one book from each author, then there is no guarantee that it is the latest book. This might be because I'm using random UUIDs as PKs. I can't change that. That's a requirement. The next obvious (and wrong) solution would be: Book.objects.order_by("author", "-published_on").distinct("author", "published_on").all() Here the ordering of the books is correct, but we get multiple books from the same author. I have also tried flipping around the arguments: Book.objects.order_by("-published_on", "author").distinct("published_on", "author").all() Here the ordering of the books is correct, but we get multiple books from the same author. How do I do a Django ORM query, where I get the latest book from each author? -
POST net::ERR_ABORTED 415 (Unsupported Media Type)
I'm trying to POST data from my React app to Django REST API by fetch method like this: fetch('http://127.0.0.1:8000/something/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, mode: 'no-cors', body: JSON.stringify(this.state) }) .then(response => { console.log(response) }) .catch(error => { console.log(error) }) I always get an error "POST http://127.0.0.1:8000/something/ net::ERR_ABORTED 415 (Unsupported Media Type)" and the response looks like this: "Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}". My state contains only empty strings (username: '', password: '' etc.) I've also tried to send a GET request using axios and print a response in a console: axios.get('http://127.0.0.1:8000/something/') .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error) }) But the response is: Access to XMLHttpRequest at 'http://127.0.0.1:8000/something/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:83) GET http://127.0.0.1:8000/something/ net::ERR_FAILED Have you got any ideas to fix that problem? -
How to insert values from a query to another table field?
I have a table below on my models called orders class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=1000, null=True) stock = models.CharField(max_length=200, null=True) min_stock = models.CharField(max_length=200, null=True) And on pgadmin 4 I have made an query below SELECT customer_id, MAX(date_created) AS "Last_purchase" FROM public.accounts_order GROUP BY customer_id; Which created an table below How can I import the last purchase table on the customers table field below within the last_purchase table, on Pgadmin 4? As shown below, class Customer(models.Model): title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) country = CountryField() birth_year = models.CharField(max_length=4, null=True) gender = models.CharField(max_length=200, null=True, choices=GENDER) email = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True,choices=STATUS) date_created = models.DateTimeField(auto_now=True, null=True) profile_pic = models.ImageField(null=True, blank=True, default='images/default.png') role = models.CharField(max_length=200, null=True, choices=ROLE) last_purchase = models.DateTimeField(blank=True, null=True) def __str__(self): return self.first_name hg -
How to make a model fields optional in django?
i have made a custom user model and from using that model. i have made email field optional. at first i can store data without email in database. but whenever second time i try to store data without email ,form validator gives error like User signup model with this Email already exists. how to solve this? i have tried to store from admin also but gives same error. my models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email,age,name, username, password=None): #if not email: #raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,age,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True,blank=True,null=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email','name','age'] objects = SignUpManager() def __str__(self): … -
Django / Python - Querying calculated field
I have the below model, and want to run a calculation on a foreign key of allocation and then sum the amounts. class Testmodel(models.Model): organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) allocation = models.ForeignKey(Fundraising, on_delete=models.CASCADE, related_name='items') percentshare = models.DecimalField(max_digits=11, decimal_places=2, default=0) #SET BY USER The following model property correctly calculates the amount field for each model instance. @property def amount(self): amount = self.allocation.amount_raised * self.percentshare return amount I'm trying now to sum up the amounts for each organisation on a new model, however the following doesn't work as I don't believe I can run a query on a calculated field? class Totals(models.Model): @property def total(self): total = Testmodel.objects.filter( organisation=self.organisation ).aggregate(amount=Coalesce(Sum('amount'), 0.00))['amount'] Is there any way to amend the last line for this to work, or to reperform the calculation in this line? I also tried aggregate(Sum(amount_raised * percentshare)), but this didn't seem to work either? -
How to allow registrations from specific email domains only like 'gmail' in django?
I tried what the docs said in here by using whitelist but it's not working, here's what I tried: from django.core.validators import EmailValidator email = models.EmailField(max_length=60, validators=[EmailValidator(whitelist=["gmail", "yahoo", "hotmail"])]) I tried registering with gail.com and I registered normally, so how can I fix this -
Django Heroku Server Error (500) when I set Debug - False on True it is working fine
I know that there are a lot of questions about that, but to be honest most of them stays unanswered or the solutions do not work. I have "simple" problem. When I set Debug to False and push it to heroku I get "Server Error (500)". I read those topics: Heroku server error (500) when Debug = False , whitenoise could not find style.css Whenever debug=False in django, Heroku gives Server Error (500) and when debug=True no error https://www.reddit.com/r/djangolearning/comments/acj65x/why_am_i_getting_a_500_server_error_when/ https://teamtreehouse.com/community/heroku-bad-request-500 And I tried their solutions but it still don't work. Only solution that I didn't test and is supposed to help is to get rid of whitenoise. This one is kinda "no go" for me. What Can I do about this error? Thanks and Cheers! -
Run worker from WebsocketConsumer
I'm following the guide in the docs of Django-channels (https://channels.readthedocs.io/en/latest/tutorial/) and I trying to use the worker functionality as well. first of all, I have a routing.py from channels.routing import ProtocolTypeRouter, ChannelNameRouter, URLRouter from channels.auth import AuthMiddlewareStack import gamemaker.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( gamemaker.routing.websocket_urlpatterns ) ), "channel": ChannelNameRouter({ "gagabo": gamemaker.consumers.PrintConsumer, }), }) The websocket routing is working fine, there is another routing.py file, But at the end - it runs the following consumer: class ChatConsumer(WebsocketConsumer): def connect(self): self.channel_layer.send( "gagabo", { "type": "test.print", "text": "YAY1", }, ) self.accept() def disconnect(self, close_code): pass def receive(self, text_data): print("GOT") self.channel_layer.send( "gagabo", { "type": "test.print", "text": "YAYAY", }, ) Now, I also have the worker's consumer, and is very basic one: class PrintConsumer(SyncConsumer): def test_print(self, message): print("Test: " + message["text"]) I run my code with the normal django runserver command and it run perfect -> I can connect to the server with a websocket client, send messages and it will received in the receive method (og the websocket consumer). my problem is, and this is the part I need help with, is the worker consumer -> as you can see, I'm using ChannelNameRouter in the routing.py … -
Cannot upload video with Youtube API using Django (set GOOGLE_APPLICATION_CREDENTIALS error )
I'm trying to upload a video to my channel using Youtube API V3. I have setup a developer account and have received the Client ID as well as the Secret Key. However I get the following error when I try to upload a file. Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://developers.google.com/accounts/docs/application-default-credentials. I have two apps, django_youtube which has the settings.py file and the other app is called core. settings.py (django_youtube/settings.py) import os from unipath import Path BASE_DIR = Path(__file__).parent # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '20p)4xp)osw$26w-b2_vobd0-#!%7pg)t7%02907naw8c_p&pi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Google Auth GOOGLE_OAUTH2_CLIENT_ID = "" GOOGLE_OAUTH2_CLIENT_SECRET = "" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', ] 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_youtube.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
_int_() missing 1 required positional argument: on_delete
Anyone please help solve this error, I am creating library book app -
ajax won't returned a new data
Hey guys i am trying to make a self generate table without refreshing the page i read online you can do this with ajax so i tried to do it but it won't update the data in my table, i wonder what did i do wrong its my first time using ajax with django. Can anyone give me explanation what did i do wrong here? thanks views.py dashboard will run and render the html page and give its value get_more_table will handle the ajax and append new data of the log to the table in html page def dashboard(request): mikrotik_session = request.session.get("mikadmin") host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() resource_log = api.get_resource("log") content_log = resource_log.get() return render(request,"dashboard.html",{"content_log":content_log}) def get_more_table(request): mikrotik_session = request.session.get("mikadmin") host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() increment = int(request.GET['append_increment']) increment_to = increment + 10 resource_log = api.get_resource("log") content_log = resource_log.get()[increment:increment_to] return render(request,"dashboard.html",{"content_log":content_log}) urls.py urlpatterns = [ path("dashboard",views.dashboard,name="dashboard"), path("mikrotiklogin",views.mikrotikapi,name="mikrotiklogin"), path("getmoretable",views.get_more_table,name="getmoretable"), ] dashboard.html <div class="panel-body" id="log_file"> <ul> {% for contents_log in content_log %} <li class="left clearfix"><span class="chat-img pull-left"> </span> <div class="chat-body clearfix"> <div class="header"><strong class="primary-font">{{contents_log.topics}}</strong> <small class="text-muted">{{contents_log.time}}</small></div> <p>{{contents_log.message}}</p> </div> </li> {% endfor %} … -
Django forms with relationships
I am fairly new to development but I cant seem to find the correct solution to this problem I want to create a form which has a dynamic array of questions that is defined by a relationship. So for example, I have a job advert but the admin user can set x amount of questions that they might want to ask directly on the website (e.g. Do you have a valid driving license). The relationship is set so that the questions table is related to the Job advert and ad admin user can set these up in the django-admin panel using a TabularInLine display to ask as many questions as he or she chooses. But when I create the forms.py and set the model in the Meta class to the JobAdvert, how can I access the related questions for that advert? so far my forms.py file - class JobAdvertForm(ModelForm): def __init__(self, *args, **kwargs): super(JobAdvertForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.label_class = 'col-sm-2 col-form-label' self.helper.field_class = 'col-sm-10' self.helper.form_tag = False class Meta: model = JobApplication fields = '__all__' labels = { 'tel_number': 'Telephone Number' } widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'Enter first name'} ), 'last_name': forms.TextInput(attrs={'placeholder': 'Enter last name'} ), 'email_address': … -
Django Simple Captcha Admin Page
https://github.com/mbi/django-simple-captcha https://django-simple-captcha.readthedocs.io/en/latest/ How do you put a django-simple-captcha captcha on the admin login 127.0.0.1:8000/admin/ page? -
Django SendGrid + allauth
I am currently trying to implement SendGrid in order to send confirmation emails for social accounts users that register and I get the following error SMTPDataError at /accounts/facebook/login/callback/ (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements') I have already done Single Sender Verification on SendGrid so everything should be fine on that end however I have contacted SendGrid too just in case. Below are my settings in case I might have missed something? EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' EMAIL_HOST_PASSWORD = config('SENDGRID_API_KEY') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Any help is very much appreciated. -
Cant add any data on model for One to Many relationship model related_name and Django signal issue
I can't add any object to my Customer Model for related_name issue. I have 4 or more models and I've used the Django signal for model automatic update. Customer Model and Ordered model relationship with a foreign key. I used related_name keyword on Ordered Model(see the details models information). So I cant add any object or instance on my Customer or Ordered while I created any object/instance on my customer or ordered model. I find the issue with and related_name issue. I would like to keep related_name on ordered model. but can't fix that. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounts_app/customer/add/ Django Version: 3.0.6 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users_app.apps.UsersAppConfig', 'accounts_app.apps.AccountsAppConfig', 'rest_framework'] Installed 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'] Traceback (most recent call last): File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/asad/PycharmProjects/microshop/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 231, in inner return … -
how to create a form from ManyToManyField with its extra fields django
im trying to create an online ordering system with django 2.2 and formset for generating form , class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) price = models.PositiveIntegerField() active = models.BooleanField(default=True) class Order(models.Model): cutomer = models.CharField(max_length=50) phone = models.CharField(max_length=13) products = models.ManyToManyField(Product ,through='ProductOrder') date_time = models.DateTimeField(default=datetime.now()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) my forms.py class ProductOrderForm(forms.ModelForm): product = forms.ModelChoiceField(queryset=Product.objects.filter(active=True),empty_label='') class Meta: model = ProductOrder fields = ['product','quantity'] def __init__(self,*args , **kwargs): super(ProductOrderForm,self).__init__(*args,**kwargs) for field in self.fields.values(): field.error_messages = {'required':'cant be blank'} class RequiredFormSet(BaseFormSet): def __init__(self,*args,**kwargs): super(RequiredFormSet , self).__init__(*args,**kwargs) for form in self.forms: form.empty_permitted = False ProductOrderFormSet = formset_factory(ProductOrderForm,formset=RequiredFormSet , extra=1) how to create a form contains customer , phone fields in Order model but not include in the formset i want to every form has only one customer name with its phone number but has multiple products with different quantities ? -
Django - Incomplete response received from application
I have a small Django website, it has been running perfectly until now when I tried to open the website link and saw Incomplete response received from application. No page is working. the website link is enter link description here -
Django depoy on heroku
I started studying heroku and I'm wondering if I should write in profile "web: python manage.py runserver" will the app work(without gunicorn)? -
The view account.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead
I am getting an error I have checked the views file also enter image description here The screenshot of views.py is this -
How can i get the Author in serializer in Django?
I am trying to get the author where i create the article.I tried various methods but i get lot of errors. For example i tried author= self.context['request'].user.profile but i got database error. I tried 1 or 2 more that i could from StackOverFlow but no chance from the ones i could find.Can someone help? Views.py class ArticleCreateView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def create(self, request): serializer_context = { 'request': request } serializer_data = request.data.get('article',{}) serializer = self.serializer_class( data=serializer_data, context=serializer_context, ) serializer.is_valid(raise_exception=True) serializer.save() response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'Article Created Successfully!', } status_code = status.HTTP_200_OK return Response(serializer.data, status=status.HTTP_201_CREATED) Serializers.py class ArticleCreateSerializer(serializers.ModelSerializer): caption = serializers.CharField(required=False) author = UserSerializer(read_only=True) class Meta: model = Articles fields = ('id','author','caption') def create(self, validated_data): article = Articles.objects.create(author=author,**validated_data) return article -
Django api stream csv file and upload to s3 in a thread
I have a Django APIView that generates CSV file stream and returns it using StreamingHttpResponse. I want to upload the generated file to s3 as well in a separate thread as I do not want the response to stall until upload is completed. I thought of saving the stream in a TemporaryFile object and use that to trigger s3 upload in a separate thread once the stream is complete. On following this approach I cannot use Context Manager as the file is automatically closed when context manager exits. I had to resort to closing the file manually once the upload got completed. I would like to avoid this manual file closing process. How do I solve this? Here is the view: class CsvExportView(APIView): def get(self, request): response = StreamingHttpResponse( streaming_content=get_file_stream(), content_type='text/csv' ) response['Content-Disposition'] = 'attachment; filename="{}"'.format('some_name') return response Here is the get_file_stream() method: import threading from tempfile import TemporaryFile class TempFileManager(object): def __init__(self): self._file = TemporaryFile() def get_file(self, parameter_list): pass def write_to_file(self, data) self._file.write(data) def close_file(self): self._file.close() def get_file_stream(): file_mng = TempFileManager() # get_csv_stream method is a generator that yields csv file content # by calling external api and complex data processing for data in get_csv_stream(): # keep writing to … -
DRF ModelViewSet cannot upload file/photo using Postman form-data?
I used to upload Image or File by overriding default post, put or patch methods and generic views. My code of uploading image was as follows. views.py/[post] from rest_framework.generics import CreateAPIView from dummy.models import DummyModel from rest_framework.response import Response from dummy.serializers import DummySerializer class DummyCreateApiView(CreateAPIView): queryset = DummyModel.objects.all() serializer_class = DummySerializer def post(self, request, *args, **kwargs): serialized_data = DummySerializer(data=request.data) if serialized_data.is_valid(): serializerd_data.save() return Response(serialized_data.data, status=200) return Response(serialized_data.errors, status=400) # api view for uploading image Above code works fine for generic api view. And I wanted to try the same thing on ViewSets and wrote the following code. from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from dummy.models import DummyModel from dummy.serializers import DummySerializer class DummyModelViewSet(ModelViewSet): queryset = DummyModel.objects.all() serializer_class = DummySerializer def list(self, request): serialized_data = DummySerializer(data=request.data) if serialized_data.is_valid(): serialized_data.save() return Response(serialized_data.data, status=200) return Response(serialized_data.errors, status=400) # viewset based API support for file uploading not working bcs of Parsers. After implementing the same logic with ViewSet based appraoch I am getting following error "detail": "Multipart form parse error - Invalid boundary in multipart: None" Question: How can I support file uploads in ViewSets/ModelViewSet? -
How to check forms in the formset for uniqueness
How to check forms in the formset for uniqueness? In documentation is written that I can use self.forms to check the values in forms of a formset but it doesn’t work for me : in django 3 only self.fields exists If I use "unique_together" constraint, then everything works fine with the first formset: if all fields are different, the field is saved. If the field entry repeats, I get a validation error next to the field with the repeated entry in the form. However, if I create a second formset, I get the error django.db.utils.IntegrityError: UNIQUE constraint failed: dyn_col.chart10_dynamic_column1, dyn_col.main_question_id If I use UniqueConstraint, then the form is always saved if the entered values are different. However, if I enter the same values, I get an error UNIQUE constraint failed. models.py class DynamicQuestion(models.Model): chart10_dynamic_column1 = models.CharField(max_length=25, default='', null=True) main_question = models.ForeignKey(Question, on_delete=models.CASCADE) class Meta: db_table = 'dyn_col' constraints = [constraints.UniqueConstraint(fields=['chart10_dynamic_column1', 'main_question'], condition=~(Q(chart10_dynamic_column1__iexact=None)), name='unique_dyn_col'), ] forms.py class MultiQuestionForm(forms.ModelForm): chart10_dynamic_column1=forms.CharField(required=False,label=_('Enter a header name'), widget=forms.TextInput(attrs={ 'placeholder': _('Type header name here!'), 'onkeyup': 'getSuggestions(this.value)', 'list': 'suggestionlist', 'autocomplete': 'off',})) class Meta: model = models.Question fields = ('chart10_dynamic_column1',) error_messages = { NON_FIELD_ERRORS: { 'unique_together': "The header has already been entered. Please enter a different header", } } …