Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mysterious null value added to the beginning of my array
I am creating an online voting system using Django. I am trying to pass the id of the candidate in the database from client side back to server side in the order they appear to the user. I am using Django's templating language to add the data to <meta> tags as below: {% for candidate in candidates %} <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}"> {% endfor %} I understand this is bad practice but I didn't know how else to do this. The problem arises when adding the values to the array. The part of the script that tackles this is here: var button = $("#send"); $(button).click(function() { var metatags = document.getElementsByTagName('meta'); var cands = []; for (var i = 0; i < metatags.length; i++) { cands.push(metatags[i].dataset.id); // console.log(cands); }; cands = JSON.stringify(cands); console.log(cands); When I do this the console is showing an array with all the candidate IDs, but a null value at the beginning. My best guess as to why is that a <meta> is created some other way in the rendering of the page (possibly by the bootstrap I have used?) which is being caught by document.getElementsByTagName('meta'). What is the best way to avoid the null value? Should I … -
Available for Remote Volunteer Work on a Python/Django Project
I'm a newbie in Python/Django language and I will love to hone my skills by volunteering alongside an engineering team whose project(s) uses Python or Django framework. I am available to work remotely. If you need an extra hand with your work, I'll be glad to work with you. My email is tundebarnabie@yahoo.com -
Django dumpdata generates invalid json format file
I'm working Django1.11. and I want to move from sqlite to PostgreSQL. So I need to dump data from Sqlite and load to PostgreSQL. I generate the dumped data with python3 manage.py dumpdata > db.json I have changed db setting to PostgreSQL and did python3 manage.py loaddata db.json and got this error. raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) So I use hexdump and tried. raise JSONDecodeError("Expecting value", s, err.value) from None django.core.serializers.base.DeserializationError: Problem installing fixture '/var/lib/myproject/fixtures/db.json': Expecting value: line 1 column 1 (char 0) I took the look at db.json and it is not valid json. -
Django 2.0 Admin "Add", filter by foreign key in another model
In a project I'm working on for a little office building, I have models that include Floors, Locations, down to Assets (workstations and printers and such): class Floor(models.Model): name = models.CharField(max_length=20) floornumber = models.IntegerField(default=1) class Location(models.Model): fkfloor = models.ForeignKey(Floor, on_delete=models.CASCADE) name = models.CharField(max_length=30) isroom = models.BooleanField(default=False) class Asset(models.Model): name = models.CharField(max_length=50) serialnumber = models.CharField(max_length=50) class Workstation(models.Model): name = models.CharField(max_length=30) owner = models.CharField(max_length=20) asset = models.OneToOneField(Asset, on_delete=models.CASCADE, primary_key=True) In the Admin interface, I need a way for adding Workstations in the OneToOne relationship with Assets, but with a filter for the location so that the entire list of Assets (including non-workstations) in every part of the building doesn't show up in the admin Add/Change form for Workstations. I've read through two books and searched SO and Django docs for every combination of terms I can think of for what I'm trying to accomplish, and I haven't found a working solution yet. I can use list_filter just fine to show the existing items, but that doesn't carry over into the admin add/change form. inlines aren't what I'm looking to use. What concept am I missing here? Many thanks in advance. -
How to schedule SMS using Twilio w/o using Celery?
I want to schedule SMS using Twilio in Python. After reading some articles I came to know about Celery. But I opted not to use celery and go with Python Threading module. Threading module works perfectly when using some dummy function, but when calling client.api.account.messages.create( to="+91xxxxxxxxx3", from_=settings.TWILIO_CALLER_ID, body=message) it sends the SMS at the same time. Here is my code from threading import Timer from django.conf import settings from twilio.rest import Client account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN message = to_do client = Client(account_sid, auth_token) run_at = user_given_time() #this function extracts the user given time from database. it works perfectly fine. # find current DateTime now = DT.now() now = DT.strptime(str(now), '%Y-%m-%d %H:%M:%S.%f') now = now.replace(microsecond=0) delay = (run_at - now).total_seconds() Timer(delay, client.api.account.messages.create( to="+91xxxxxxxxx3", from_=settings.TWILIO_CALLER_ID, body=to_do)).start() So the problem is that Twilio sends SMS at the same time, but I want it to send after given delay. -
Im trying to connect my django to postgress with heroku
this´s in my settings.py DATABASE_URL = os.environ['MYPOSTGRESKEY'] import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) im tryng to push to master but throws this: KeyError: 'MYPOSTGRESKEY' it´s weirds cause im using the database url what obtain from the command $ heroku config -
Matching query does not exist error
There are a bunch of people on this site have had a similar questions to mine, but I can't seem to find one that has solved it the way I want it to. I'm trying to get a password out of a database so that I can send an email automatically. To do this, I am calling Credential.objects.get(username='foo').password. This is where I get the error. What's really weird about this is I already had access to this database in a python console, and I've created a row in it. I have no clue why it's not showing up! Other people seem to recommend doing the following: try: Credential.objects.get(username='foo').password except Exception as e: return None All that this is doing is making sure the program doesn't return an error. This doesn't help me because this can't fail. An email must be sent and this call must get it. I'm almost certain I'm calling the right function for this, but I've been wrong before. Any help on this would be greatly appreciated. credential.py (not putting up max_length for security reasons): import d_models as models class Credential(models.Model): username = models.CharField() password = EncryptedCharField() -
Django - Form Signed up. Get Name from URL and save in hidden first_name
On my form signed up I want to override the behavior I want to get from url www.example.com/accounts/signup/?name=Michael and save the name as first_name. But I need that input first_name hidden What i've tried: class SignupForm(forms.Form): def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.save() <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> <input type="hidden" name="{{ form.first_name }}" value="test" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo;</button> </form> So The form would be something like: e-mail; password but also save first_name as Michael. Thanks for help! -
Server profile pic users on Django with DEBUG = False
I was deployng my project to Heroku and set up the DEBUG option to False. Until that, all was working ok. But, now, I can't server the user profile images. I want to server only with the Django, not with Apache or Nginx. I know that it's not the best option, but I don't need the best way to do this, so, if exists any way to server this with only the Django, will better to me. This is my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'saga', 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' This is my urls.py: from django.conf import settings urlpatterns = [ #URLs ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And I think that's goodn say that I'm using the WhiteNoise to server the Static Files on Heroku. -
Django Installation Issue
I am using Hostgator shared hosting. I have done the following: Installed virtual environment Installed flup. Created index.fcgi Created .htaccess It gives 404 not found. Missing WSGI when run from shell. -
Django + Redis + Celery Struggle to set the tasks
I have been trying to set up my scheduled task to run every x minutes, but I am not making any progress. I read the documentation and tried different approaches to the problem but I am obviously still doing something wrong. celery.py CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/1' from datetime import timedelta from celery import Celery app = Celery('taskscheduler', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND) app.autodiscover_tasks() CELERYBEAT_SCHEDULE = { 'schedule-name': { 'task': 'taskscheduler.task.just_print', 'schedule': timedelta(seconds=5), }, } task.py from celery import shared_task @shared_task def just_print(): print("Print from celery task") __init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from taskscheduler.celery import app as celery_app __all__ = ['celery_app'] All of the files are inside one of the many apps folders. What I am trying to achieve is basically to set up this task when I start the server and run it every x seconds, as long as the server is on. -
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/$']
Am trying to develop an app for student management. Every thing seems to be working fine. but am receiving an errors at some point. If i open the list view it shows all the student, if i click a student photo it will open a detail view of that student for me, then if i click add button inside the view it will show me (NoReverseMatch at /add_subj/3/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/$'] ). I want to be able to add subject to a particular id. Please need some help, am new in django. This is the link to my models.py, views.py and urls https://gist.github.com/AnyiLloyd/a963e9e3f52aa8f46fd7ef9a6ec0dddb -
Django Pagination + Regroup
So I'm working on a list view for one of my models and I want to display them by group like: Group 1 - Item - Item Group 2 - Item Group 3 - Item - Item - Item That's easy enough to do with regroup tag in Django, no problem there. But what if I want to paginate the queryset? Unless each group has the exact same number of items (they don't), I'll run into problems if I just do the standard: queryset = Model.objects.all() paginate_by = 10 So I'm wondering if there's anyway to paginate by group, or is Django's built in paginator totally incompatible with the regroup tag? From my searching I get the feeling that I'd have to implement a custom pagination system to achieve this, but I couldn't find anything conclusive so thought I'd check here in case I'm missing something and possibly get some clean alternatives. -
Django polls app not taking votes on selecting and clicking votes
Problem statement : I am new to Django and trying polls app. am currently in the place where we create vote function to accept votes and show results. but problem am facing is it's not capturing the vote. when I go to the results page it shows the names but no votes.Below are the code and snips. def results(request, question_id): i = get_object_or_404(Question, pk=question_id) return render(request, "span/results.html", {'i': i}) def vote(request, question_id): i = get_object_or_404(Question, pk=question_id) try: selected_choice = i.choice_set.get(pk=request.POST['choice']) except: return render(request, 'span/detail.html', {'i': i, 'error_message': "Please select a choice "}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('span:results', args=(i.id,))) above is my views.py and below shoing my detail: {% extends 'span/base.html' %} {%block main_content %} <h1> {{i.question_text}}</h1> {% if error_message %} <p><strong>{{error_message}}</strong></p>{% endif %} <form action = "{% url 'span:vote' i.id %}" method = "post"> {% csrf_token %} {% for j in i.choice_set.all %} <input type = "radio" name = "j" id="j{{forloop.counter}}" value = "{{j.id}}"/> <label for ="j{{forloop.counter}}">{{j.choice_text}}</label> <br> {% endfor %} <input type = "submit" value = "vote"> </form> {% endblock %} and my result {% extends 'span/base.html' %} {% block main_content %} <h1> {{i.question_text}}</h1> <ul> {% for j in i.choice_set.all %} <li> {{j.choice_text}} -- {{j.votes}} vote{{ j.votes|pluralize}} … -
Django: is it possible to calculate the sum of an annotated field within a group by segment?
Django: 2.0.2 DB: PostgreSQL: 10.1 I have a QuerySet of Event objects: I am annotating the filtered Sum of an IntegerField from a many-to-many on each Event based on a property of each object in the many-to-many, let’s call this event_cost) I am then grouping by the event month using ‘.values(‘event_month’)’ where event_month contains the event’s year and month I then want to annotate the Sum of event_cost within each month Generally the code looks like this: events_queryset = Event.objects.filter(...somefilters...) ids_list = [...listofids...] events_queryset\ .annotate(relevant_salaries=Sum(‘attendees__salary', filter=Q(attendees__id__in=ids_list)))\ .annotate(event_cost=F('relevant_salaries') * F('length'))\ .values(‘event_month’)\ .annotate(segment_total_cost=Sum(‘event_cost’)) The issue I am running into is having my event_cost annotation to be available after the .values() call: If I don’t add event_cost to values() it is not accessible to be used within Sum() after the values() call. However, if I do include it in values() the GROUP BY effect of the values() call is not correct (instead of getting values of 1/18, 2/18, 3/18, for example, the result would be more like (1/18, $12), (1/18, $26), ….. (2/18, $3), (2/18, $19)….. ($s added for clarity)) Is there a way to accomplish this query through the Django ORM or must this be done as a raw SQL query? Let … -
Having issues with Django URL mapping
Hi I am trying Django for an upcoming project and going through a tutorial and running into issue with defining URL paths. Below is the project structure showing the urls.py at the project root. The urls.py in my timer package is pretty simple: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] However when I launch the application and navigate to localhost:8080/timer/ I am getting a 404. Any suggestions what I should be looking at? Thanks Suresh -
how to: creating a view and serializer for adding, editing, and deleting objects with foreign relationships django rest framework
I am having a very hard time connecting all the documentation on django and django rest framework on how to create a view and serializer that allows for a foreign key. Example I have these models. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) I want to be able to choose a city and then view all the neighborhoods that city has, and be able to add a neighborhood, edit and neighborhood and delete a neighborhood. so perhaps the url to get all the neighborhoods a city has or create a new neighborhood for a city url(r'^neighborhood/(?P<citypk>[0-9]+)$', SearchNeighborhoodListCreate.as_view()), and one to edit and delete a neighborhood: url(r'^neighborhood/(?P<citypk>[0-9]+)/(?P<neighborhoodpk>[0-9]+)$',SearchNeighborhoodDetail.as_view()), I am currently using the ListCreateAPIView and the RetreiveUpdateDestoryAPIView from DRF Generics I understand that we have options like query_setrelated that allow us to get all the relations a model has. I know we have the x_set option. used like this in my example. Searchcity.SearchNeighborhood_set.all() I know we have related serializers and that the proper way I create them is such: class CityNeighborhoodSerializer(serializers.ModelSerializer): neighborhood = serializers.PrimaryKeyRelatedField(many=True, read_only=False) class Meta: model = SearchCity fields = ('City', 'neighborhood') But how do I use it in this use case? http://www.django-rest-framework.org/api-guide/relations/#serializer-relations … -
Django login after registration
Im' trying to auto login the user after registration but anything seems to work. Does not work: if registroForm.is_valid(): registroForm.save() user = authenticate(username=registroForm.cleaned_data['username'], password=registroForm.cleaned_data['password1']) request.session['_auth_user_id'] = user.pk request.session['_auth_user_backend'] = user.backend return JsonResponse({}) Does not work: if registroForm.is_valid(): registroForm.save() usuario = authenticate(username=registroForm.cleaned_data['username'], password=registroForm.cleaned_data['password1']) login(request, usuario) return JsonResponse({}) I'm using Django 2.0 -
gentelella for django doesn't recognize changes on custom.css
I am trying to apply gentelella bootstrap template for django, so I copied the app directory into my own django project. I am using some of-the-box html templates, so I copy them to the templates directory of the proper application, but I keep all static content on the app directory. The problem is when I modify the app/static/build/css/custom.css file, because I the html files don't reflect the change. In this case, I added the new class yellow to the custom.css file, and I added such class to some objects in the index2.html file, but the color of the text didn't change. This the django project directory tree: ├── Attractora │ ├── ActorsManagerApp │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── models.py │ │ ├── templates │ │ │ └── ActorsManagerApp │ │ │ ├── index2.html │ │ │ └── profile.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── Attractora │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── app │ │ ├── __init__.py │ │ ├── __init__.pycn-36.pyc │ │ ├── admin.py │ │ ├── … -
How to allow any user to upload an image with django-filebrowser-no-grapelli and tinymce?
I can't seem to find an answer for this anywhere so I think it will be useful for other people looking for it. I can only upload an image if I'm the admin user. Otherwise I get an unauthorised access warning from the Django admin, prompting me to login as admin. My guess is that I need to change the url pattern, which right now starts with "admin" as it can be seen below. re_path(r'^tinymce/', include('tinymce.urls')), re_path(r'^admin/filebrowser/', site.urls), -
Filter and sort results over multiple tables in Django
I have two models Page and Post where Page can have multiple Posts. Users will be sharing multiple Posts per day with the same URL. As result I need to get feed of the most shared URL per day and it’s posts in the current day. Is there a way to do this in Django ORM? class Page(models.Model): url = models.URLField() class Post(models.Model): page = models.ForeignKey(‘Page', on_delete=models.DO_NOTHING, null=True, blank=True, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I ended up with this which gives me the most shared URL but now I can’t figure it out how to get all the related posts and have them sorted by created_at. Post.objects.filter(created_at__date=date.today()).values('page__id').annotate(num_shares=Count('page__id')).order_by('-num_shares') <PostQuerySet [{'page__id': 2, 'num_shares': 6}, {'page__id': 1, 'num_shares': 5}]> -
Attempting to write full implementation of getting, adding, editing, deleting foreign key objects serialized sent over to front end
I am trying to do a return on objects that are related to another. example. I return a list of cities to my front end. If I click on a city I want to be able to view all the neighborhoods in that city. I want to be able to add, delete, and edit neighborhoods that pertain to that city. Here is my models. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) here are my views and urls that pertain to getting a city or a list of cities url(r'city/(?P<pk>[0-9]+)/$',SearchCityDetail.as_view()), url(r'city$', SearchCityListCreate.as_view()), # create city list url class SearchCityListCreate(ListCreateAPIView): queryset = SearchCity.objects.all() serializer_class =SearchCitySerializer class SearchCityDetail(RetrieveUpdateDestroyAPIView): queryset = SearchCity.objects.all() serializer_class = SearchCitySerializer my neighborhood urls and views so far: ( I am not sure if this is right) url(r'^neighborhood/(?P<citypk>[0-9]+)$', SearchNeighborhoodListCreate.as_view()), url(r'^neighborhood/(?P<citypk>[0-9]+)/(?P<neighborhoodpk>[0-9]+)$',SearchNeighborhoodDetail.as_view()), class SearchNeighborhoodListCreate(ListCreateAPIView): queryset = SearchCity.SearchNeighborhood_set.all() serializer_class = SearchNeighborhoodSerializer class SearchNeighborhoodDetail(RetrieveUpdateDestroyAPIView): queryset = SearchNeighborhood.objects.all() serializer_class = SearchNeighborhoodSerializer now according to the documentation I need to use a serializer that takes a backward relation http://www.django-rest-framework.org/api-guide/relations/#the-queryset-argument but I am not sure how. What I am getting at is that I am closing in on a solution from both ends but not sure exactly what I am … -
ParentalKey is not rendered within the StructBlock
I'm trying to create a custom StructBlock which I wanna use inside the StreamField. Here in the StructBlock I have 4 fields, namely: background_style title image category That's my code: from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailcore import blocks from wagtail.wagtailimages.blocks import ImageChooserBlock from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel from modelcluster.fields import ParentalKey from .vars import BackgroundChoices class BaseBlock(blocks.StructBlock): background_style = blocks.ChoiceBlock(choices=BackgroundChoices, icon='color', required=False) @register_snippet class LeadCaptureCategory(models.Model): name = models.CharField(max_length=255) about = models.CharField(max_length=255, blank=True) icon = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('name'), FieldPanel('about'), ImageChooserPanel('icon'), ] def __str__(self): return self.name class Meta: verbose_name_plural = 'Lead Capture Categories' class LeadCaptureForm(BaseBlock): title = blocks.CharBlock(required=False) image = ImageChooserBlock(required=False) category = blocks.BlockField(ParentalKey('LeadCaptureCategory')) class Meta: icon = 'plus-inverse' label = 'lead capture form'.title() admin_text = label template = 'home/blocks/lead_capture_form.html' class HomePage(Page): template = 'home/home_page.html' menu = models.CharField(max_length=128, blank=True) body = StreamField([ ('lead_capture_form', LeadCaptureForm()), ], blank=True) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] 3 of these fields in the admin are rendered correctly, except category. You can see that the category is based on the modelcluster.fields.ParentalKey. Maybe that's the problem? Any idea how to solve this? In [27]: … -
get_absolute_url is not working
I am practicing with below github source code, but stuck in getting working get_absolute_url method.Not able to access svariable.html. It always redirecting to base.html.Any help would be much appreciated. https://github.com/GeoffMahugu/Django-Ecommerce Model.py class Product(models.Model): title = models.CharField(max_length=120) categories = models.ManyToManyField('Category', blank=True) default_category = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE) description = models.TextField(null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=20) default_image = models.ImageField(upload_to=image_upload_to_prod, blank=True, null=True) active = models.BooleanField(default=True) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) slug = models.SlugField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Products:SingleProduct', kwargs={'pk': self.pk}) view.py def SingleProduct(request, pk): objects = get_object_or_404(Product, pk=pk) vari = Variation.objects.filter(product=objects) obj_cat = objects.default_category obj_prod = Product.objects.filter(default_category=obj_cat).exclude(pk=objects.pk).order_by('-pk')[:3] title = '%s' % (objects.title) cart_id = request.session.get('cart_id') object = get_object_or_404(Cart, pk=cart_id) cart_count = object.cartitem_set.count() cart_items = object.cartitem_set.all() context = { 'vari': vari, 'title': title, 'objects': objects, 'obj_prod': obj_prod, 'cart_count': cart_count, 'cart_items': cart_items } template = 'svariable.html' return render(request, template, context) -
How can I input current user_id into django database table?
I'm trying to create editable table in user interface and everything works till I try to insert new model argument like: usr=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) after that getting this kind of error: django.db.utils.IntegrityError: NOT NULL constraint failed: irenginiai_irenginys.usr_id I'm trying to implement this because when I save my data every user can see it. But goal is to separate users information. Maybe there is an easier way to do it. Using django 1.11.10 version Models.py class Device(models.Model): usr = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip = models.CharField(max_length=50) port_number = models.CharField(max_length=50) Views.py def save_device_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True devices = Device.objects.all() data['html_device_list'] = render_to_string('devices/additional/partial_devices_list.html', { 'devices': devices }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def device_sukurti(request): if request.method == 'POST': form = DeviceForm(request.POST) else: form = DeviceForm() return save_device_form(request, form, 'devices/additional/partial_device_sukurti.html') def device_update(request, pk): device = get_object_or_404(Device, pk=pk) if request.method == 'POST': form = DeviceForm(request.POST, instance=device) else: form = DeviceForm(instance=device) return save_device_form(request, form, 'devices/additional/partial_device_update.html') def device_delete(request, pk): device = get_object_or_404(Device, pk=pk) data = dict() if request.method == 'POST': device.delete() data['form_is_valid'] = True devices = Device.objects.all() data['html_device_list'] = render_to_string('devices/additional/partial_devices_list.html', { 'devices': devices }) else: context = {'device': …