Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django restrict user to edit data which doesnt belongs to them
I have a url, localhost:8000/user/data/edit/1 In the above, 1 is the data's id which belongs to user=x ! Likewise i have 1000's of data Now when i log in as user=y and go the same link, it opens the edit page ! But data 1 is belongs to user=x - how to handle this ? How to restrict this ? Does django do this automatically or we need to do this manually ? -
How can i active or passive options Django Admin
I have a form option in my Django application. I want to be able to activate or deactivate some options from the admin panel. How can I go about this? <div class="form-group"> <label for="username">Username</label> <input type="text" placeholder='Username' class="form-control" name="username"> <br> <label for="type">Bonus Türü</label> <select name="bonuses" id="test" id='testvalue' class="form-control"> <option selected value="0">Please select</option> <option value="2">Taste </option> <option value="36206">Taste 1 </option> <option value="58013">Taste 2</option> <option value="55908">Taste 3</option> <option value="21310">Taste 4</option> </select> </div> For example, with a feature I added to the admin panel, I want to disable the 4th option and activate it whenever I want. This is my admin.py from django.contrib import admin from .models import Bonusrequest class adminPlus(admin.ModelAdmin): list_display = ("username","name","bonus","result","created","descrpt") admin.site.register(Bonusrequest,adminPlus) -
Create Django abstract child model refering to the table of the parent model
I have a model (Parent) that has a table in the database (table app1_parent) in a first app (app1). In another app (app2), I would like to add functionnality to this Parent model, but still refer to the existing Parent table (table app1_parent), which is part of the other app (app1). If I create in app2 the Child model that simply inherite from Parent, I end up with two different tables: app1_parent and app2_child I'd like to know if I can create an (abstract ?) child model (Child) that refers to the table of the Parent model, without adding additional field, but adding new methods and properties. (Basically I would want to do the contrary of what abstract tables have been built to do) class Parent(models.Model): my_field = models.CharField(max_length=255) class Child(Parent): def my_method(self): return 'done' class Meta: abstract = True Is there another way to achieve my result? PS: of course, the objective would be not to modify the app1.Parent model and app1.parent table -
can we plot dendrogram on frontend by using django backend
I am working on a clustering based project where I have to perform dendrogram operation on backend and to plot that chart on front-end using any javascript based framework (angular). So I know how to do it in python but on front-end how can I plot that because the data from python SciPy library is like nested lists which use line plots while in front-end libraries they accept data as parent child relation. In case I am not clear then do let me know. -
How to serialize two nested django tables?
Album is being generated, files are being associated with album table, but the question is how i'll serialize both tables to show response on post request. waiting for help. -
how can i get data of a variable or something in javascipt in veiws.py in django? [duplicate]
i was working on a shopping website . and in this case the products that i have in my cart is in the localstorge . i want to get them with localstorge.getitem commend and then i want to have access to them in the views.py to send them with a email . this is the views.py def cart(request ) : sent = False if request.method == "POST" : form = emaildtata(request.POST) if form.is_valid() : cd = form.cleaned_data name = cd["name"] add = cd["add"] num = cd["num"] num2 = cd["num2"] postcode = cd["postcode"] msg = "name : "+name+" | addres : "+add + " | number : "+num +"/"+num2 + "postcode : "+postcode send_mail("سفارش جدید" , msg , "kkmbcmbc@gmail.com" , ["alirezajavanpour789@gmail.com"]) sent = True return render(request , "site/cart.html" , {"form" : form , "sent" : sent}) food = realitems.objects.all() form = emaildtata() context = { "posts" : food, "form" : form } return render(request , "site/cart.html" , context) okay and its my forms.py class emaildtata(forms.Form) : name = forms.CharField(max_length=24 , label="نام و نام خانوادگی") add = forms.CharField(max_length=210 , label="ادرس تحویل" , widget=forms.Textarea) num = forms.CharField(max_length=13 , label="شماره تماس") num2 = forms.CharField(max_length=13 , label="شماره تماس 2" ,required=False) postcode = forms.CharField(max_length=10 , label="کد … -
How to paginate/search/filter objects simultaneously. Query parameters [Django]
I have 3 different forms in my html template: to filter, search and paginate results. I want there to be an option to do that simultaneously: shop/?filter_by=diary_products&paginate_by=6 shop/search/?q=milk&filter_by=diary_products&paginate_by=6 The problem is when form is been submitted. Query parameters does not append, so i cannot reach the above mentioned result. Search form <form action="{% url 'search_products' %}" method="GET"> {% csrf_token %} <button type="submit">Search</button> <input type="text" name="q" placeholder="Search"> </form> Select form to choose items per page (pagination) <form action="{% what should i put here? %}" method="GET"> <select name="paginate_by" onchange="this.form.submit()"> <option selected>1</option> <option>2</option> <option>3</option> </select> <noscript><input type="submit" value="Submit"></noscript> </form> Filter form <form action="{% what should i put here? %}" method="GET"> <select name="filter_by" onchange="this.form.submit()"> <option selected>diary_products</option> <option>by_price</option> <option>newest_first</option> </select> <noscript><input type="submit" value="Submit"></noscript> </form> urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.shop, name='shop'), path('search/', views.search_products, name='search_products'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Jquery plugin for fixed column with django formset
Did any one use any jquery plugin for fixed columns with Django formset. The django formset is normal table that have events to create or delete row. I have try with css sticky property but it doesn't work. The DataTables fixedColumn is not suitable for django formset table. You can look her for more inforamtion about the django formset blugin. -
django specify column arrangement in SQL Server
I am using Django ORM to create my database tables and perform the rest of the operations. However, I've noticed that the columns if I see in the database are not in the order I specify in the django models. For example, my model is class ItemMetaData(models.Model): item = models.ForeignKey(Item, on_delete=CASCADE) field = models.CharField(max_length=80) field_value = models.CharField(max_length=80) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) But in the database when I see the table, the foreign key is the last column so it looks like id | field | field_value | created_at | modified_at | item_id I would like my item_id to be the first column after id . Like this: id | item_id | field | field_value | created_at | modified_at Is this possible? I tried to search but when I look for ordering all the answers assume it's row ordering and suggest using order_by -
How to send some value if unchecked for each checkbox with same name?
Here I have multiple checkbox with same name. Checkbox can be added to n no. of times. Here if already checked I want to send 1 and if not 0. Right now in my django backend I am getting the list like this. If all checked [1, 1, 1] which is fine . if only one checked [1] but I want like this [1, 0, 0] <input name="need_a" type="checkbox" class="custom-control-input" value="1" {% if some_condition %}checked{% endif %}/> <input name="need_a" type="checkbox" class="custom-control-input " value="1" {% if some_condition %}checked{% endif %}/> <input name="need_a" type="checkbox" class="custom-control-input" value="1" {% if some_condition %}checked{% endif %}/> -
Can I test celery with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked))?
I have celery task that create new Alert objects after 3 days from the POST action, and I want to test that. I create a test that assert assert Alert.boject.count() == 0 right now and it assert that the alert will be 1 after 3 days. But, the alerts returns 0 instead of 1 My code is so complicated and long so it is not practical idea to share it Goal I just need to know if the mock.patch actually work on celery countdown functions. res = self.client.post('/alerts/rules/', data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) i = now + delta_time(3,'days') mocked = datetime.datetime(2021, 4, i, 0, 0, 0, tzinfo=pytz.utc) assert Alert.boject.count() == 0 with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked)): assert Alert.bojects.count() == 1 -
UnitTest for Django Inline Formset
I have a formset with custom validation logic: forms.py class MyFormSet(BaseInlineFormSet): def clean(self): super().clean() forms = list(filter(lambda form: len(form.cleaned_data), self.forms)) if not forms or any(self.errors): return for form in forms: ... And I use this custom formset in admin-site models: admin.py class MyInline(admin.TabularInline): formset = MyFormSet model = ClientAgreement class ClientAdmin(admin.ModelAdmin): form = Client inlines = [ MyInline ] So what I want to do now - test my custom clean logic in unit test. Inside the test I create formset with: formset = inlineformset_factory(Client, ClientAgreement, formset=MyInlineFormSet, fields='all') After that I create instance with my object: object_formset = formset(instance=client1) Now I can see all prepopulated test data inside object_formset according to ClientAdmin model. But how can I pass changes to forms data to check my clean logic? Or maybe there is different path to solve this? -
ValueError: too many values to unpack (expected 2) Django
Not sure why but my code is getting the following error: ValueError: too many values to unpack (expected 2) Here is my models.py: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.list_name Here is my views.py def otherUserList(request): userName = request.GET.get('userName', None) print(userName) qs = UserList.objects.filter(user__username=userName) return qs Here is the traceback: Internal Server Error: /electra/otheruserlist/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) [02/Sep/2021 05:38:43] "GET /electra/otheruserlist/?userName=alice HTTP/1.1" 500 94227 I'd be very grateful for any assistance. -
Django Send email for new model object create
I want to send email if user placed a new order. I want to do the send email function from my models.py. Is it possible?? I setup my settings.py for email. I am looking for a easiest way to do this. I don't want to touch my views so is it possible? #this is my Order model class Order(models.Model): PENDING_PAYMENT = 'Pending Payment' ON_HOLD = 'On Hold' status_choices = [ ('Cancel', 'Cancel'), ('Pending Payment', 'Pending Payment'), ('On Hold', 'On Hold'), ('Waiting For Payment', 'Waiting For Payment'), ('Processing', 'Processing'), ('Done', 'Done'), ] orderstatus_choices = [ ('Cancel', 'Cancel'), ('Pending Payment', 'Pending Payment'), ('On Hold', 'On Hold'), ('Waiting For Payment', 'Waiting For Payment'), ('Processing', 'Processing'), ('Done', 'Done'), ] Ordinary = 'Ordinary' customer_choices = [ ('Ordinary', 'Ordinary'), ('Police', 'Police'), ('RAB', 'RAB'), ('DGIF', 'DGIF'), ('CID', 'CID'), ('NAVY', 'NAVY'), ('Air Force', 'Air Force'), ('Army', 'Army'), ('DB', 'DB'), ('Administration', 'Administration'), ] user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) taxPrice = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) shippingPrice = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) totalPrice = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False) paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) isDelivered = models.BooleanField(default=False) deliverAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=220, choices=status_choices, default=PENDING_PAYMENT) orderStatus= models.CharField(max_length=220, choices=orderstatus_choices, default=ON_HOLD, … -
UsZipCode --> Input -> (zipcode, radius) output -> (List of Zipcodes)
This is what I have tried from this search = SearchEngine() search.query(zipcode="74104", radius="30", returns=5) this returns [SimpleZipcode(zipcode='74104', zipcode_type='Standard', major_city='Tulsa', post_office_city='Tulsa, OK', common_city_list=['Tulsa'], county='Tulsa County', state='OK', lat=36.15, lng=-95.96, timezone='Central', radius_in_miles=1.0, area_code_list=['918'], population=12724, population_density=4673.0, land_area_in_sqmi=2.72, water_area_in_sqmi=0.0, housing_units=6606, occupied_housing_units=5794, median_home_value=136200, median_household_income=36848, bounds_west=-95.970417, bounds_east=-95.940281, bounds_north=36.160214, bounds_south=36.13323)] If I specify radius as an int search = SearchEngine() search.query(zipcode="74104", radius=30, returns=5) I get You can either specify all of lat, lng, radius or none of them Not sure what I am doing wrong -
OSError: cannot load library 'gobject-2.0-0'
I am currently implementing code that can print my database outputs to a pdf file. The following error (Title) is given when I do 'manage.py runserver' I have just installed weasyprint and imported HTML from it in the top of my views file , as per the below: Views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse import pyodbc from django.http import FileResponse from django.contrib import messages from django.views import View from django.template.loader import render_to_string from weasyprint import HTML import tempfile from django.db.models import Sum def home(request): return render(request , 'main/home.html') def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l}) def printToPdf(request): response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink … -
django - How to display a form in a modal window?
On the details page of a particular object (in my case, 'TrimType'), I want to display the create form when I press the 'Create' button, and the update form when I press the 'Update' button in one modal window. Does it need multiple url/view for the modal window that displays the Create or Update form? Or is it possible in single url/view? I implemented it in a single url/view, create works well, but it doesn't work as an update function. How do I implement views.py? models.py: class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) class TrimType(models.Model): car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True,) typeName = models.CharField(max_length=50, blank=False, null=False) forms.py: class TrimTypeForm(forms.ModelForm): class Meta: model = TrimType fields = ('car', 'typeName') typeName = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) detail_view.html: <div class="text-right mt-3 mb-3"> <a href="" id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="">add</a> <a href="" id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="">modify</a> </div> {% include 'modal_form.html' %} modal_form.html: <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h3 class="modal-title">TrimType</h3> <form method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.errors }}</p> <input type="hidden" name="car" value="{{ carID }}"> <div … -
Increment Integer Field only once per post
I am building a Blog App And I am implemented a feature of , When user edit a post then it will add +1 point in the User Profile's Integer Field. Everything is working fine But Integer Field is increasing every time I refresh the page. And I am trying to add only +1 point in it. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') full_name = models.CharField(max_length=30,default='') edited_count = models.IntegerField(default=0) class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') blog_post_edited_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post_edited_by') views.py def blog_post_detail_view(request,blogpost_id): post = get_object_or_404(BlogPost,id=blogpost_id) post_edited_by = post.blog_post_edited_by if post_edited_by == request.user: request.user.profile.edited_count += 1 request.user.profile.save() context = {'post':post} return render(request, 'blog_post_detail_view.html', context} What have i tried ? I have also tried using Boolean Field if user is awarded +1 point then it will turn to False, But it will create a problem, I mean I am awarding user in every edit But it will only award once every time. I have also tried by awarding +1 point in Edit Form like :- def edit_blogpost(request,blogpost_id): post = BlogPost.objects.get(id=blogpost_id) if request.method != 'POST': form = BlogPostEditForm(request.POST or None, request.FILES or None, instance=post) else: form = BlogPostEditForm( instance=post, data=request.POST, files=request.FILES) if … -
How to write Elasticsearch query in elasticsearch_dsl in python
I am newbie in Python Django and could not get started though I have seen basic documentations at https://www.elastic.co/guide/en/elasticsearch/reference/6.8/query-dsl.html Here is my Elasticsearch query api for aggregation curl -X POST "localhost:9200/my_index/_search?pretty" -H 'Content-Type: application/json' -d' { "aggs": { "imei_count": { "cardinality": { "field": "imei" } } } } ' Explanation of code block is welcome. Thanks -
Call a specific custom migration operation whenever a model is created
I am trying to implement this, http://docs.citusdata.com/en/v10.1/develop/migration_mt_django.html#:~:text=4.%20Distribute%20data,tenant_migrations.Distribute(%27Task%27)%2C%0A%20%20%5D Since I cannot hard code this operation for hundreds of models, I am wondering whether there is a way to automate this "make migration" whenever a model is created and me specifying the "reference" attribute in the model's meta class. Thank you -
Django unit test taking a long time to run
I tried different approaches like python manage.py test --keepdband creating a separate test database. I'm getting an error -: Using existing test database for alias 'default'... Got an error creating the test database: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE DATABASE IF NOT EXISTS `test_b2b ;\n SET sql_notes = @' at line 2") I'm using MySQL as a database. -
How to add a js without static folder un django
So I have a html template in Django and I want to include it with some js but I don't want my js to be in my static folder and I don't want to let any users in my site view that Javascript by going to any url so it it possible to that in django? -
Django - How to add access token to Client.post in Django test?
So I have some code below. Every endpoint has an authentication process, which is below as well. I want to be able to attach an access token, which is in cls.user to the Client.post so that I can test all the endpoints and ensure they are authenticating properly as well. How can I do this? So ideally I'd be attaching <bearer> <access token> to request.Meta['HTTP_AUTHORIZATION'] test.py import json from cheers.models import * from warrant import Cognito from django.urls import reverse from django.test import TestCase from rest_framework import status from cheers.models import GoalCategory, Post from dummy_factory.Factories import UserFactory, GoalFactory class PostTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.goal_category = 'health' GoalCategory.objects.create(category=cls.goal_category, emoji_url='url') cls.user = UserFactory() cls.goal = GoalFactory() user_obj = User.objects.get(pk=cls.user.phone_number) goal_obj = Goal.objects.get(pk=cls.goal.uuid) Post.objects.create(creator_id=user_obj, goal_id=goal_obj, body='Some text') cls.user = Cognito(<Some login credentials>) cls.user.authenticate(password=<password>) def test_create(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) Test authenticator function def cognito_authenticator(view_func): def wrapped_view(request, *args, **kwargs): # Check the cognito token from the request. token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] try: jwt.decode_cognito_jwt(token) except Exception: # Fail if invalid return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) # Or HttpResponseForbidden() else: # Proceed with the view … -
Django ModelChoiceField initial value is not showing up while editting
I have an form "ModelChoiceField" form field, and when adding the data it works fine ! But how to retrieve the saved data database to get selected when the form is edited ? form = AddForm(owner=pk, instance=data, initial={'course': data.course}) I even tried setting initial value, but still am not getting to selected value to get displayed ! class AddForm(ModelForm(: def __init__(self, owner, *args, **kwargs): super(AddForm, self).__init__(*args, **kwargs) self.fields['course'].queryset = Faculty.objects.filter(owner=owner) And note, that the selected values are correctly getting saved on database ! But its not showing up -
Continuous cycling through all objects in a table with django
As a learner of the django framework, I face the challenge of looping through all primary keys of a table, beginning with the first, and at the end of the sequence, to start all over again. The id field is an auto-incrementing serial field in postgres. A very basic breakdown of the project is as follows: models.py ... class Event(models.Model): id = models.BigAutoField(primary_key=True) event_name = models.BigIntegerField(blank=True, null=False) timestamp = models.DateTimeField(blank=True, null=True) viewed = models.BooleanField(default=False) views.py def home(request, id=None): from .models import Event first_obj = Event.objects.order_by('id').first() my_json = serialize('json', first_obj, fields=('event_name', 'timestamp')) return render(request, 'home.html', {'items': my_json}) def confirm(request): #set viewed=True on current object .save() return redirect('home') #move to next object home.html ... <form method="POST" action="{% url 'confirm' %}"> <button>confirm</button> </form> ... The idea is to send the my_json object to an html template. A user clicks a button, which should then mark the current object as viewed (sets viewed from False to True), then the next object should be fetched (by incremental primary key), and so on. If it has reached the last object, the first object (pk=1) should be fetched next, and the cycle continues. I would like to avoid making ajax requests and think a second url would …