Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do PUT request without primary key?
I'm creating a Like/Dislike api for a blog using DRF. I have Like table which contains "Post", "User" and "isLike" fields. Since Django can't have composite key, I'm using unique_together constraint for ("Post" and "User"). If a user likes a post, I create a entry in Like table. Now if a user wants to remove his like from the post or want to dislike the post, I need primary key of entry from Like table for these (PUT/DELETE) methods. Since I know "User" and "Post", and since both are unique, Can I perform (PUT/DELETE) methods with unique fields? Model class class LikeDislike(models.Model): """model for like counts""" post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) isLike = models.BooleanField() class Meta: unique_together = (("post", "user"),) View for creating entry in Like table: class LikeDislikeCreateView(generics.CreateAPIView): queryset = models.LikeDislike.objects.all() serializer_class = serializers.LikeDislikeSerializer def perform_create(self, LikeDislikeSerializer): LikeDislikeSerializer.save(user=self.request.user) I can update a like/dislike using -> /like/primary-key/ but I want to do using "post" and "user" details. -
How to display a multi layer JSON in Django template?
So I have this JSON response: { "orders": [ { "orderId": "4123456789", "dateTimeOrderPlaced": "2017-02-09T12:39:48+01:00", "orderItems": [ { "orderItemId": "2012345678", "ean": "0000007740404", "cancelRequest": false, "quantity": 10 } ] } ] } I passed it in my view with the .json() method. I use this in my template: {% for key, value in orders.items %} {{ key }}: {{ value }} {% endfor %} I get this in my HTML: orders: [{'orderId': '2529081520', 'dateTimeOrderPlaced': '2019-09-07T00:12:16+02:00', 'orderItems': [{'orderItemId': '2298728074', 'ean': '8945005881389', 'cancelRequest': False, 'quantity': 1}]}] But how to dissect it further? For example to get the OrderId or the ean? -
How do I send cookies stored in variable in views to front-end of user display?
I stored recently viewed deals/items in cookies using javascript in ###array format. Then I created a view to get the cookies values stored ###and push them to frontend of user so he can watch the recently viewed ###items. I tried playing with the named variables in js code and also tried ###changing the name of the variables to same but I'm getting errors Views.py def view_deal(request, id): try: deals = Deal.objects.get(id=id) category = ProductGroup.objects.get(id=deals.product_group_id) similar = Deal.objects.filter(product_group_id=deals.product_group_id).exclude(id=id) recent = request.COOKIES["recentlyview"] recentDeals = Deal.objects.filter(['recent']) print(recentDeals) except Deal.DoesNotExist: deals = None try: comment = Comment.objects.filter(deal_id=deals).order_by('-created_on') except Comment.DoesNotExist: comment = None return render(request, 'frontend/view-deals.html',{'comment':comment, 'deal':deals,'similar': similar, 'recentDeals':recentDeals}) -
Use email as authentication field and add email verification on django custom user model
I have this custom user model on my Django project. I want to make the email as authentication field instead of the username. Also, I want to perform an email verification. models.py class es_user(models.Model): user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE), is_activated = models.BooleanField(default=False) def get_absolute_url(self): return reverse('user_detail', kwargs={'id': self.pk }) view.py def signup(request): signup_form_instance = SignUpForm() if request.method == "POST": signup_form_instance = SignUpForm(request.POST) if signup_form_instance.is_valid(): signup_form_instance2 = signup_form_instance.save(commit = False) username = signup_form_instance2.username password = signup_form_instance2.password signup_form_instance2.password = make_password(signup_form_instance.cleaned_data['password']) signup_form_instance2.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) active_user = request.user es_user_instance = es_user.objects.create(user= active_user) # return index(request) return redirect('index') # return user_detail(request)#successful signup redirect or return # return redirect('user_detail',id = [str(request.user.id) ])#kwargs={'id': request.user.id }) else: print("SIGN UP FORM INVALID") return render(request,'signup.html',{'signup_form':signup_form_instance}) forms.py class SignUpForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'password') # for adding bootstrap classes & placeholders widgets = { 'username': TextInput(attrs={ 'class':'form-control', 'placeholder': 'Username *'}), 'email': EmailInput(attrs={ 'class':'form-control', 'placeholder': 'Your Email *'}), 'password': PasswordInput(attrs={ 'class':'form-control', 'placeholder': 'Your Password *'}), } help_texts = { 'username': None, } # to remove labels in form labels = { 'username': (''), 'email':(''), 'password':(''), } My project is near completion so I cannot change my user model … -
Error:variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.?
i've deployed login related project in server its not working properly and error showing variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.in console -
How to download CSV file in Django?
I created a small Django project for amazon products scraping. But don't know how to download the CSV file. I am a beginner in this so I don't know how to give a download link, so I haven't tried anything from django.http import HttpResponse from django.shortcuts import render import requests from bs4 import BeautifulSoup import csv import re def index(request): url = request.POST.get('url', '') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) with open('product_file.csv', mode='w') as product_file: product_writer = csv.writer(product_file) for name,price in zip(p_name,p_price): product_writer.writerow([name.text, price.text]) return render(request, 'index.html') -
Django Wagtail sitemap
I have an existing Django site for which i've added Wagtail. I would like to have a sitemap for both Django and Wagtail urls. My current sitemap.py: class StaticSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = "weekly" protocol = "https" def items(self): return ["public:index", "other pages etc..."] def location(self, item): return reverse(item) My current urls.py: sitemaps = {"static": StaticSitemap} path( "sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), The above works correctly for a standard Django sitemap. How do I include Wagtail urls? -
How to rename a model field from default Django model?
I would like to rename all the Groups field in Django admin as Roles field. But there are still some parts that didn't changed. I have successfully renamed Groups into Roles but then a field in the Users still has the name 'Groups' in it. I know it has something to do with the PermissionsMixin in django.contrib.auth.models which contains the ManyToManyField named groups that is being called in the UserAdmin. I would like to know how to rename this model field. This is the field that I want to rename. -
Access specific post data using request.data Django Rest framework
I am trying to get specific data from my post request. My code is: @api_view(['POST']) def create_user(request): if request.method == 'POST': first_name = request.data['first_name'] last_name = request.data['last_name'] This does not give me the information with the keywords. I have tried request.data.get(), request.POST[], request.POST.get(),... but none of these work. Thanks in advance -
Unable to locate sass file
I have a sass file in my django project the path inside my project is the following: Project\Project\static\style\file.scss but when i run the command python manage.py runserver i get the following error message: "Unable to locate file Login.scss while rendering tag 'sass_src' in template None" but when i create the sass file inside the following path "D:\Python\Lib\site-packages\django\contrib\admin\static " my webpage can identify my sass file and work normally. how can i do to make my webpage identify the sass file that is located in a folder inside the project like the following: "Project\Project\static\style\" ---------------- html ------------------------------ {% load sass_tags %} import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sass_processor', ] 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 = 'CvProject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CvProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',}, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Django-rest-framework API test 403 {'detail': 'You do not have permission to perform this action.'}
I'm currently writing a test to test my get request, the get request require jwt access_token in the header which i'm using django-rest-framework-simplejwt to get the token as well as using it as default authentication class settings.py: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',) } My test_api.py: from rest_framework.test import APITestCase from rest_framework import status from rest_framework.test import APIClient from django.urls import reverse from listing.models import Property from backend.models import User class PropertyTestCase(APITestCase): def setUp(self): property_1 = Property.objects.create(title="test", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 1", type="sell", category="category 1", address="address 1", lat=21.027763, long=105.834160, images=["https://avatars2.githubusercontent.com/u/46511495?s=88&v=4"], contact_name="name 1", contact_address="test address 1", contact_phone="0923512213", contact_email="test@gmail.com", frontend=322, road=32, floor=4, bedroom=5, living_room=6, toilet=2, direction="Nam", balcony="Nam", meta_data={"menu": {"id": "file", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}, "value": "File"}}) property_1.save() property_2 = Property.objects.create(title="test2", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 2", type="rent", category="category 2", address="address 2", lat=21.027763, long=105.834160, images=["https://avatars2.githubusercontent.com/u/46511495?s=88&v=4"], contact_name="name 2", contact_address="test address 2", contact_phone="0923512213", contact_email="test2@gmail.com", frontend=322, road=32, floor=4, bedroom=5, living_room=6, toilet=2, direction="Nam", balcony="Nam", meta_data={"menu": {"id": "file", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}, "value": … -
Django: How can I use templating to add a header to each HTML page, and only update one central file?
I have about 12 different HTML pages in my Django application. I am looking for a way to make my header in 1 template file, and then add that file to each HTML template that I need a header on. I tried following the template documentation from Django, but it wasn't concise enough for me. Would anyone be able to please break it down a little further for me? I am basically starting at square 1 with this... I was at a point where I was able to get a header to load, but no css was attached to it. I have since erased the code because I didn't want to screw anything up. -
Django2.1 : Queryset ModelChoice in a ModelForm then save two forms
I want the current logged in user to be able to create and save both forms. The second form has a ManyToManyField and ForeignKey relationships as you can see below. Currently I have tried to queryset the current user from ChatGroupUser ModelForm. With the current codes, as soon as I try to access the page, Django raise the error below: __init__() missing 1 required positional argument: 'user' it says that the error comes from line 88, which is: form_user = ChatGroupUserForm() Full Traceback Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/Groupixx/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/Groupixx/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/Groupixx/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/Groupixx/groupixx/core/views.py", line 88, in create_group form_user = ChatGroupUserForm() TypeError: __init__() missing 1 required positional argument: 'user' models.py class ChatGroup(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='chat_group_admins') is_active = models.BooleanField(default=True, null=True) is_current = models.BooleanField(default=False, null=True) class ChatGroupUser(models.Model): user = models.ManyToManyField(User) chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, related_name='chat_group_users') forms.py class ChatGroupForm(forms.ModelForm): class Meta: model = ChatGroup fields = ['name',] class ChatGroupUserForm(forms.ModelForm): #user = forms.ModelMultipleChoiceField(queryset=User.objects.all()) class Meta: model = ChatGroupUser fields = ['user'] def __init__(self, user, *args, **kwargs): super(ChatGroupUserForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = … -
How can I filter django queryset again to get unique parameters?
Hi I am trying to receive one last message per user. I have filtered out messages but I am getting many messages for one user. How can I get last message of user. queryset=MessageModel.objects.filter( Q(sUser=self.request.user) | Q(rUser=self.request.user) ).order_by('-id') return queryset I am getting this list from filtering. { "message": "Hi b do you want to buy? 2", "sUser": 1, "rUser": 15, "sent": true, "pk": 8, "user": { "pk": 15 } }, { "message": "a to c", "sUser": 1, "rUser": 16, "sent": true, "pk": 7, "user": { "pk": 16 } }, { "message": "No thanks not buying this time", "sUser": 15, "rUser": 1, "sent": false, "pk": 6, "user": { "pk": 15 } }, { "message": "c to a", "sUser": 16, "rUser": 1, "sent": false, "pk": 4, "user": { "pk": 16 } }, { "message": "Hi b do you want to buy?", "sUser": 1, "rUser": 15, "sent": true, "pk": 1, "user": { "pk": 15 } } ] I want to get message with pk 8 and 7 only because its last message to user 15 and 16 but I am getting all messages. -
Nesting fields in serialization use custom fields with Django REST framework
I'm trying to serialize foreikey to another name. For example: class User(models.Model): user_name = models.CharField(..) class Blog(models.Model): user = models.ForeignKey(User, ...) title = models.CharField(...) class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' when use BlogSerializer(blog_instance).data can get the data: { "id": 1, "user": 1, "user_info": {"id": 1, "user_name": "admin"}, "title": "hello world" } -
How to OneToOneField have many table?
I want to make this. Class Post has ContentId (OneToOneField) Class PostContent has postId (OneToOneField) Class PostContentClub has postId(OneToOneField) both PostContent and PostContentClub are Post. but, the contents are different. So, I want to share them. How do I write the code? -
django-rest-framework- Filtering using 'or' on multiple values from one url parameter
I have a tagging system in place for a model that my API exposes. The models look something like this: class TaggableModel(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name="taggable_models") class Tag(models.Model): tag = models.CharField(max_length=32) I've then set up a serializer and view that look like: class TaggableModelSerializer(serializers.ModelSerializer): class Meta: model = TaggableModel fields = ('id', 'name', 'tags',) read_only_fields = ('id',) class TaggableModelViewSet(viewsets.ModelViewSet): queryset = TaggableModel.objects.all() serializer_class = TaggableModelSerializer permission_classes = (AllowAny,) filter_backend = [DjangoFilterBackend] filterset_fields = ['tags'] If I want to grab all TaggableModels that have tag ids 1, 2, or 3, I can do so via: https://my-api-domain/api/taggable-models?tags=1&tags=2&tags=3 Is there a way to split on a delimiter, so I can pass it all as one parameter? e.g.: https://my-api-domain/api/taggable-models?tags=1,2,3 It looks like I can write my own custom DjangoFilterBackend filters, but I am a bit unsure as to where to start. Or perhaps there is an easier way to accomplish this? -
search data for table template by django.can't not show next page >
i'm create template for search this table.it can search but click for next page is error in the picture For Error Same mycode. @view.py def search(request): query = request.GET.get('q1') qselect = request.GET.get('q2') qs = Record_data.objects.filter(Q(invoice_no__startswith=query) | Q(product=query)) page = request.GET.get('page', 1) paginator = Paginator(qs, 5) try: page1 = paginator.page(page) except PageNotAnInteger: page1 = paginator.page(1) except EmptyPage: page1 = paginator.page(paginator.num_pages) template_name = 'status.html' context = {'object_list': page1} # page function @html code {% if object_list.has_other_pages %} <ul class="pagination"> {% if object_list.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ object_list.previous_page_number }}">Previous</a></li> {% else %} <li class="page-item disabled"><span class="page-link">Previous</span></li> {% endif %} {% for i in object_list.paginator.page_range %} {% if object_list.number == i %} <li class="page-item active"><span class="page-link">{{ i }}</span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if object_list.has_next %} <li class="page-item"><a class="page-link" href="?page={{ object_list.next_page_number }}">Next</a></li> {% else %} <li class="page-item disabled"><span class="page-link">Next</span></li> {% endif %} </ul> {% endif %} -
How to make a horizontal navigation bar?
I am trying to make a website with a horizontal navigation bar. I found a useful reference, but I couldn't figure it out to be adopted to my current code since I am not an expert with HTML and CSS. I like to create similar bar like this: ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } /* Change the link color to #111 (black) on hover */ li a:hover { background-color: #111; } And below are my current code: {% block sidebar %} <ul class="sidebar-nav"> <li><a href="{% url 'index' %">Home</a></li> <li><a href="">All users</a></li> <li><a href="">All productss</a></li> <!-- <li><a href="">All vendors</a></li> --> </ul> {% endblock %} .sidebar-nav { margin-top: 20px; padding: 0; list-style: none; } -
Django Template Not Extending
I'm trying to extend a base template in Django named 'base.html' in my main page 'index.html' and it does not work as expected. Rather than extending the template, the page just displays {% extends 'base.html' %}, plus the HTML in index.html when displaying the index page. The 'base.html' page sits in the root of my templates folder and my 'index.html' page sits in templates/pages. In 'base.html': {% load static %} ...some code... {% block content %} {% endblock %} ...some code... In 'index.html': {% extends 'base.html' %} {% load static %} {% block content %} ...some code... {% endblock %} In views.py: def index(request): return render(request, 'pages/index.html') In settings.py: TEMPLATES = [{'DIRS': [os.path.join(BASE_DIR, 'templates)] Expected Result: Navbar Content Actual Result: {% extends 'base.html' %} {% block content %} Content {% endblock %} -
Pyzipcode city lookup not working properly
Trying to get the city from the zip code, so I installed the pyzipcode package. However, whenever I try to get the city I get the following error. The state, zipcode, lat/long work normally. I've tried numerous zipcodes and none of them seem to pull any city records. from pyzipcode import ZipCodeDatabase zcdb = ZipCodeDatabase() zipc=zcdb['29839'] zipc.city Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ZipCode' object has no attribute 'city' The documentation for the package uses 'city' as an example. -
Send notifications through DRF
Hello I'm building a RESTfull application using Django Rest Framework. The clients are android application and react application. I need to send a time based notification to users. -
No errors in custom login form
I've created a custom login form with Django, but incorrect logins don't generate form errors. What do I need to do to get errors passed through the form? class CustomUserLoginForm(forms.ModelForm): class Meta: model = User fields = ['email', 'password'] password = forms.CharField(widget=forms.PasswordInput) widgets = { 'password': forms.PasswordInput(), } -
How to load data into Django template using render and filter loaded data using AJAX requests?
I'm loading data into my template using render. The data I'm sending to the template includes objects called course and reviews. Course has an array of instructors, while each review has one instructor. I'm listing out all the instructors associated to a course as a button on the template, and I would like to filter reviews based on which instructor button the user clicks. I'm already sending the data from the server to the template, but I'm thinking I need to use AJAX in this. Any ideas on how to do this and would it be possible to do this without sending another request to the server and utilizing the data that has already been sent to the template? template {% for instructor in course.instructors %} <button class="ui button"> {{ instructor }} </button> {% endfor %} {% if reviews %} {% for review in reviews %} <p>Usefulness: {{ review.usefulness_rating }}</p> <p>Difficulty: {{ review.difficulty_rating }}</p> <p>Instructor: {{ review.instructor_rating }}</p> <p>Comment: {{ review.comment }}</p> <p>Instructor: {{ review.instructor }}</p> <p>Session: {{ review.taken_season }} {{ review.taken_year }</p> How should I implement the AJAX for this? -
Select value from field with type foreignkey
"""I am creating an API (comments) using DRF. And now I'm confused, I need to get an album so that I can completely create my api, but so far all other fields except the album come. album = serializers.CharField (source = 'comments.name_album', read_only = True) does not help. That's all I get in the answer {"album":"","post":"ahsdh","author":"philip","text":"ahsdhah"}""" class AlbumCreateSerializer(serializers.ModelSerializer): album = serializers.CharField(source='comments.name_album', read_only=True) class Meta: model = Comments fields = [ 'album', 'post', 'author', 'text', ] #apiview class AlbumCreateAPIView(CreateAPIView): queryset = Comments.objects.all() serializer_class = AlbumCreateSerializer permission_classes = [IsAuthenticated, IsAdminUser] def post(self, request,pk=None, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ready_data = serializer.save() return Response(ready_data.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) #model class Comments(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='comments') post = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=500) publish_date = models.DateTimeField(default=timezone.now()) def __str__(self): return self.text #ajax$ ('#post_form').on('submit', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: 'http://localhost:8000/api/albums/create/', data: { 'post': $('#post').val(), 'text': $('#text').val(), 'author': $('#author').val(), 'album': $('#album').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ console.log(data); } }); }); #html form <form id="post_form" method="post" action="/api/albums/create/"> <input type="hidden" name="csrfmiddlewaretoken"> <input type="hidden" id="author" value="{{ user }}"> <input type="hidden" id="album" value="{{ comments.name_album }}"> <input type="text" id="post"></br> <input type="text" id="text"></br> <button>submit</button> </form>