Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare different layers using Django and OpenLayers
I'm developing a GIS project with Django and Openlayers. I've created a comparison map that with a slider allow to compare two WMS. Now I would like to do something more tricky because I would to give to the user the possibility to select which WMS to compare. So in my model I've created a ForeignKey that represent a static layer and a ManyToManyField that contain the list of layers to compare with the static layer. I'm be able to create a template that give to the user the possibility to active/deactive a single layer: {% for layer in webgis_single.layers.all %} const source{{ layer.wms_layer_name|cut:"_" }} = wmsMainSource.createWMSLayer( '{{ layer.title }}', '{{ layer.wms_layer_path }}', '{{ layer.wms_layer_name }}', {% if layer.wms_layer_style == None %}null{% endif %}{% if layer.wms_layer_style != None %}'{{ layer.wms_layer_style }}'{% endif %}, {{ layer.set_max_zoom }}, {{ layer.set_min_zoom }}, {{ layer.set_zindex }}, {{ layer.set_opacity }} ); $('#{{ layer.pk }}_{{ layer.wms_layer_name }}').on('change', function() { let isChecked = $(this).is(':checked'); if (isChecked) { mapCanvas.addLayer(source{{ layer.wms_layer_name|cut:"_" }}); } else { mapCanvas.removeLayer(source{{ layer.wms_layer_name|cut:"_" }}); } }); {% endfor %} But I'm locked on the possibility to deactive the active layer when there is a list of activable layers: {% for layer in webgis_single.map_swipe_right.all %} const … -
How can i make a Query through Many-To-Many-Relationship
I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...) How do I make the correct query? Are the models correct for this? Models: class Course_dates(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() def __str__(self): return str(self.id) """return self.date.strftime("%d.%m.%Y")""" class Course(models.Model): course_number = models.CharField(max_length=24, blank=True) course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE) course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates") def __str__(self): return self.course_number class Trainer_Course_Course_date_role(models.Model): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) role = models.CharField(max_length=24, blank=True) def __str__(self): return str(self.id) class Course_Course_dates(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE) trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.id) class Trainer(models.Model): salutation = models.CharField(max_length=8,choices=GENDER_CHOICES) last_names = models.CharField(max_length=56) first_names = models.CharField(max_length=56) date_of_birth = models.DateField() address = models.ForeignKey(Address, on_delete=models.CASCADE) email = models.EmailField() phone = models.CharField(max_length=56, blank=True) mobile = models.CharField(max_length=56, blank=True) def __str__(self): return self.last_names View: def course(request): courses = Course.objects.all() course_list = [] for course in courses: sorted_date_list = course.course_dates.all().order_by('date') course_list.append({'course': course, 'sorted_date_list': sorted_date_list }) context = { 'course_list': course_list, } return render(request, 'kursverwaltung_tenant/course.html', context) -
Cant access a private s3 image however I can upload
I have created an s3 bucket. I have created a user and granted the access AmazonS3FullAccess. The images are uploaded correctly, however the link is not working and I get the following xml error: "The request signature we calculated does not match the signature you provided. Check your key and signing method" I am new to aws and perhaps I am doing something wrong. I want the link to be secure, e.g. with an expiration date. Settings: 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 = 'xxxxxx' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-central-1' AWS_S3_SIGNATURE_VERSION = 's3v4' -
Read with pandas once and keep many csv files open or read and close each time
I am doing a project with Django in which I generate several graphs with Plotly and do operations with CSV files that I read, write and modify (also download or delete) with pandas. These files depend on the company to which the user belongs, for example, if it belongs to the TOYOTA company, the file is in data / toyota, and if it belongs to Honda, it is in data / honda. My question is which is better, to read the 50 csvs that will be used when the user logs in, or to read and close the csvs as needed. For example, in my url example.com/analysis, these functions are called: @login_required def analysis(request): data_report = pd.read_csv(f'data/{request.user.company}/test/data_report.csv', sep=';', encoding='utf-8') context = {} for column in data_report.columns: context[column] = data_report.loc[0, column] data_roles = pd.read_csv(f'data/{request.user.company}/test/data_roles.csv', sep=';', encoding='utf-8') # Here more code that doesn't matter ... graphs = [] marker = { 'color': 'rgb(0,150,209)', 'opacity': 0.5, } graphs.append( go.Scatter(x=n_users, y=n_perms, mode='markers', name='Line y1', marker=marker) ) layout = { 'xaxis_title': 'Number of users', 'yaxis_title': 'Number of permissions', 'height': 400, } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') context['plot_div'] = plot_div return render(request, 'analysis.html', context) @method_decorator(csrf_exempt) def update_pie_chart(request): if request.method == 'POST' and request.is_ajax(): selected … -
Appointment slot from uml to django
I would like to know if my django model are correct according to this class diagram : The diagram : The code : class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class Staff(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class AppointmentSlot(models.Model): staff = models.ForeignKey('Staff', null = True, on_delete = models.CASCADE) date = models.DateField(null = True) start = models.TimeField(null=True, blank=True) end = models.TimeField(null=True, blank=True) student = models.ForeignKey('Student', null=True, on_delete=models.CASCADE) Do I have made some errors ? -
Python Why Django won't let me load a new product?
I'm in this page: Filling the details The ling is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg When I'm pressing 'save' it gives me this: Error message Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20 -
rest_framework.permissions.IsAuthenticated is never executed
I am trying to only let execute a method to people who has signed in. I am using JSONWebTokenAuthentication This is the implementation: class vistaUsuarios(APIView): permission_classes = (IsAuthenticated,) def usuario(request): print("USUARIO ",request.user.is_authenticated) if request.method == 'GET': usuario = None id = request.GET.get("id") if id is not None: usuario = Usuario.objects.get(pk=id) usuarios_serializer = UsuarioSerializer(usuario) return JsonResponse(usuarios_serializer.data, safe=False) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'NON_FIELD_ERRORS_KEY': 'global', } # JWT settings JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': timedelta(days=2), } # allauth SITE_ID = 1 ACCOUNT_EMAIL_VERIFICATION = 'none' # JWT settings REST_USE_JWT = True INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'subroutinesbackapp', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth', 'rest_auth.registration' ] ... The problem is that IsAuthenticated is never executed. I have a print there, and never do. class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): print("holaaaaaaa") return bool(request.user and request.user.is_authenticated) The method usuario from vistaUsuarios class, always execute. Even though the print print("USUARIO ",request.user.is_authenticated) shows USUARIO false because I haven't passed a valid token. How can I make the IsAuthenticated method execute? Thanks, in advance -
How to get a button in template to change a model? Django
I am trying to build an app with a like-dislike functionality such that by clicking a like button you get added to a string of users that liked and get removed from the dislike string if you were there. How can i do that? I added some of the relevent code: the button: <button type='submit'> Like </button> And the model im trying to change: title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) auther = models.ForeignKey(User, on_delete=models.CASCADE) views_number = models.IntegerField(default=0) user_like_id = models.CharField(validators=[int_list_validator], max_length = 10000000, default = "") user_dislike_id = models.CharField(validators=[int_list_validator], max_length = 10000000, default = "") -
I am getting Key error message while trying to save my Django form. I am not able to save data from Django form to the database
I am trying to add client to my client model along with the user model using Django forms. But as of now I am getting a key error. I am not able to figure out what is wrong with this and would appreciate some help on this one. My clients model is this class Clients(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) primaryphone = models.CharField(max_length=15, unique=True) location = models.CharField(max_length=30, choices=States) project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1) contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() The view for this are def add_client(request): form = AddClientForm() context = { "form": form } return render(request, 'admintemplate/add_client_template.html', context) def add_client_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_client') else: form = AddClientForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] phone = form.cleaned_data['phone'] location = form.cleaned_data['location'] project_id = form.cleaned_data['project_id'] contract_id = form.cleaned_data['contract_id'] try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.clients.location = location user.client.primaryphone = phone project_obj = Projects.objects.get(id=project_id) user.clients.project_id = project_obj contract_obj = Contracts.objects.get(id=contract_id) user.clients.contract_id = contract_obj user.clients.save() messages.success(request, "Client Added Successfully!") return redirect('add_client') except: messages.error(request, "Failed to Add Client!") return redirect('add_client') else: return redirect('add_client') … -
NuxtJS with NestJS
Im really confused and i wanted soemone to explain this for me, so if im not wrong is NuxtJS just a vue front end framework and NestJS a node based backend framework? if i work with both it shouldnt matter right? it should be like working with some x frontend framework with other y backend framework. I want a good framework to use with my NuxtJS application that has good security implemented, should i work with node? nest? express? django? What u guys recommend me? Sorry for being a newbie haha. -
How to save data from form.ModelForm in database and also show new post in template?
View.py def create_post(request): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.date_posted = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'post_detail.html', {'form': form}) Forms.py from django import forms from django.forms import ModelForm, fields from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'date_posted', 'author'] -
Unable to install mod_wsgi with command <pip install -v mod_wsgi>
I am trying to set up a Django-Apache platform to host my Django Application on my local network. I am facing an issue with installing the mod_wsgi module with the command : ''' pip install mod_wsgi ''' The command is actually downloading all the versions of mod_wsgi starting from mod_wsgi-4.1.0 to mod_wsgi-4.9.0 and is ultimately getting terminated while raising the error: ERROR: No matching distribution found for mod_wsgi and ModuleNotFoundError: No module named '_distutils_hack'. Given below is the screenshot of the issue: Please help me resolve this. -
TypeError: 'RelatedManager' object is not iterable - serializers.ListField()
I have this 2 models: Route and Order. Route has a relation oneToMany with Order as you can see: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField(default=datetime.date.today) date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) description = models.CharField(max_length=500, null=True) route = models.ForeignKey(Route, related_name='orders', null=True, on_delete=models.CASCADE) class Route(models.Model): day = models.DateField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) start_time = models.TimeField() When a order is created it's route should be null. When a route is created I want to associate orders with the route created, so I have the following Route Serializer. class routeSerializer(serializers.ModelSerializer): orders = serializers.ListField() class Meta: model = Route fields = ['day', 'warehouse', 'start_time', 'orders'] def create(self, validated_data): keys_to_extract = ['day', 'warehouse', 'start_time'] route_subset = {key: validated_data[key] for key in keys_to_extract} print(validated_data) route = Route.objects.create(**route_subset) for order_data in validated_data['orders']: Order.objects.filter(id=order_data).update(route=route) return route The body of the request should be like this: { "day" : "2021-12-12", "warehouse": "1", "start_time": "7:00", "orders": [ 1,2,3,4,5,6,7 ] } I was doing this in a different way, but I was told to do this in this way, but with orders = serializers.PrimaryKeyRelatedField(). But in that way I can't get the 'orders' from validated_data since it just come with 'day', 'warehouse' … -
How to merge data from two models
I have a VideoView model which tracks data about a user who watched a video. I am now creating a Todo model which will keep track of what users need to watch. I figured I may as well merge these models into one Todo model and remove the VideoView model. What is a common procedure for moving the data from one model to another? I see a couple different options but maybe there are other options. The models: class VideoView(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now=True) class Todo(models.Model): created_on = models.DateTimeField(auto_now_add=True) completed_on = models.DateTimeField(auto_now=True) user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey( Video, on_delete=models.CASCADE, null=True, blank=True, related_name='todos' ) Option 1: Write a view which opens each VideoView then creates new Todo instances with the data of each. Then visit the view in the browser to migrate the data. This option seems to be decent as the code will be readable and I can delete Todos if there are mistakes. Option 2: Same thing but in the shell. Less readable. More prone to errors. Option 3: Is there a way to simply move the field from one model to another? Or maybe doing a multi-stage(?) migration, where … -
How to "create or update" using F object?
I need to create LeaderboardEntry if it is not exists. It should be updated with the new value (current + new) if exists. I want to achieve this with a single query. How can I do that? Current code looking like this: (2 queries) reward_amount = 50 LeaderboardEntry.objects.get_or_create(player=player) LeaderboardEntry.objects.filter(player=player).update(golds=F('golds') + reward_amount) PS: Default value of "golds" is 0. -
NOT NULL constraint failed: plegdetect_fileupload.user_id
I am building a plagiarism detector using Django. Whenever a user upload a file and click on upload , That file goes to my media file . But I got the error that NOT NULL constraint failed: plegdetect_fileupload.user_id . my models.py is : from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class FileUpload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='files') def __str__(self): return self.user.username my view.py is: class PostCreateView(CreateView): model = FileUpload fields = ['file'] def form_valid(self, form): form.instance.author = self.request.user return super(PostCreateView, self).form_valid(form) my urls.py is : from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('post/new/',views.PostCreateView.as_view(),name='post-create'), ] Thanks in advance -
How to Convert MP4 to HLS with Multiple Audio and Multiple Video Quality in Python/Django?
I have tried with ffmpeg library and I can convert videos mp4 to hls with multiple quality but multiple audio is not working. > [Commands Excuting from Terminal] And with subprocess library calling subprocess.call. > [ Want to know is this the right way? to do with Django? ] -
<form method="get"> is send as POST (Django)
I'm trying to make django-filter work, and it have worked, but now it suddenly have stopped. The issue is that the submit button in the filter seems to be sending a POST request and not GET Below is a snippet of the HTML code <div class="form-group"> <form method="POST"> {% csrf_token %} {{form|crispy}} <button class="btn btn-outline-success" type="submit">Add product</button> </div> <div id="filter-menu"> <form method="get"> {{filter.form.nick_name|as_crispy_field}} <br> {{filter.form.domain|as_crispy_field}} <br> <button class="btn btn-outline-success" type="submit">Apply filter</button> </form> </div> I do have a POST-request submit button above as seen, and it seems like it's the one being triggerd, since when I debug the application, request.method == "POST" when pressing the apply filter button. If needed, a snippet of my view is here (omitted messages and stuff) def MyView(request): user = request.user user_products = MyModel.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) #Helper function for returning filters filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = MyForm(request.POST) if post_form.is_valid(): filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/my_html.html",context=context) else: #invalid post_form context = { "form":post_form, "filter":filter } return render(request, "myapp/my_html.html",context=context) else: #Get request form = MyForm() context = { "form":form, "filter":filter } return render(request, … -
django CSS & Javascript not loading in HTML files?, error 404?
I have put some static files for CSS Javascript and Jquery in my file static. I have put load static in my HTML and it doesn't respond properly to the HTML. Do you have anything else to do with it? output error setting.py file -
RuntimeError: set_wakeup_fd only works in main thread of the main interpreter when adding a proxybroker job in django-apscheduler
I tried to use django-apscheduler to add a proxybroker job. There is no problem to run test_proxybroker.py and got proxies returned. But I got this error when I run the django-apscheduler command. set_wakeup_fd only works in main thread of the main interpreter #test_proxybroker.py import asyncio from proxybroker import Broker # https://proxybroker.readthedocs.io/en/latest/examples.html def broke(): async def show(proxies): while True: proxy = await proxies.get() if proxy is None: break print('Found proxy: %s' % proxy) try: loop = asyncio.get_event_loop() except: new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) loop = asyncio.get_event_loop() proxies = asyncio.Queue() broker = Broker(proxies) tasks = asyncio.gather( broker.find(types=['HTTP', 'HTTPS'], limit=10), show(proxies)) loop.run_until_complete(tasks) #runapscheduler.py. (the django command file) ... def test_job(): try: broke() except: pass ... -
Recent user visits in Django
I have a visit model on my site that is strong enough to use the page of a product, an object is registered with the product and the user's IP. If anyone knows, thank you -
Django appeared ajax error after uploading the site to heroku
I am making a portfolio site in django and I wanted to upload it to heroku. Everything worked fine on localhost, but after uploading the site to heroku, I started getting errors when using AJAX. Im using ajax for register user and sending email massage Js $.ajax({ type: 'POST', url: "", enctype: 'multipart/form-data', data: fd, success: function(response) { mess = $('.b-popup_message') if (response.status == 'login') { window.location.href = '/'; mess.text('Wait...') } else { mess.text('We have sent the code to you by mail. Enter it') } }, error: function(error) { console.log(error); }, cache: false, contentType: false, processData: false, }) return false view.py def main(request): global code login_form = LoginForm(request.POST or None) data = {} if request.method == 'POST': if login_form.is_valid(): if request.is_ajax(): email = request.POST.get('email') data['email'] = email data['code'] = login_form.cleaned_data['code'] if not code or code != data['code']: sleep(10) code = generate_code(4) send_email_message = EmailMessage('DONUTELA CODE', f'Enter this code on the register form: {code}', to=[email]) send_email_message.send() data['status'] = 'sent_code' elif code == data['code']: if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) else: user = User.objects.create_user(username=generate_code(20), email=email, password=generate_code(20)) login(request, user, backend='MainApp.Backends.PasswordlessAuthBackend') data['status'] = 'login' return JsonResponse(data=data) added_products_cookies = request.COOKIES.get('added_products') added_product_names = [] # все добавленые продукты по названию added_products_dict = {} # вид {название продукты: … -
How can I use an extra ModelChoiceField on a ModelForm?
I am trying to add a ModelChoiceField to a ModelForm, but I keep getting a TypeError: type object argument after ** must be a mapping, not QuerySet. I feel like I implemented the modelchoicefield as in the docs, with a queryset argument. The form worked fine before I added the ModelChoiceField. forms.py from django import forms from events.models import Event, ExtraThing class EventForm(forms.ModelForm): extra_thing = forms.ModelChoiceField(queryset=ExtraThing.objects.all()) class Meta: model = Event fields = ('name', 'date', 'extra_thing') views.py from events.forms import EventForm def newevent(request): if request.method == 'POST': form = EventForm(request.POST) if form.is_valid(): form.save() else: form = EventForm() return render(request, 'manage/event_form.html', {'form': form}) -
Frontend and backend validation synergy
I've created a register form validation on frontend and backend and I am checking both at the frontend and backend: whether the name and surname consist of letters only, whether the password contains numbers, uppercase and lowercase letters, whether the email is correctly saved. The interface informs about errors. My question is, since I check all the conditions on the frontend, should the backend also send error messages to the frontend? I mean both frontend and backend check data validation, but should the frontend react to backend error messages? It seems unnecessary for the backend to send information that f.e. the password is too short, since the frontend already does it. The backend should only make sure that f.e. the password length is appropriate. Second question: should I check on the backend side whether the checkbox regarding acceptance of the website regulations has been selected or whether the password and the repeated password are the same? -
Python/DJango 'django.db.utils.OperationalError: no such table' in Django Rest Framework (DRF)
I'm trying to create a POST API for users to vote on a given choice. But I keep getting the error below. What could be the problem? Thanks in advance! Internal Server Error: /polls/6/choices/19/vote/ Traceback (most recent call last): File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.vote_choice__old File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\models\base.py", line 879, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ..... ..... File "D:\Studio\Python\REST\elections\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: main.vote_choice__old [08/Aug/2021 17:09:09] "POST /polls/6/choices/19/vote/ HTTP/1.1" 500 193455 Here's the vote class in serializer.py: class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = '__all__' Here's the CreateVote class in apiviews.py: class CreateVote(APIView): serializer_class = VoteSerializer def post(self, request, pk, choice_pk): voted_by = request.data.get("voted_by") data = {'choice': choice_pk, 'poll': pk, 'voted_by': voted_by} serializer = VoteSerializer(data=data) if serializer.is_valid(): vote = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here's the URL Patterns code in urls.py: urlpatterns = [ path("polls/<int:pk>/choices/<int:choice_pk>/vote/", CreateVote.as_view(), name="create_vote"), ] And the models code looks like so in models.py: class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ("poll", "voted_by")