Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models.foreignKey not being picked up and causing a Not Null Constraint error
Fairly new to Python and Django and having an issue with a foreignKey in that it's not being picked up. I am loading the data from some JSON I've get from an API call. There are two models I'm looking at, Team and Player. models (snipped for brevity): class Team(models.Model): code = models.IntegerField(null=True) name = models.CharField(max_length=30, null=True) short_name = models.CharField(max_length=3, null=True) id = models.IntegerField(primary_key=True) class Player(models.Model): total_points = models.IntegerField(null=True) squad_number = models.IntegerField(null=True) id = models.IntegerField(primary_key=True) goals_scored = models.IntegerField(null=True) minutes = models.IntegerField(null=True) team = models.IntegerField(null=True) team_code = models.IntegerField(null=True) player_team = models.ForeignKey(Team, on_delete=CASCADE) Both models have a unique id, id and code. Strange, but that's the way the data comes! Team.code maps to Player.team_code and Team.id maps to Player.team. In reality I could use either. I created player_team in Player with a ForeignKey link back to Team. I load and save Team first, then Player. teams = [Team(**data_dict) for data_dict in data['teams']] Team.objects.all().delete() Team.objects.bulk_create(teams) players = [Player(**data_dict) for data_dict in data['elements']] Player.objects.all().delete() Player.objects.bulk_create(players) The error I get is django.db.utils.IntegrityError: NOT NULL constraint failed: players_player.player_team_id I don't really understand how exactly it is linking the two models. I can see that in Player it is saying models.ForeignKey(Team...) so that makes sense. But how … -
Where can I find django(ORM) practice problems?
I'm really finding it very difficult to source practice problems for Django and its ORMs. I've heard Mosh's paid course has such exercises. I'm just getting started with Django mostly referring to youtube and its official documentation. I hope one of you who reads this could help me out. I don't know if this is the right forum to ask. Thanks in advance! -
Add CSRF to locust post request to prevent django error - Forbidden (CSRF cookie not set.)
How to add CSRF to the URL to test django from locust to prevent the error Forbidden (CSRF cookie not set.)? Here is what I have tried: @task def some_task(self): response = self.client.get("/") csrftoken = response.cookies['csrftoken'] self.client.post( "api/", {'csrfmiddlewaretoken': csrftoken}, headers={ 'X-CSRFToken': csrftoken, }) -
Is there any way to make this filter query smaller
These are my tables: class Employee(models.Model): name = models.CharField() class Job(models.Model): title = models.CharField() class Employee_Job(models.Model): employee_f = models.ForeignKey(Employee, on_delete=models.CASCADE) job_f = models.ForeignKey(Job, on_delete=models.CASCADE) class Salary(models.Model): employee_job_f = models.ForeignKey(Employee_Job, on_delete=models.CASCADE) @property def name(self): return Employee.objects.filter(id = ( Employee_Job.objects.filter(id = self.employee_job_f_id ).first().employee_f )).first().name This query seems very long to me, I thought select_related() should help with this, but it follows foreign keys and return ALL results not the result that is related to THIS instance of Salary. -
How can I add Django table list on edit page change_form.html?
Friends, how can I add into admin edit page Django admin like table? So, I got MaterialAdmin. I've added change_view() function in it and all the necessary data put into extra_content like this: class MaterialAdmin(admin.ModelAdmin): change_form_template = 'admin/change_material_form.html' search_fields = ['name'] autocomplete_fields = ("manufacturer", ) list_display = ("_show_name_with_manufacturer", "_show_material_groups_quantity", "_show_boxing", "unit",) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related("manufacturer").prefetch_related("material_group", "material_item", "unit") def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} material = Material.objects.filter(id=object_id).select_related("manufacturer").prefetch_related("material_group", "material_item", "unit").first() material_items = material.material_item.all() material_groups = material.material_group.all() works = MaterialGroupWork.objects.filter(material_group__in=material_groups).distinct() extra_context['material_items'] = material_items extra_context['material_groups'] = material_groups extra_context['works'] = works return super(MaterialAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) admin.site.register(Material, MaterialAdmin) Now I have access to the data in my custom change_material_form.html .... <div> {% for material_item in material_items %} {{ material_item }} {% endfor %} </div> <div> {% for material_group in material_groups %} {{ material_group }} {% endfor %} </div> <div> {% for work in works %} {{ work.work }} {% endfor %} </div> What I really want is to replace those divs with Django Admin tables. How can I implement this? I looked in the template file "change_list_results.html" and it has some result_headers и results data. But I don't know how to get "results" … -
Django Template Not Receiving Context Object
I'm trying to implement a simple sign up form and slightly tearing my hair out. For some reason, the view doesn't seem to be properly passing the context object I pass it (regardless of what it is.) here's my code: urls.py path(r"signup/", client_views.signup_view, name="page-signup") views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('page-index') else: form = SignUpForm() context = {'form': form} return render(request, 'registration/signup.html', context=context) registration/signup.html {% extends "base.html" %} {% load static %} {% block header %} Sign Up {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock %} forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) I've confirmed it's generating the form properly as html it's also definitely rendering the correct template doesn't pass any context even if it's just a string or something doesn't work with any forms doesn't work in other templates, implying to me it's in the view … -
See variable values in developer tools for Django templates
I have a template in Django which uses some variables. For example, I use {% with swatch_matrix=item_group.get_swatch_matrix %} Without rendering this on-screen is there a way to use the developer tools, or something else, to check what value is being generated here? -
Python Django - dynamically add and create objects in ModelMultipleChoiceField
I have a problem with something that I thought was quite common, but I cannot find the answer to it anywhere. I have 2 models Item and Group, where an item can be a member of many (or none) groups. I am writing a view for creating an Item. My code looks like this: # models.py class Group(models.Model): ... class Item(models.Model): item = models.CharField(...) groups = models.ManyToManyField(Group) # forms.py class NewItemForm(forms.Form): item = forms.CharField() groups = forms.ModelMultipleChoiceField( queryset = models.Group.objects.all(), widget = forms.CheckboxSelectMultiple, required = False ) In my template I add javascript that allows user to dynamically crate a new checkbox (and setting it's value to something like __new__group_name) for a new group. What I want to accomplish it to allow user to create a new group and add an item to it, while this item is currently being created. Unfortunately this cannot work, because checkboxes generated by Django are sending a primary key of Group and there obviously is not a group with primary key __new__group_name so validation of this form failes. While it is correct and I am glad it does, I cannot find a easy solution for this problem. The only thing I can think about … -
django: repeat testcase with different fixtures
I have a Django TestCase, all of whose tests I'd like to run for two different sets of data (in this case, the Bike object whose colour can be red or blue). Whether that's through loading different fixtures, or the same fixtures and manipulating the colour, I have no preference. See below example: class TestBike(TestCase): fixtures = [ "testfiles/data/blue_bike.json", ] def setUp(self, *args, **kwargs): self.bike = Bike.objects.get(color="blue") run_expensive_commands(self.bike) def test_bike_1(self): # one of many tests def test_bike_2(self): # second of many tests One way I considered was using the parameterized package, but then I'd have to parameterize each test, and call a prepare() function from each test. Sounds like a whole lot of redundancy. Another is to multiple-inherit the test with different fixtures. Also a bit too verbose for my liking. -
how i can connect between 2 django services using mqtt?
"how i can connect two Django services using MQTT (i want to create a customer in the first service and then dispatched it to the another service)` -
Speeding up Django Rest Framework Model Serializer N+1 Query problem
I have a DRF ModelSerializer class that serializes anOrder model. This serializer has a field: num_modelA = serializers.SerializerMethodField() ` def get_num_modelA(self, o): r = ModelA.objects.filter(modelB__modelC__order=o).count() return r Where ModelA has a ForeignKey field modelB, ModelB has a ForeignKey field modelC, and ModelC has a ForeignKey field order. The problem with this is obviously that for each order that gets serialized it makes an additional query to the DB which slows performance down. I've implemented a static method setup_eager_loading as described here that fixed the N+1 query problem for other fields I was having. @staticmethod def setup_eager_loading(queryset): # select_related for "to-one" relationships queryset = queryset.select_related('modelD','modelE') return queryset My idea was I could use prefetch_related as well to reduce the number of queries. But I am unsure how to do this since Order and ModelA are separated by multiple foreign keys. Let me know if any other information would be useful -
Wagtail Create Snippet from the frontend to accepts Images (Django)
I have a simple snippet using Django Wagtail. I would like to be able to update the logo from a "CreateView" but when it renders in my view it's expecting a foreign key. I would imagine it would be easy to create a from to do this but it's not. @register_snippet class MerchantSnippet(models.Model): name = models.CharField(max_length=255, blank=False, null=False, unique=True) logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, ) def __str__(self): return '{} {}'.format(self.user.first_name, self.user.last_name) panels =[ FieldPanel('name'), ImageChooserPanel('logo'), ] edit_handler = TabbedInterface([ ObjectList(panels, heading='Content'), ]) class ProductCreateView(CreateView): model = ProductSnippet fields = ['name','logo'] class ProductUpdateView(UpdateView): model = ProductSnippet fields = ['name','logo'] When I use the default example in the template I ended up just getting a drop down. {% render_field field class+="form-control" %} How would I be able to see an image preview in the event I am updating the snippet and the ability to upload a different one . In the event I am creating a new item the ability to select an upload an image. -
Iterating over model object in template is returning no results - Django
This is my model: pass class Listing(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=500) url = models.URLField() live = models.BooleanField(default=True) author = models.ForeignKey('User', on_delete=models.CASCADE, name='author') category = models.ForeignKey('Category', on_delete=models.CASCADE, name='category', default="") def __str__(self): return f'{self.id}: {self.title}' class Bid(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) bid_count = models.IntegerField() highest_bidder = models.ForeignKey('User', on_delete=models.PROTECT, name="highest_bidder", default=None, blank=True, null=True) listing = models.ForeignKey('Listing', on_delete=models.CASCADE, name='listing', default="") def __str__(self): return f'{self.listing.title} ({self.price})' class Category(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Watchlist(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, name='user') item = models.ManyToManyField('Listing', blank=True, null=True) def __str__(self): return f"{self.user}'s Watchlist" This is my view: currentUser = request.user watchlist = Watchlist.objects.filter(user=request.user).values() bids = Bid.objects.all() return render(request, 'auctions/userWatchlist.html', { 'currentUser': currentUser, 'watchlist': watchlist, 'bids': bids }) I've also tried not passing in .values() and using .all in the template instead. Here's the template: {% block body %} <h2>Watchlist</h2> <div class="container"> <div class="row"> {% for listing in watchlist %} <div>{{ listing }}</div> <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ listing.item.url }}" class="card-img-top" alt="{{ listing.item.title }}"> <div class="card-body"> <h5 class="card-title">{{ listing.item.title }}</h5> <p class="card-text">{{ listing.item.description }}</p> {% for bid in bids.all %} {% if bid.listing == listing.item %} <p class="card-text">Bid price: {{ bid.price }}</p> {% endif %} {% endfor %} <a href="{% url 'item_details' … -
Django Many to Many relationship Query Filter
class servers(models.Model): hostname=models.CharField(max_length=100) ip= models.CharField(max_length=100) os= models.CharField(max_length=100) class application(models.Model) name=models.CharField(max_length=100) URL= models.CharField(max_length=100) servers= models.ManyToManyField(servers, blank = True, null=True) current DB status 3 servers 2 with os as linux and 1 with os as windows 2 applications Requirement : application can have many servers and each server can be part of many applications also Need support to create filter only those applications whose os is windows. I tried below but it is returning all three servers. def viewapp(request,pk) criterion1 = Q(id=pk) criterion2 = Q(servers__os__startswith="windows") prodlist = application.objects.filter(criterion1 & criterion2) -
how I'm gonna create the URL pattern for each topic?
I want to create a URL patterns for each topic. How I'm gonna do that?? This is my code: models.py from django.db import models from django.db import models class Task(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title urls.py from django.urls import path from . import views app_name = 'my_app' urlpatterns = [ path('', views.index, name='index'), path('add_task/', views.add_task, name='add_task'), ] forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'add new task...'})) class Meta: model = Task fields = '__all__' views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Task from .forms import TaskForm def index(request): task = Task.objects.all() context = {'task': task} return render(request, 'my_app/index.html', context) def add_task(request): if request.method == 'GET': form = TaskForm() else: form = TaskForm(data=request.POST) if form.is_valid(): form.save() return redirect('my_app:index') context = {'form': form} return render(request, 'my_app/add_task.html', context) base.html To do {% block content %}{% endblock %} index.html {% extends 'my_app/base.html' %} {% block content %} <p><a href="{% url 'my_app:add_task' %}">Add task</a></p> <ul> {% for tasks in task %} <li> {{ tasks }} </li> {% empty %} <li> <p>There's no task</p> </li> {% endfor %} </ul> {% endblock %} add_task.html {% … -
how to save the uploaded images in Django backend
Here I have written a code for multi uploading images. This I have done in vue.js and backend is Django. So here while user uploads an multiple images so it is uploading the image and it is showing in console. But the issue i am not able to access this in backend. And below I have past django function if anyone have an idea how to save this images in backend from last one week struggling alot to save the images in backend nut not succeeded yet please help me if anyone have an idea about this <body> <div id="el"> <div id="my-strictly-unique-vue-upload-multiple-image"> <vue-upload-multiple-image @upload-success="uploadImageSuccess" @before-remove="beforeRemove" @edit-image="editImage" @data-change="dataChange" :data-images="images" ></vue-upload-multiple-image> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <script src="https://unpkg.com/vue-upload-multiple-image@1.0.2/dist/vue-upload-multiple-image.js"></script> <script type="text/javascript"> var vm = new Vue({ el: '#el', data() { return { images: [] } }, components: { VueUploadMultipleImage, }, methods: { uploadImageSuccess(formData, index, fileList) { console.log('data k', fileList); console.log('data1', formData); console.log('data2', index); }, beforeRemove(index, done, fileList) { console.log('index', index, fileList) var r = confirm("remove image") if (r == true) { done() } else { } }, editImage(formData, index, fileList) { console.log('edit data', formData, index, fileList) }, dataChange(data) { console.log(data); } } }); </script> </body> views.py def fileupload(request): return render(request, 'fileupload.html') -
Using User Model in POST Django Rest Framework
I have a small web app. I want to essentially recreate this form from django admin, in a POST request in Django REST Framework: I've been able to add the File Name and File Path fields, but I am have trouble replicating the user field so I can type in a user id or user name and send it with the request. I keep getting this is error when I access the endpoint: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field I have included my serializer and view for the endpoint below: serializer.py class FileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = File fields = '__all__' views.py class UserFileList(generics.ListCreateAPIView): queryset = File.objects.all().order_by('user_id') permisson_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = FileSerializer -
How to make calculation of fields from different Models?
There are now three tables: class Product(models.Model): sku = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200, null=True) class HistoricalData(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateTimeField() demand_sold = models.IntegerField(default=0) class ForecastData(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date = models.DateTimeField() demand_sold = models.IntegerField(default=0) I need to compare Historical and Forecast data for the list of products and calculate the accuracy rate. Formula like: ForecastData.demand_sold * 100/HistoricalData.demand_sold The current solution is to iterate through the history and forecast datasets and make calculations for demand_sold products = Product.objects.filter(...) queryset_hist = HistoricalData.objects.filter(product__in=products) queryset_forecast = ForecastData.objects.filter(product__in=products) I am wondering is there any elegant solution to calculate field from different Django Models. -
How to implement elastic search using graphene-elastic in Django?
Hope you all are having an amazing day ! I’m trying to implement elastic search in my Django application using graphene-elastic package https://graphene-elastic.readthedocs.io/en/latest/ and documentation for this is quite unclear what I want to achieve, Any leads to working examples or blogs would be very much appreciated! Thanks :) -
How to encrypt postgresql database with Django as the backend?
I am using Postgresql database with Django rest framework, I want to encrypt my database to improve security but I didn't find any documentations which clearly explains the encryption process and algorithms underlying it. Any help is appreciated -
How can I do additions of multiple values in Django template?
1 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total1.realization__amount_received__sum == None %} 0 {% else %} {{total1.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> 2 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total2.realization__amount_received__sum == None %} 0 {% else %} {{total2.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> 3 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total3.realization__amount_received__sum == None %} 0 {% else %} {{total3.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> 4 <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"><b>RT CASH AMOUNT</b></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>KCC</b></div> <div class="col-2 text-center fs2 border-start border-bottom border-dark" id="cash_amt"> <b> {% if total4.realization__amount_received__sum == None %} 0 {% else %} {{total4.realization__amount_received__sum|floatformat}} {% endif %} </b> </div> </div> And where I want the result: <div class="row"> <div class="col-7 text-start fs2 border-bottom border-dark"></div> <div class="col-3 text-center fs2 border-start border-bottom border-dark"><b>TOTAL (A)</b></div> <div class="col-2 … -
Returning only one value from the database in Django
I'm trying to retrieve the data from the SQL stored procedure where I'm able to get the data but its giving the single output but I want to reflect all the records from the database. How could I loop through each one of the element in the database views.py: @api_view(['GET', 'POST']) def ClaimReferenceView(request,userid): try: userid = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': userID = request.data.get(userid) print(userID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= %s',('10',)) result_set = cursor.fetchall() print(type(result_set)) print(result_set) for row in result_set: Number= row[0] Opened = row[1] Contacttype = row[2] Category1 = row[3] State = row[4] Assignmentgroup = row[5] Country_Location = row[6] Openedfor = row[7] Employeenumber = row[8] Shortdescription = row[9] AllocatedDate = row[10] return Response(result_set) return Response({"Number":Number,"Opened":Opened, "Contacttype": Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "Country_Location": Country_Location, "Openedfor":Openedfor, "Employeenumber":Employeenumber, "Shortdescription": Shortdescription, "AllocatedDate":AllocatedDate}, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = ClaimReferenceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) output which I get only record but I want all the records to be printed AllocatedDate: "2021-11-10" Assignmentgroup: "BusS" Category1: "Referrals " Contacttype: "Web" Country_Location: "India" Employeenumber: 11546124 Number: "HRR6712929" Opened: "2021-11-05T20:22:58" Openedfor: "ritika" Shortdescription: "Unable to submit " State: "Draft" Data which I get from the database [(('HR749', datetime.datetime(2021, … -
Tests for view names failing since upgrading to Django 4.0
In a Django project I have tests that check that a URL uses a specific class-based view. e.g. I have this view: from django.views.generic import TemplateView class HomeView(TemplateView): template_name = "home.html" And this test: from django.test import TestCase from django.urls import resolve from myapp import views class UrlsTestCase(TestCase): def test_home_view(self): self.assertEqual(resolve("/").func.__name__, views.HomeView.__name__) This test passes in Django 3.x but once I try it with Django 4.0 the test fails with: self.assertEqual(resolve("/").func.__name__, views.HomeView.__name__) AssertionError: 'view' != 'HomeView' - view + HomeView Obviously something has changed in Django 4.0 but I can't see anything related in the release notes. So, what's changed and how can I make this test work again (or how can I test this in a better way)? -
Difference between post method and form_valid in generic base view
Can you explain me what is difference between two methods based on generic base view in Django: post and form_valid? I have both in my views, and both save my forms. I used it both, because my practical task required it, but understanding the difference between them I have no. Here's a part of my views.py. I hope you can shed some light on this question. class SellerUpdateView(LoginRequiredMixin, UpdateView): model = Seller template_name = "main/seller_update.html" fields = "__all__" success_url = reverse_lazy("seller-info") login_url = "/accounts/login/" def get_object(self, queryset=None): seller, created = Seller.objects.get_or_create(user=self.request.user) return seller def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["user_form"] = UserForm(instance=self.object.user) context["smslog_form"] = SMSLogForm(instance=self.object) return context def form_valid(self, form): self.object = form.save() user_form = UserForm(self.request.POST, instance=self.request.user) if user_form.is_valid(): user_form.save() return super().form_valid(form) class AdUpdateView(LoginRequiredMixin, UpdateView): model = Ad template_name = "main/update_ad.html" fields = ("name", "description", "category", "tag", "price") login_url = "/accounts/login/" def get_context_data(self): context = super().get_context_data() context["picture_form"] = ImageFormset(instance=self.object) context["seller"] = self.object.seller return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() formset = ImageFormset(request.POST, request.FILES, instance=self.object) if form.is_valid(): form.save() if formset.is_valid(): formset.save() return HttpResponseRedirect(self.get_success_url()) else: return form.invalid() def get_success_url(self): return reverse_lazy("ad-detail", args=(self.object.id,)) -
datetime as a parameter of stored procedure
I have this code snippet with a stored procedure Read_records_from_to cleaned_data = from_to_form.cleaned_data with connections["mssql_database"].cursor() as cursor: cursor.execute("Read_records_from_to '2021-12-01 07:55:39.000', '2021-12-14 07:55:39.000'") result = cursor.fetchall() class FromToForm(Form): start_date = DateField(widget=AdminDateWidget()) start_time = TimeField(widget=AdminTimeWidget()) end_date = DateField(widget=AdminDateWidget()) end_time = TimeField(widget=AdminTimeWidget()) The stored procedure takes to parameters from_datetime and to_datetime. I'd like to assign it values taken from FromtoForm. How can I do this?