Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to create a new model with a foreign key associated to a previously visited model
I'm currently working on a web app, and I'm using config files to load up the names for certain models. How would I go about associating these created models to a foreign key associated to a parent model class that already exists in a different app. For example, I have the following models #Base models.py class Parent(models.Model): name = models.CharField() #Child models.py class child(models.Model): name = models.CharField() Parent = models.foreignKey('Parent', on_delete = models.CASCADE) The first base models will already exist within the database and will be used in a previous view. Then in the current views I'll call a function that will get or create a certain amount of child models, based on the number of rows in the csv file, and pass these generated models into the html template. What I'm not sure how to do is making sure that the models created in the function will have the appropriate foreign key that associates it to the right specific model used in the previous view. I'm still pretty new to Django so any help is appreciated. -
How to use correct oAuth2 redirect url in Django test case?
My Django webapp uses oAuth2 to get authenticated in Strava. I have a link in my webpage that sends a request to Strava indicating a redirect url amongst other arguments. In this example case http://127.0.0.1:8000/token_exchange Strava then makes a request to that url with the code to exchange for the access token. I have a view that does that exchange in that url. Everything works fine. My problem is that I am trying to build an automated test. But when I launch the tests (with python manage.py test) the server does not run in port 8000 but in a different port. Is there a best practice way to manage that redirect url so that it has production domain in production but uses the test server address when running the tests? Thanks!!! -
Getting Django ORM data to Javascript for evaluation
I have a ORM call that returns values from a database. I pass that to the HTML template, but need that data for a Javascript call. So the process is this: Form loads and calls ORM, gets values from Database (lets call it db_data) db_data is passed to HTML template return render(request, "foo.html", db_data) User in the UI clicks a button in foo.html On button click, JS function set_ui_data() is called set_ui_data() evaluates user selection and presents db_data to UI What is the proper way to give the data from db_data to a set_ui_data() method for evaluation? -
Django validate form with RangeWidget
I have a form: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ['name', 'description', 'slot',] widgets = { 'slot': RangeWidget(forms.DateTimeInput()), } I am receiving the form in the view: if request.POST: form = MyForm(data=request.POST) if form.is_valid(): But the form is never validated as the parameters posted are: name: 'TEST', description : 'fsd', slot_0: '2018/05/15 21:00:00', slot_1: '2018/05/15 21:30:00', submit: 'submit' The form.errors are: Enter a valid date/time. I assumed django would automatically create a tuple of datetime objects for the values posted, but apparently not. How can I validate this form and save it to the database? -
Django - Tutorial - Setting IndexView but Getting TemplateDoesNotExist
I have searched through all the questions here already on TemplateDoesNotExist. I have also been troubleshooting this for about 12 hours. There is something I am not understanding. I am new to django. I am following the following Thinkster tutorial: Building Web Applications with Django and AngularJS Here is the error: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\templates\index.html (Source does not exist) This is the code I do not understand, and I believe is where the problem lies. I think this is what changes the index.html or how to find it. This is inside my views.py and is same project folder where my urls.py is located. views.py from django.views.decorators.csrf import ensure_csrf_cookie from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator class IndexView(TemplateView): template_name = 'index.html' @method_decorator(ensure_csrf_cookie) def dispatch(self, *args, **kwargs): return super(IndexView, self).dispatch(*args, **kwargs) url.py from django.contrib import admin from django.urls import path, re_path, include from rest_framework_nested import routers from authentication.views import AccountViewSet from HawkProject.views import IndexView router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^api/v1/', include(router.urls)), re_path(r'^.*$', IndexView.as_view(), name='index') ] partial settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ … -
Using collections.Counter() with a Django queryset that has negative integers
As a follow-on to this question which was resolved using Counter(), I've run into a new problem that seems easy enough to fix - except I can't get it to work. I'm trying to use Counter() to sum a series of dict entries which works if the sum is a positive integer, BUT returns an empty element if the sum is a negative integer. I was able to find this answer which is right on point in explaining that Counter() is designed to count and not sum, per se. I can recreate the example and get it to work, but with a django queryset, when coupled with the Counter() method, generates a more complex dictionary that looks like this. totals = { 'sumthing_a': Counter({'total': 48000}), 'sumthing_b': Counter({'total': 39050}), 'sumthing_c': Counter({'total': 8950}), 'sumthing_d': Counter({'total': 10000}), 'sumthing_e': Counter({'total': 17200}), 'sumthing_f': Counter({'total': 17750}), 'sumthing_g': Counter({'total': 30450} } I've tried variations of: totals.update('sumthing_e: Counter({'total': 300})) which replaces the original 17200 with 300 rather than adding them. I've also tried: totals['sumthing_e'].update('sumthing_e: Counter({'total': 300})) which throws: unsupported operand type(s) for +: 'Counter' and 'int' The documentation for .update() states: Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds … -
Get Model-object from view?
My views.py file has many functions that eventually call a HttpResponse. They render a template, individually, that is report, with a chart This report, previously has to be added in the /admin. This makes the Report object, which has many fields, but I only need the one called 'codename', that was given in the /admin. How do i get the current Report-object related to the view? Views (part of it): @login_required def new_reservations(request): user = request.user client = [user.cliente_id] campaign_data, campaign = get_campaign_data( request.user, request.GET.get('campaign'), ) form = VideoConferenceUsageForm( data=campaign_data or request.GET or None, user=request.user, initial=campaign_data and {} or { 'ignore_test_calls': 1, 'ignore_weekends': 1, 'frequency': VideoConferenceUsageForm.MONTHLY, 'time_in_advance': ONE_YEAR_AGO, 'clients': client, } ) if campaign: campaign_form = ReportCampaignForm( instance=campaign, ) else: campaign_form = ReportCampaignForm( initial={ 'name': _('New campaign'), 'description': '', }, ) return render( request, "new_reservations.html", { 'form': form, 'create_campaign_form': campaign_form, 'campaign': campaign, } ) @login_required def new_reservations_json(request): form = VideoConferenceUsageForm( request.GET or {}, request.user ) form.is_valid() return HttpResponse( json.dumps( get_new_reservations( request, form.cleaned_data, form.get_interval(), ) ) ) -
Getting type error while trying to authenticate user
I'm trying to authenticate users using a custom MyUser model in Django version 2.0.4. However, when the code hits the check_password line in my custom backend module, I get this error: Error Traceback: Traceback: File "D:\Python\lib\site-packages\django\core\handlers\exception.py" in inner 35 response = get_response(request) File "D:\Python\lib\site-packages\django\core\handlers\base.py" in _get_response 128 response = self.process_exception_by_middleware(e, request) File "D:\Python\lib\site-packages\django\core\handlers\base.py" in _get_response 126 response = wrapped_callback(request, *callback_args, **callback_kwargs) File "d:\Programs\Python\Django\test2\accounts\views.py" in login_user 52 user = authenticate(request=request, email=email, password=password) File "D:\Python\lib\site-packages\django\contrib\auth\__init__.py" in authenticate 70 user = _authenticate_with_backend(backend, backend_path, request, credentials) File "D:\Python\lib\site-packages\django\contrib\auth\__init__.py" in _authenticate_with_backend 116 return backend.authenticate(*args, **credentials) File "d:\Programs\Python\Django\test2\accounts\backends.py" in authenticate 29 if MyUser.check_password(password): Exception Type: TypeError at /accounts/login/ Exception Value: check_password() missing 1 required positional argument: 'raw_password' Here is my custom backend from backends.py: class EmailAuthenticationBackend(ModelBackend): def authenticate(self, request, email=None, password=None): MyUser = get_user_model() try: # Check the email/password and return a user user = MyUser.objects.get(email=email) # BUG if MyUser.check_password(password): return user except MyUser.DoesNotExist: return None This is how the password come in. Login user view: def login_user(request): template_name = 'registration/login.html' if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request=request, email=email, password=password) While the error seems to be somewhat self explanatory, all the combos I've tried have failed. I've read the docs … -
Django: creating child objects within post_save
I have a site that updates data from a call to an API. So, in order to poll the API for the relevant fields, I have an "ingest_on_save" flag on the model, that's checked in a @pre_save handler, and after grabbing the API data will create or update the record. At the end of the @pre_save it turns the ingest_on_save to False and proceeds with save(). It works great! BUT the API also has pointers to child objects that are in a different model (e.g., a Book models with a FK to Author). If I change my Author model to also have a "ingest_books" flag, I can create/edit Books from it's @pre_save similarly (from the Author @post_save - necessary because I need the PK if the Author is newly-created to set the FK between Author and Book), but I can't figure out how to unset the Author.ingest_books since save() has already been called (and calling it from it's @post_save creates an infinite recursion loop). I've seen answers for other similar situations saying to use queryset.filter(pk=instance.pk).update except that there's no queryset that's reachable from @post_save (and those answers don't say how they were able to reach it)... ... ideas? -
In Django, for a OneToOne relationship between two objects of the same class, can an object be prevented from referring to itself at the db level?
I have the following in my app: class University(models.Model): ... sister_university = models.OneToOneField('self', related_name = 'university_sister_university', blank=True, null=True, on_delete=models.SET_NULL) As it is, under the Django Admin site, I’m able to select University A as the sister_university of University A (itself). Is it possible to enforce some sort of a rule at the database level so a university object can never be its own sister_university? Alternatively, is there a better way of accomplishing what I’m trying to do? -
Duplicate Title Tags with Django Pagination
I've recently deployed my website infortion. On the home page, I've used the django pagination so that users can see more content. Few days ago I connected the site to webmasters & it's showing an error Duplicate title tags in the HTML improvements section. Problem is coming from the home page because pagination is taking the users to next page but still keeping the same title. Which means these two pages, / /?page=2 will have the same title. How can we solve this problem? Thank You. -
Use Django signal when data is inserted into database from Scrapy
I would like to integrate Scrapy with Django. When I insert data into DB from Scrapy, Django signal is not working. This is the code snippet that is used for signal. @receiver(post_save, sender=Page) def create_page(sender, instance=None, created=False, **kwargs): if created: print('========== page created') This is pipeline.py that is used to insert data into DB. class CrawlerPipeline(object): def __init__(self, unique_id, *args, **kwargs): self.unique_id = unique_id @classmethod def from_crawler(cls, crawler): return cls( unique_id=crawler.settings.get('unique_id'), ) def close_spider(self, spider): pass def process_item(self, item, spider): site = Site.objects.get(id=self.unique_id) page = Page(url=item['url'], site=site) page.save() return item As you can see, data is inserted into DB on the Scrapy part and it works. But Django signal is not working as I expected. I am not sure how I can get Django signal to work. -
Button doesn't work in registration form: Django
Everything works fine but the button in the registration doc is not working, nothing happens when I click It...I have added the code for URLs , views and template below URLS from django.conf.urls import url from . import views urlpatterns = [ url(r'^register', views.register , name = 'register'), ] VIEWS def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('/index') else: form = UserCreationForm() else: form = UserCreationForm() args = {'form': form} return render(request, 'reg.html',args) REG.html <!DOCTYPE html> <html> <head> <title>Register</title> {% load staticfiles %} </head> <link rel="stylesheet" href=" {% static 'css/bootstrap.min.css' %}" type = 'text/css'/> <link rel="stylesheet" href=" {% static 'css/bootstrap-theme.min.css' %}" type = 'text/css'/> <link rel="stylesheet" href=" {% static 'css/fontAwesome.css' %}" type = 'text/css'/> <link rel="stylesheet" href=" {% static 'css/tooplate-style.css' %}" type = 'text/css'/> <body> <div class="container-fluid"> <h1> Registration form</h1><br> <img src="{% static 'img/53471658c4ed95e72a2ed6058361a367.jpg' %}" alt="HI" align="right"> <form method="post"> {{ form.as_ul }} <br> <button type="button" class="btn btn-primary">Register</button> </form> </div> </body> </html> Top 10 Tutorials HTML Tutorial CSS Tutorial JavaScript Tutorial W3.CSS Tutorial Bootstrap Tutorial SQL Tutorial PHP Tutorial jQuery Tutorial Angular Tutorial How To Tutorial Top 10 References HTML Reference CSS Reference JavaScript Reference W3.CSS Reference Bootstrap Reference SQL Reference PHP Reference HTML Colors … -
Filter queryset by checking element entrance in array in django
I have a movie model and it has genres array, which contains ids of Genre model. How can i filter movies by checking some one genre id entry in arrays of Film model? Just like Film.objects.filter(genres__in=[1, 4, 7]) but vice versa. Film.objects.filter(genres__has=genre_id) -
How to access a onetoone values from views in django?
So I have a KeyRequest Model and a KeyInstance model. One KeyRequest can only refer to one KeyInstance, vise versa. And each KeyInstance has an uuid and a status. I would like to access that uuid and the number of available keys in a KeyRequest Here is my models.py: class KeyInstance(models.Model): """ Model representing key instances. """ roomkey = models.ForeignKey('RoomKey',verbose_name="Room", on_delete=models.SET_NULL, null=True) keyrequest = models.OneToOneField('KeyRequest', verbose_name='Key requests', on_delete=models.SET_NULL, null=True, blank=True, related_name='request') LOAN_STATUS = ( ('a', 'Available'), ('o', 'On loan'), ('r', 'Reserved'), ) status = models.CharField(max_length=1, choices=LOAN_STATUS, help_text='Key availability', verbose_name="Key status", blank=True) date_out = models.DateField(null=True, blank=True, verbose_name="Date Issued") due_back = models.DateField(null=True, blank=True, verbose_name="Date to be returned") key_notes = models.CharField(max_length=2000, help_text='Key instance notes if applicable', null=True, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular key") borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ["due_back"] permissions = (("can_mark_returned", "Set key as returned"),) @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False def __str__(self): """ String for representing the Model object """ return '{1} ({0})'.format(self.id,self.roomkey.room_name) def get_absolute_url(self): """ Returns the url to access a detail record for this book. """ return reverse('keys',args={'pk':self.id}) class KeyRequest(models.Model): """ Model that will hold the key requests """ roomkey = models.ForeignKey('RoomKey',verbose_name="Room", … -
Django: Form for each entry of a model
I am trying to implement a form to edit a field 'comments' for each entry of a given model, which is in my case 'Rental'. class Rental(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) object = models.ForeignKey(Inventory, on_delete=models.CASCADE) quantity = models.IntegerField() returned = models.BooleanField(default = False) due_date = models.DateField() issue_date = models.DateField(default = datetime.date.today) comments = models.TextField(max_length = 500, null = True, blank = True) def __str__(self): return self.user.first_name + " - " + self.object.name I don't take input for comments when making a new record but the user should have an option to give a comment afterwards. I need to make multiple forms and user should be able to write a comment and submit it using a button exactly next to the box. I tried using formset and inlineformset but they don't do what I need. Is there any other way to solve this problem. Thank you in advance. -
how to get posted object in django rest framwork from a request
I am almost new to django and rest framwork. I want to get data of a request from client side and save a model's object. In my view.py file i have a class that extends from APIView(for example named CreateUser(APIView). From client side, I want to post a json file and get it in this view and save it in my models. How can I handle it? My Student class is: from django.contrib.auth.models import User from django.db import models class Student(models.Model): user = models.ForeignKey(User) grade = models.IntegerField() I have created a serializer for my Student class. from rest_framework import serializers from users.models import Student class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('username', 'password', 'grade') def create(self, validated_data): user = validated_data.get('user') grade = validated_data.get('grade') student = Student.objects.create(self, user=user, grade=grade) return student I want to get a json object with username password and grade and save it in my models. -
Getting Django error 'AnonymousUser' object is not iterable after redirecting back from Stripe page
So it is my understanding that this error comes about from trying to call request.user when a user isn't logged in. The problem I'm having is, I am using Stripe Connect Express so I can have users sign up with debit card or bank account for payouts in my marketplace app. This redirects the user to stripe for a few pages. When Stripe collects the data it needs it redirects the user back to my page where I use request.user to pull their info from the database so I can save Stripe data to their table. I'd say about 50% of the time this is successful and the other half I get the error TypeError at /pricing/ 'AnonymousUser' object is not iterable This leads me to believe that the user is logged out sometime during the redirect to Stripe. Is there a solution to this issue? Is my session expired? Did the CSRF token change? Also, Stripe allows you to pass a 'state' query parameter in the POST request to them which they suggest to is for matters like CSRF tokens. They then return this 'state' to you in the redirect GET request they send from their servers. Can I … -
Can't see my project's strings in Django Rosetta
I have installed and configured rosetta on my Django project and I can say it is working because I can see multi-language features with Django admin and I can see strings to translate in third party and django tabs, but when a chose project tab I get this message: Nothing to translate! You haven't specified any languages in your settings file, or haven't yet generated a batch of translation catalogs. Please refer to Django's I18N documentation for a guide on how to set up internationalization for your project. I have already used gettext() in my code but I can't see those strings in rosetta. This is an example of the use of gettext() in my models.py: from django.utils.translation import gettext as _ class Hotel(models.Model): ONE_STAR = '*' TWO_STARS = '**' THREE_STARS = '***' FOUR_STARS = '****' FIVE_STARS = '****' GRAND_TOURISM = 'GRAND_TOURISM' NA = 'NA' SPECIAL = 'SPECIAL' ECO = 'ECO' BOUTIQUE = 'BOUTIQUE' HOTEL_CATEGORY_CHOICES = ( (ONE_STAR, _('*')), (TWO_STARS, _('**')), (THREE_STARS, _('***')), (FOUR_STARS, _('****')), (FIVE_STARS, _('*****')), (GRAND_TOURISM, _('Grand Tourism')), (NA, _('NA')), (SPECIAL, _('Special')), (ECO, _('Eco-Hotel')), (BOUTIQUE, _('Boutique-Hotel')) ) This is the configuration of languages in settings.py: LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', … -
SMTPRecipientsRefused: Sender address rejected: not owned by user
I have a Django app running on a server with uWSGI and nginx. In my local_settings.py file I have this: ############### # EMAIL SETUP # ############### EMAIL_HOST = 'smtp.privateemail.com' EMAIL_HOST_USER = 'support@mydomain.com' EMAIL_HOST_PASSWORD = 'MY EMAIL PASSWORD' EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True ######################## # OTHER EMAIL SETTINGS # ######################## ADMIN_EMAIL = "admin@mydomain.com" SUPPORT_EMAIL = "support@mydomain.com" DEFAULT_FROM_EMAIL = ADMIN_EMAIL SERVER_EMAIL = ADMIN_EMAIL I run python manage.py runserver on my local machine in the Django project's virtual environment. I fill out the password reset form at password_rest/ using the email my.personal@gmail.com and submit it. I get this error. SMTPRecipientsRefused: {u'my.personal@gmail.com': (553, '5.7.1 <admin@mydomain.com>: Sender address rejected: not owned by user support@mydomain.com')} My website's email provider is Namecheap. Why do I get this error when testing on my local machine? What must I change/add to get rid of it? -
If object count greater than 1000 , display 1k in template view
I am very new in django. I am trying to do something like facebook ,where by if the number of comments on a picture is equal to 1000, instead of displaying 1000comments , i want 1k comments is displayed to the users. I did something like this view code def DisplayPic(request,slug): # this get the object of the image AdvertObj=get_object_or_404(Images,slug=slug) #to get comment objects belonging to the image .Company stands for image instance comments=ProductComments.objects.all().filter(company=AdvertObj) #get the total comment count belonging to the image commentcount=comments.count() # now verify if comment count is greater than 1000 # if comment count greater than 1000 or equal to 1000 , 1K+ comments display instead of showing 1000+ comments 1kcomments displayed if commentcount>=1000: r=commentcount/1000 #(to reduce values to be displayed to users in 1k+) return r context{'count':commentcount} template_name='templat.html' return render(request,template_name,context) I get an error when ever commentcount is greater than or equals to 1000 counts ** error 'float' object has no attribute 'get'** I know i my approach is completely wrong . Please help me . My end result is to display if commentcount is 1000 , instead of displaying 1000comments to users , 1kcomments is displayed . Thanks for your help -
Hosting a Django website on a Server
Im still a beginner, and this is the first time I'm working on a project. I'm currently using Django 2.0.5 for Pycharm-2018.1.2 (on KaliLinux). I recently started working on my first project for an internship. I was told a little while ago to host the website on their own server. This is the first time I'm hosting a website and i have no clue how to do it. They did specify that they wanted to host it on a Windows server which uses MySql. I've used Sqlite for the the database while creating the website. How do i Migrate to MySql? Questions: 1) What are the changes I'll Have to make in the application to get ready to be uploaded onto the server? 2)How do i Migrate to Mysql? 3) How do i use MySQL on Django? Is it the same as Sqlite? If i work on Models.py, will it work on creating the database and linking it to the application? 4)(dumb question) Can i Upload my website onto a windows server using my Linux OS? 5) How do i get my 404,500 error pages working? Everytime i Put Debug= False, the website doesnt even load. \BugReport \BugReport \__init.py__ \settings.py … -
Python Django URL Match Issues with Anchor Tag
I have a question regarding why Django isn't matching my the url in an anchor tag in my template. I'm finding that in this one instance, if I put a button inside an anchor tag, Django won't match it because it looks for a trailing slash. If I put the button inside a form, it matches fine. <a href="/reset"><button>Reset my account</button></a> The above code returns a 404 error: Using the URLconf defined in main.urls, Django tried these URL patterns, in this order: ^admin/ ^ ^$ ^ ^process$ ^ ^checkout$ ^ ^reset$ The current URL, reset/, didn't match any of these. If I put the button inside form tags, it works fine: <form action="/reset"> <input type="submit" value="Reset my account"> </form> Alternately, if I add a trailing slash to the path in my_app/urls.py, the anchor tag will work: url(r'^reset/$', views.reset) Why is Django trying to match a trailing slash in this instance? I have used this approach before without issue. Thanks! -
Django send email not working
I'm trying to send email through my Django app. I have this in my settings.py: EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = '`132312123' EMAIL_HOST_USER = 'mimic@gmail.com' EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER and my api.py: class sendEmailViewSet(ModelViewSet): queryset = Candidature.objects.all() serializer_class = CandidatureSerializer def get(self, request, *args, **kwargs): send_mail('Object', 'Here is the message.', 'wajihkatrou@gmail.com', ['marwenop@gmail.com'], fail_silently=False) Im not getting any error but when i send a get request nothing happens. How do I make my app send emails properly? -
jQuery + django sending ordered list of numbers
I have a simple task list that the user can choose how to order. When the user order the tasks I want to send all the tasks' IDs in their order to the server. In short, what is the most convenient to send a javascript array and fetch the values in django view? If I do this: // tasks is an array of numbers, e.g [1,2,3,4] $.post('/save_tasks/', {tasks: tasks}).done(...) then I can access them in the view with request.POST.getlist('tasks[]') But this does not guarantee the order.