Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My models.py file is printing an error that does not makes sense to me
Here's my models.py: from django.db import models from django.contrib.auth.models import AbstractUser categories = ( ('car', 'CAR'), ('motorcycle', 'MOTORCYCLE'), ('car and motorcycle', 'CAR AND MOTORCYCLE'), ) yn = ( ('Free', 'FREE'), ('Ocupied', 'OCUPIED') ) class User(AbstractUser): pass class Slot(models.Model): status = models.CharField(max_length=20, choices=yn, default="True") def __str__(self): return f'slot {self.id} is {self.status}' class Parking(models.Model): title = models.CharField(max_length=140, default="unknown") category = models.CharField(max_length=20, choices=categories, default="car") img_src = models.CharField(max_length=200, default="../../static/capstone/img/parking4.jpg") slots = models.ManyToManyField(Slot) def __str__(self): return self.title class Slot(models.Model): status = models.CharField(max_length=20, choices=yn, default="True") def __str__(self): return f'slot {self.id} of {self.status} is {self.available}' When i try to run the server, this error is consoled: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: capstone.Parking.slots: (fields.E300) Field defines a relation with model 'Slot', which is either not installed, or is abstract. The Slot model is installed, i already made the migrations. But it's not functioning. I tried to reestart the terminal, but it didn't worked too. -
Getting NoReverseMatch error when trying to redirect user after form upload
I am getting the error NoReverseMatch in Django when I try to redirect the user to a new url after processing a form upload and succesfully saving the form. Here is my views.py @login_required def profile(request): if request.method == 'POST': profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) files = request.FILES.getlist('resume') resumes_data = [] if profile_form.is_valid(): for file in files: try: # saving the file resume = profile_form.cleaned_data['resume'] parser = ResumeParser(file.temporary_file_path()) data = parser.get_extracted_data() resumes_data.append(data) profile_form.instance.name = data.get('name') profile_form.instance.email = data.get('email') profile_form.instance.mobile_number = data.get('mobile_number') if data.get('degree') is not None: profile_form.instance.education = ', '.join(data.get('degree')) else: profile_form.instance.education = None profile_form.instance.company_names = data.get('company_names') profile_form.instance.college_name = data.get('college_name') profile_form.instance.designation = data.get('designation') profile_form.instance.total_experience = data.get('total_experience') if data.get('skills') is not None: profile_form.instance.skills = ', '.join(data.get('skills')) else: profile_form.instance.skills = None if data.get('experience') is not None: profile_form.instance.experience = ', '.join(data.get('experience')) else: profile_form.instance.experience = None profile_form.save() return redirect('users-profile') except IntegrityError: messages.warning(request, 'Duplicate resume found') return redirect('users-profile') profile_form.save() messages.success(request, 'Your profile is updated successfully') # return redirect(reverse('userprofile', kwargs={"id": request.user})) return redirect('userprofile') else: profile_form = UpdateProfileForm(instance=request.user.profile) return render(request, 'user/resumeprofile.html', {'profile_form': profile_form}) @login_required def myprofile(request, user_id): profile = Profile.objects.get(id=user_id) context = {'profile':profile} return render(request, 'user/profile.html', context) And here is my urls.py: urlpatterns = [ path('', jobs_views.home, name='home'), #this is home function inside the views.py in the … -
How to provide a URL link from one app's template to the homepage which is in the root urls.py in Django?
I have to give a link to the homepage which happens to be the login page of my website, from an app's template, that is: <small style="margin-top: 5px;">To login<a href="{% url 'login' %}" class="login">Click Here</a></small> Now, the problem in the URL tag is that the link is available in the root urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.login, name='login'), ] How do I do this? -
Django product is not adding to cart
I am trying to add cart to my website using Django I have some problems: I cant add product to my cart and for some reason I do not have choice of quantity of this product this is my page that`s what i need this is my cart urls.py path('cart/', cart_detail, name='cart_detail'), path('cart/add/<int:post_id>/', cart_add, name='cart_add'), path('cart/remove/<int:post_id>/', cart_remove, name='cart_remove'), views.py @require_POST def cart_add(request, post_id): cart = Cart(request) post = get_object_or_404(Posts, id=post_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(post=post, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart_detail') def cart_remove(request, post_id): cart = Cart(request) post = get_object_or_404(Posts, id=post_id) cart.remove(post) return redirect('cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'store/detail.html', {'cart': cart}) def product_detail(request, post_id, slug): product = get_object_or_404(Posts, id=post_id, slug=slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'store/detail.html', {'product': product, 'cart_product_form': cart_product_form}) my form in html file <form action="{% url 'cart_add' post.id %}" method="post"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Add to cart"> </form> cart.py from decimal import Decimal from django.conf import settings from .models import Posts class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, post, quantity=1, update_quantity=False): post_id = str(post.id) if post_id not in self.cart: self.cart[post_id] = … -
Django updateview (cbv and fbv) to upload multiple files not working
I am trying to upload files (single and multiple) with an updateview (cbv and fbv) via an update template but I keep getting a 'This field is required' error when i submit and the files don't get uploaded of course. All required fields are filled with valid data types and the file upload fields are optional, so I don't understand where this error is coming from. I strongly suspect there's an error in my view specifically in the 'if form.is_valid():' section. I tried using both fbv and cbv, still i get the same error. I have even created a seperate model for the multiple files upload field and a seperate form class that extends the updateform class, still i get the same error. I am stumped. Please whatever help can be rendered will be highly appreciated. Thanks. this is the model for the multiple files upload field class shareCapitalFiles(models.Model): # Foreign key coopform = models.ForeignKey(CoopForm, on_delete=models.CASCADE) # Attach evidence of share capital attach_share_capital = models.FileField('Attach Share Capital', upload_to="documents", blank=True) this is my forms.py # Update Form class updateCoopForm(forms.ModelForm): nature_registration = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'flex inline-flex', 'cursor': 'pointer'}), choices=CoopForm.REGISTRATION_TYPE) have_bye_laws = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'flex inline-flex', 'cursor': 'pointer'}), choices=CoopForm.BYE_LAWS_CHOICES) attach_bye_laws = forms.FileField(required=False) class Meta: model … -
Upload to S3 Bucket from Django Models directly
I'm currently developing a Django application, and my images and staticfiles are initially uploaded to a local path, then when I run collect-static, it pushes everything to the S3 bucket. I was wondering if there is a way to remove intermediaries and directly upload the files and images to the S3 bucket. -
I am getting mistake Please Help Me Guys TY
# CHANGING THE COMPANY def change_company(request,pk): item = get_object_or_404(Companies, pk=pk) if request.method == "POST": form = CompaniesForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('display_companies') else: form = CompaniesForm(instance=item) return render(request, 'change_company.html', {'form':form}) here is my view The view companies.views.change_company didn't return an HttpResponse object. It returned None instead. Showing this mistake when i click on button in order to change my company table -
Django variables from forms to templates
I'm building a website and i'm trying to make the user able to change his credentials. I've made a form for this: newUsername = forms.CharField( label="Enter your new username here*", required=True, widget=forms.TextInput(attrs={ 'class': 'userChangeCredentials', 'value': "{{ user.username }}" })) newEmail = forms.EmailField( label="Enter your new e-mail adress here*", required=True, widget=forms.EmailInput(attrs={ 'class': 'userChangeCredentials', 'value': '{{ user.email }}' })) newPassword = forms.CharField( label="Enter your new password here", required=False, widget=forms.PasswordInput(attrs={ 'class': 'userChangeCredentials', 'value': '' })) passwordConfirmation = forms.CharField( label="Confirm your existing password here*", required=True, max_length=256, widget=forms.PasswordInput(attrs={ 'class': 'userChangeCredentials', 'value': '' })) The problem is, that the values in the widget dictionary are passed as raw text and i want them to be variables. This is the output: Do i need to change something inside of html? My html: <form id="UserForm" action="{% url 'user' name=user.username %}" method="POST"> {% csrf_token %} {{ form|safe }} <input class="userChangeCredentials" type="submit"></input> </form> I tried to make the text raw like this: widget=forms.EmailInput(attrs={ 'class': 'userChangeCredentials', 'value': r'{{ user.email }}' }) But it didn't help. I am seeking for the answer for like a week and i wasn't able to find any question on this theme. I've read the oficial Django form page, but there is nothing about this exact thing. … -
How to add filter inside the tabular-inline model of django admin
I am trying to add filter with inline model I tried adding list_filter within inline class but it is a method not given in inline class -
JavaScript: Age Gate Validation
I am creating an app that a user must be over 18 to enter the site or competition, I have tried my best to get the validation on the inputs, I have tried my best to create the JS What Must Happen When the user either inputs a alphanumeric character or leaves the input empty, there should be a div that appears with the error message underneath that says "Invalid Credentials" here is my html: <div id="modal"> <div class="modal-content"> <div class="flex-container"> <div> <img src="{% static 'imgs/Fireball_logo.png' %}" class="logo" alt="fireball logo"> <h1>WOAH THERE!</h1> <p class="info-text">We just need to see something</p> </div> <form action=""> {% csrf_token %} <div class="form-flex"> <input class="ageGate" type="text" max-length="2" placeholder="DD"> <input class="ageGate" type="text" max-length="2" placeholder="MM"> <input class="ageGate" type="text" max-length="4" placeholder="YYYY"> </div> <p class="cookie-policy"> <small> This site uses cookies. Cookie Policy. I agree to the terms of use, and the privacy policy. This information will not be used for marketing purposes </small> </p> <div class="text-center"> <button id="btnSubmit" class="btn" type="submit"> <p class="btn-text">Enter</p> </button> </div> <span id="errorMsg"></span> </form> <div> <img src="{% static 'imgs/Drinkaware_logo.png' %}" alt="Drinkaware Logo"> </div> </div> </div> </div> and my JavaScript file: const modal = document.getElementById("myModal"); const btnSub = document.getElementById('btnSubmit'); // When the user clicks anywhere outside of the … -
How to render results from API based on the user's search/ Django
As you can see in the picture below I'm trying to have the user search for a given country, start/end date and get the result of "Confirmed Cases" and "Date" back from the API, but I'm not sure how to do it. enter image description here I tried using this API, to fill the drop-down menu of the countries --> https://api.covid19api.com/summary but this is the other API that I have to use but while changing the parameters for the country and dates --> https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z Here are snippets of my code: views.py def home(request): # response = requests.get('https://api.covid19api.com/country/afghanistan/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json() response = requests.get('https://api.covid19api.com/summary').json() my_list = [] for i in range(0, len(response ['Countries'])): my_list.append(response ['Countries'][i]['Country']) if request.method=='POST': selected_country = request.POST['selected_country'] print('here', selected_country) return render(request, 'home.html', { 'my_list': my_list}) home.html <div class="container"> <form method="POST" action="{% url 'home' %}"> {% csrf_token %} <label for="selected_country" style="margin-right: 5px;"> Select a Country, Start & End Dates : </label> <select name="selected_country" id="selected_country"> {% for object in my_list %} <option value="">{{object}}</option> {% endfor %} </select> <label for="startdate"></label> <input type="date" id="startdate"> <label for="enddate"></label> <input type="date" id="enddate"> <input type="submit" value="Search" /> </form> </div> PLUS: when I click on "search" i should get the value of the selected_country because I tried printing it, but … -
Recover sqlite_sequence table
is there any way to recover the content from sqlite_sequence table ? I have SQLite db file which still has the entires if I open the db file with a text editor. But I open it with grafical SQLite editor, the content is not avalible. Is there any chance to recover those enties and export them ? Thanks I have try to export it with SysTools SQLite Database Recoyery Tool, but it doesn't export anything -
Python output beautifier subprocess
Hello i am using subprocess. import subprocess proc = subprocess.Popen(['ls'], stdout=subprocess.PIPE) output = proc.stdout.read() print(output) output is correct b'file.txt\nmain.py\nsource\ntest-page\n' is there any way to beautify it , like in linux server ? root@master:/home/python# ls file.txt main.py source test-page -
Django models - how to properly calculate multiple values with various conditions
I want to count multiple metrics in a single query on my model. each metric should have a different filter (or no filters at all) I'm using Django==2.2.3 and a Djongo model. MyModel columns: user_id = models.IntegerField(blank=True, null=True) group_id = models.IntegerField(blank=True, null=True) What i try to run, suggested in another topic, does not work for me. Query: MyModel.objects.aggregate ( total=Count('user_id'), test=Count('user_id', filter=Q(user_id='just_a_fake_id')), group_1_value=Count('user_id', filter=Q(group_id=1)), group_2_value=Count('user_id', filter=Q(group_id=2)), ) The results: {'total': 0, 'test': 47479, 'group_1_value': 47479, 'group_2_value': 47479}, does not make sense - all results (except total) returns the same number which is the count of all the records What i want to run is query similar to SELECT COUNT(user_id) as total, COUNT(CASE WHEN group_id=1 THEN user_id END) as group_1_value, COUNT(CASE WHEN group_id=2 THEN user_id END) as group_2_value FROM MyModel How do i need to modify the query in order to get the correct values? -
Is https://github.com/Corvia/django-tenant-users and alternative version of https://github.com/django-tenants/django-tenants?
I'm working on building a SAAS and I've found Thomas Turner's django-tenants quite useful (awesome). But I found in another question, which he answered himself and made a reference to Corvia/django-tenant-users. So I don't know if they are different alternatives or if they complement each other. Thanks for your support. (Hope you see my question Thomas) My best wishes, PR I have found these options: https://github.com/Corvia/django-tenant-users (Last Release on Nov 26 2022) https://github.com/Corvia/django-tenant-users (Last Release on Oct 31 2022) and https://github.com/bernardopires/django-tenant-schemas (Last Release on Jun 3 2017) -
How can I send Message.info from admin to another user in Django
When someone user tries to publish an article. The user must wait for the approval/disapproval of this article from the admin. after approving/disapproving their articles, the users must get Message.info. But these messages showed on the admin page, not on a user page the disapproved message: this is model.py class Article(models.Model): auther = models.ForeignKey(User, on_delete= models.CASCADE) title = models.CharField(max_length= 200, null = False) bio = models.CharField(max_length = 450, null = False) tags = TaggableManager() body = RichTextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) approved = models.BooleanField('approved', default = 'False') def __str__(self): return self.title this viws.py : from django.contrib.auth.models import User from article.models import Article def delete_article(request, pk): model_article = apps.get_model('article','Article') if request.user.is_superuser: id_user = model_article.objects.get(pk = pk).auther_id model_article.objects.get(pk = pk).delete() messages.info(request,' تم تنفيذ العملية بنجاح!' ) for x in User.objects.all(): if(x.id == id_user): messages.info(request, 'تم حذف مقالك الجديد لأنه يخالف سياسة الموقع !') return redirect('main') But i want the message shwon to user who want to publish an article -
The jinja code is being read as HTML text instead of getting executed
I don't know if I'm asking this question in the right way. Please see this screenshot: https://i.stack.imgur.com/Idl0l.png directory: weatherApp core urls views templates index.html weatherApp urls This is the main project urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')) ] These are app urls and views: core.urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views from django.shortcuts import render import urllib.request import json def index(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen('https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=').read() data_list = json.loads(source) data = { "country_code" : str(data_list['sys']['country']), "temp" : str(data_list['sys']['country']), "temp_min" : str(data_list['main']['temp_min']), "temp_max" : str(data_list['main']['temp_max']), "pressure" : str(data_list['main']['pressure']), "humidity" : str(data_list['main']['humidity']), "wind_speed" : str(data_list['wind']['speed']), "wind_dir": str(data_list['wind']['dig']), "main" : str(data_list['weather'][0]['main']), "description" : str(data_list['weather'][0]['description']), "icon" : str(data_list['weather'][0]['icon']), } print(data) else: data = {} print(data) return render(request, 'index.html', data) -
SignatureDoesNotMatch when calling PutObject with Django, Django-Storage, AWS S3, boto3
I created a Django App and host it on Heroku where I specified all setting vars such as Access Key ID (see Settingsfile). Settingsfile Settingsfile2 Relevant requirements: django-storages==1.12.3 boto3==1.26.31 Anyone any ideas on how to solve this? I tried the IAM user with full access, only S3 Full access, the Access Keys of the global account and I just keep geeting the error: "botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the PutObject operation: The request signature we calculated does not match the signature you provided. Check your key and signing method." when trying to upload something to S3. The website then outputs: Internal Server Error The server encountered an unexpected internal server error (generated by waitress) The logger I added to the settings file on django is not helpful at all as it just shows me a SignatureDoesNotMatch error. I tried Access Keys with + and without as this might be the source of the error. I couldnt find any best practice on how to insert the keys to the heroku settings but a lot of ppl reporting errors when copying the keys from the aws website. I cheched it with the csv file and the website output. I tried … -
Auto populate form field - django
I am trying to auto populate a field in a form so the user does not have the input the data. In this case, the user will start from a show_venue page which is going to display a number of products. By clicking on one of these products, the user is redirected to a product page where a review can be left as part of a form. The form requries the user to select the venue where the review took place. I am looking to simplify this. Since the user already come from a venue_id page, I would like to auto fill this field. I tried different things found in this forum and left my last attempt, which currently deliver the following error message: cannot unpack non-iterable NoneType object. Slight quirk - you will notice the form is actually being saved in the show_venue function and not on the show_product_from_venue function (product page). This is due to a redirection process I had to implement: the user is redirected to the previous venue_ID page after submitting the form: made this happen with a javascript in the template. I am not adding the template page to keep the question concise and dont … -
Optimization Subquery Django ORM
I have function with some calculations. Subquery with OuterRef running too long, how i can optimization or find another way to get id for average_ndmi? def get_ranking_manager_ndvi_regions( year: str, month: int, pk: Optional[int] = None ) -> List[Region]: return ( get_regions(pk=pk) .annotate( year=SearchVector("commune__field__fieldattribute__date__year"), month=SearchVector( Cast("commune__field__fieldattribute__date__month", CharField()) ), size=Sum(F("commune__field__fieldattribute__planted_area")), field_count=Count("commune__field"), ) .filter(year=year, month=str(month)) .annotate( average_ndvi=Subquery( Field.objects.filter(commune__region__id=OuterRef("pk")) .values("commune__region__id") .annotate(ndvi_avg=Avg("fieldattribute__ndvi")) .values("ndvi_avg"), output_field=FloatField(), ) ) .annotate( standart_deviation=( Sum( (F("commune__field__fieldattribute__ndvi") - F("average_ndvi")) ** 2, output_field=FloatField(), ) / F("field_count") ) ** (1 / 2) ) )``` -
How to add columns to auth_user in django postgresql?
Hello i want to register user in django. In django there is just fileds for basic datas email and username, but i want to add more like; about, user_profile_picture_url, address etc. It creates the model perfectly but... It's not saving it to database also makemigrations and migrate does not work! there is just username, first_name, last_name and email views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib import messages from profiles.forms import Register_User_Form from profiles.models import User_Profile def register_user(request): if request.method == 'POST': form = Register_User_Form(request.POST) if form.is_valid(): form.save() username = form.cleaned_data["username"] password = form.cleaned_data["password1"] email = form.cleaned_data["email"] about = form.cleaned_data["about"] phone_num = form.cleaned_data["phone_num"] picture_url = form.cleaned_data["picture_url"] User_Profile(name=username, email=email, about=about, phone_num=phone_num, picture_url=picture_url) print("Model Created") user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Registration Successfull") return redirect('/') else: form = Register_User_Form() return render(request, 'registration/register.html', {"form": form}) models.py from django.db.models import * class User_Profile(Model): picture_url = CharField(max_length=120, default="") name = CharField(max_length=30, default="") about = CharField(max_length=250, default="") email = CharField(max_length=50, default="") phone_num = CharField(max_length=15, default="") forms.py from django.forms import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class Register_User_Form(UserCreationForm): username = CharField(label="Username", max_length=36) email = CharField(label="Email", max_length=120, widget=EmailInput()) password1 = CharField(label="Password", max_length=36, widget=PasswordInput()) password2 = CharField(label="Confirm Password", max_length=36, widget=PasswordInput()) … -
Fetching data from multiple api in django rest framwork
First I don't know I'm asking a good question or not. I'm trying to integrate Paytm Payment in my django rest framework. There are many api from paytm like Initiate transaction , fetch all payment, send OTP etc, like in the image below Im able to initiate transaction but not all payments are available, Inorder to do that I have to call the Fetch Payment Options API. But I don't know how to do that because I'm already calling Initiate transaction API in the view with parameters but I don't know how to call other api with different parameters in the same view. Like when I initiate transaction, the API gets fired and frontend shows the paytm page. So these api should be called on frontend?. I actually don't know how to ask this question properly. I need help -
Django & PostgreSQL- Store Random Numbers in the database
In order to strengthen my basic knowledge in Django, I have decided to create something ther than a "to-do" list, I want to create a app that: "will need to create a number of unique 6 digit codes and store in the database. This will be used to verify unique entries." so my question is as follows: How can I quickly generate and store 50 random entries in my db How can I check if the user has a number that matches or not What is the best way to approach this, I need to start thinking like a dev so I am looking for a bit of guidance and not the result, a nudge in the right direction, I have attached a mock up of the design where the user is requested to submit their "unique entry" and see if it matches to any one of them stored in the db I am obviously reading the official django documentation too, but its not as straight forward for me to understand Regards Trevor -
Create multiple instances with given fields
I have these models class Guest(models.Model): name = models.CharField(max_length=50, blank=True, null=True) surname = models.CharField(max_length=100, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) adress = models.CharField(max_length=200, blank=True, null=True) table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=True, null=True) class Dish(models.Model): name = models.CharField(max_length=50, blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) class GuestOrder(models.Model): comment = models.CharField(max_length=400, blank=True, null=True) guest = models.ForeignKey(Guest, on_delete=models.SET_NULL, null=True) dish = models.ManyToManyField(Dish) ingredient = models.ManyToManyField(Ingredient) And I get this data from postman { "guests":{ "23": [1, 2, 3], "24": [1, 2], "25": [1] } } So here 23-25 are guest ids and 1-3 are dish id. This is the view (I also get table_id from posman but that's irrelevant for question) class CreateOrderView(APIView): def post(self, request): table_id = request.data.get('table_id') table = Table.objects.get(id=table_id) number_of_guests = int(request.data.get('number_of_guests')) guest_orders = [] guests = [] for i in range(number_of_guests): guest = Guest() guest.table = table guest.first_name = str(i) guests.append(guest) Guest.objects.bulk_create(guests, number_of_guests) guests = request.data.get('guests') for key, value in guests.items(): guest = find_guests(key) print(guest) # print(value) dish = find_dish(value) print(dish) GuestOrder.objects.create(guest=guest, table=table) guest_orders = GuestOrder.objects.filter(table=table) for guestorder in guest_orders: guestorder.dish.set(dish) return Response("5") these are the helper functions used in the view. def find_guests(id): found_guest = Guest.objects.get(id=id) return found_guest def find_dish(list): for y in list: found_dishes = [] found_dish … -
Can't move validation from view to serializer
I need to move validation from views.py to serializators.py. How can I do it? Validation must check: user can't follow himself user can't follow author that his already follow I have a ViewSet with @action: my view.py: @action( detail=True, methods=['post', 'delete'], permission_classes=(permissions.IsAuthenticated,) ) def subscribe(self, request, id=None): """Following""" author_id = id if request.method == 'POST': author = get_object_or_404(CustomUser, id=author_id) if author == request.user: raise serializers.ValidationError( {'errors': 'You can't follow yourself.'} ) if self.request.user.follower.filter(author=author).exists(): raise serializers.ValidationError( {'errors': 'You already follow this author.'} ) author = get_object_or_404(CustomUser, id=author_id) Follow.objects.create( user=request.user, author=author ) serializer = FollowSerializer(author, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) if request.method == 'DELETE': user_id = request.user.id subscribe = get_object_or_404( Follow, user__id=user_id, author__id=author_id ) subscribe.delete() return Response(status=status.HTTP_204_NO_CONTENT) and I have a FollowSerializer in serializers.py my serializers.py class FollowSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('email', 'id', 'username', 'first_name', 'last_name', 'is_subscribed', 'recipes', 'recipes_count') I try to add a validate method like def validate(self, data): but it doesn't work.