Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - common nested serializer for multiple models with the same base class
Assuming that we have the following models: from django.db import models class BaseModel(models.Model): field_a = models.TextField() field_b = models.IntegerField() class Meta: abstract = True class ModelA(BaseModel): some_relation = models.ForeignKey( "app.RelatedModelA", related_name="model_a_set", ... ) class ModelB(BaseModel): different_relation = models.ForeignKey( "app.RelatedModelB", related_name="model_b_set", ... ) class RelatedModelA(models.Model): pass class RelatedModelB(models.Model): pass I would like to be able to define serializers in the following way: from rest_framework import serializers class RelatedModelASerializer(serializers.ModelSerializer): model_a_set = BaseModelSerializer(many=True) class Meta: model = RelatedModelA fields = ("id", "model_a_set") class RelatedModelBSerializer(serializers.ModelSerializer): model_b_set = BaseModelSerializer(many=True) class Meta: model = RelatedModelB fields = ("id", "model_b_set") The question is - how to define BaseModelSerializer? I found a solution that takes into account overriding to_representation, although it requires writing serializers for each type separately (ModelASerializer and ModelBSerializer), so it would look like this: class BaseModelSerializer(serializers.ModelSerializer): def to_representation(self, obj): if isinstance(obj, ModelA): return ModelASerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, ModelB): return ModelBSerializer(obj, context=self.context).to_representation(obj) raise NotImplementedError class Meta: model = BaseModel fields = ("id", "field_a", "field_b") The ideal solution for me would be something like that, without defining serializers for ModelA and ModelB: class BaseModelSerializer(serializers.ModelSerializer): class Meta: model = BaseModel fields = ("id", "field_a", "field_b") but unfortunately it won't work that way, because an abstract model cannot be … -
How to create a django model record using get_or_create and select_related
I have a class like below: class GroupProduct(models.Model): product = models.ForeignKey( 'myapp.Products' related_name='myapp_group_product') @classmethod def create_group_product(cls, p_id, product_id): cls.objects.get_or_create(id=p_id, defaults=dict(product=product_id).select_related('product') So I expect it creates a record in the table with the following params, however it doesn't. GP = GroupProduct() GP.create_group_product(3, 225) It says it product must be a myapp.Products instance. Is there any way to use select_related in this way rather than doing a seprate query and hit the database? -
Mapboxgl breaks when I change django language in settings
Basically my code works well when language in django settings.py is set to "en-us" But when I try to change it I get: Uncaught Error: Invalid LngLat object: (NaN, NaN) at new Ha (lng_lat.js:39:19) at Function.convert (lng_lat.js:142:20) at Rr.setLngLat (marker.js:337:31) at dodaj_marker ((indeks):282:37) at (indeks):296:9 I'm changing lang because I need to get months in different language, but how does it affect mapbox? Is there any mapbox language variable I have to edit in order to get it working ? -
win10 netstat -ano|findstr 8000 return empty and error ’WinError 10013” when python manage.py runserver 8000
receive Error: [WinError 10013] when i use 'python manage.py runserver 8000'. then netstat -ano|findstr 8000, but nothing is return,only empty list. I use win10, what missing? thanks. But run python manage.py runserver 9000 is ok? what problem with port 8000? why netstat -ano|findstr 8000 return empty? -
django.db.utils.OperationalError: no such table: main.authentication_user
I am getting the error mentioned in the title during my try to save some information to a postgres database. My models.py script is the following: from django.db import models from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) CustomeUser is from the models.py of a custom authentication application: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): demo = models.CharField(max_length=40) My serializers.py script is the following: from rest_framework import serializers from vpp_optimization.models import Event class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') And my views.py where I am trying to add a specific event to the database is the following: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) @permission_classes([IsAuthenticated,]) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id_event=request.user) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) The full error is the following: Traceback (most recent call last): File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.authentication_user … -
Django - Vue - how to generate view for tag, or?
Im use vue and django with rest framework. In django models.py i have model field "tahs" this is charfield with tags separated by comma. exaple : django,forest,native I want to generate view for each tag example "django". OR try to search in filed tahs and return objects contains this tag[ex.django] this is my views.py class TagsResultsViewSet(viewsets.ModelViewSet): serializer_class = TagResultsViewSetSerializer queryset = CustomUserPass.objects.all() lookup_field = 'tahs' def get_queryset(self, *args, **kwargs): context = super().get_queryset(*args, **kwargs) tag = self.kwargs['tahs'] print('this is tags:', tag) context = self.queryset.filter(tahs__icontains=tag) print(context) return context serializer.py class TagResultsViewSetSerializer(serializers.ModelSerializer): tahs = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = CustomUserPass fields = '__all__' urls.py router = DefaultRouter() ... router.register('tags', TagsPassViewSet, basename='tags') router.register('tag', TagsResultsViewSet, basename='tag') urlpatterns = [ path('', include(router.urls)), ] vue file: TagView.vue <template> <div class="about"> <h1>You looking: {{tag}}</h1> <div v-for="result in results" :key="result.id"> <div>{{result.username}}</div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'TagView', data() { return { results: [], errors: [], } }, props: { tag: { type: String, required: true, }, }, mounted() { this.getTagsResults() }, methods: { async getTagsResults() { this.$store.commit('setIsLoading', true) axios .get(`/api/v1/tag/${this.tag}`) .then(response => { this.results = response.data console.log(this.results) }) .catch(error => { console.log(error) }) this.$store.commit('setIsLoading', false) }, } } </script> actually when … -
How to fill in programmatically Django admin built-in autocomplete?
I would like to use JS in the Django admin to fill in programmatically a field that uses the built-in autocomplete option (NOT autocomplete-light). Let's say the field is called myfavfield. I can retrieve it with JS as follows $("#id_myfavfield"). If it is already filled in with some values, I can retrieve them with $("#id_myfavfield").val();, which, for example, returns ['1', '4'], I can also clear myfavfield with $("#id_myfavfield").empty();. However, I can't fill it in, for example, by running $("#id_myfavfield").val(['2', '4', '5']); or any other way that I have tried. Does anybody know how one can achieve that? -
Django - display image from database in edit form
I recorded a form that also contained an image. I would like that later in edit form to be able to visually see the previously uploaded image before changing it. I tried to display it in edit form via <img src = "{{curs.poster_curs.url}}" alt = "alternate text"> but in inspect it shows src = "unknown". How can I display the image already uploaded in edit form? I ask for a solution in this regard. Thank you -
Post a dcitionaries and lists along with a file using python resquests
I built an endpoint using Django-rest-framework which expects a file and some other information, including some dictionaries and lists. If I make the request using the browsable API from drf, none of the data is truncated and I also receive the file. However if I make a POST request through Python-requests library it doesn't work and the data received on the server side is received truncated as HTTP form-encoding is not capable of representing nested data structures. Does anyone know how can I reproduce the same behavior as the browsable API in the request through python requests library and avoid the truncation? Any help is greatly appreciated. -
django-tenants: redirecting to tenant url after login raises "NoReverseMatch: 'demo.localhost' is not a registered namespace"
I don't seem to find a way to solve an error happening at the user authentication. User needs to login at the public website level let's say localhost/login and when he/she is authenticated, I need the user to be redirected in the corresponding sub domain, for example demo.localhost. This is not working for me so far, even after checking some posts about the subject. Here is the views.py in customers.views where user log in: def login_view(request): if request.method == 'POST': form = AuthenticationForm(request,data=request.POST) print("form login view") if form.is_valid(): print("checkpoint") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) user = form.get_user() schema_name = user.schema_name print(user) if user is not None: login(request, user) url = reverse(schema_name + '.localhost:8000/mydashboard/') print("url") return HttpResponseRedirect(url) else: print("not working") form = AuthenticationForm() context = { 'form': form, } return render(request, 'login.html', context) here is what urls in the core folder: urlpatterns = [ path('admin/', admin.site.urls), path('django_plotly_dash/', include('django_plotly_dash.urls')), path('mydashboard/', include('mydashboard.urls',namespace="mydashboard")), ] and I have added app_name = 'mydashboard' in mydashboard.urls Here is the traceback of the error I keep getting: Internal Server Error: /registration/loginUser Traceback (most recent call last): File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'demo.localhost' During handling of the above … -
Django ORM count or get precentage report
I have three models named Category, Account, and AccountCategory. I need to be able to generate a report wherein I can show the number of which each account was categorized. (e.g let's say I have 10 accounts, then I have three categories (A, B, C) I need to be able to show a piechart) Account has a many-to-many relationship with Category and AccountCategory is the junction table. Ideally, I need to have a result of Name Slug Percentage Num of Accounts A a 40% 4 B b 10% 1 C c 50% 5 I was able to get the raw Query but I still need to get the total number of accounts so I can get the percentage I'm struggling with how to do this on ORM. Basically, I did query the categories, joined account categories, and did a distinct on the account so it won't return the duplicates and then just total the result. For the ORM I think I need to filter the account categories to only return the latest account category per account and then total it but I can't seem to write the exact query using ORM I tried using the Subquery and Prefetch but no … -
Save a CSV in a Django FileField through a Django view
I am trying to save a whole CSV file uploaded from a form through a Django view. However, when I click the button to upload the CSV to the FileField I get 'str' object has no attribute 'file' I have seen some questions like this but I haven't managed to save the CSV in the model. What am I missing? The model: class wordsFile(models.Model): table = models.ForeignKey(WordsTable, on_delete=models.CASCADE) file = models.FileField(upload_to='media/%Y/%m/%d/', blank=True, null=True) def save(self, *args, **kwargs): self.file.save(self.file.name, self.file, save=False) views.py: def home(request): if request.method == 'POST': tp = request.POST.get('tp') if tp == "Upload CSV": if request.user.is_authenticated: upCSV = request.FILES.get('upload') wordsFile.save(upCSV.name, upCSV) #HERE is where I save the CSV to the FileField decoded_file = upCSV.read().decode('utf-8') io_string = io.StringIO(decoded_file) usr = User.objects.get(username=request.user) for idx,row in enumerate(csv.reader(io_string, delimiter=',')): if idx!=0: wt = WordsTable() wt.user = usr wt.word1 = row[0] wt.word2 = row[1] wt.word3 = row[2] wt.word4 = row[3] wt.word5 = row[4] wt.save() return redirect("home") The form: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="upload" accept=".csv, .xlsx" value="Upload"> <br> <input type="submit" id="btnupload" class="button btn btn-primary" name="tp" value="Upload CSV"> </form> -
How to get query list that does not exist in another model in Django ORM?
I have three table: Table1 class Table1(models.Model): field1 = model.CharField(...) field2 = model.CharField(...) Table2 class Table2(models.Model): field1 = model.CharField(...) field2 = model.CharField(...) Table3 class Table3(models.Model): table1 = model.ForeignKey(Table1) table2 = model.ForeignKey(Table2) I want to get all Table1 data that does not exists in Table3 with a which also includes Table2. For Example: In Table1 I have three rows: rows1, rows2, rows3 In Table2 I have One rows: r1 In Table3 I have One rows: table1 = rows1 table2 = r1 I want to get rows2 and rows3 from Table1 when I am searching against Table2s r1 in Table3 I can get my expected result using this code: table3 = Table3.objects.filter(table2=Table2.objects.get(field=r1)).values_list('table1') queryset = Table1.objects.filter(~Q(id__in=table3 )) My Question now is there any better way to do this? Thanks -
how to send POST request with Postman using Django 4 ?? faced with : "detail": "CSRF Failed: CSRF token missing."
I faced with the problem. I write a simple test app. Now I want to use Postman to send a request. Everything is going ok if I send GET request I got all staff correctly. But if I try to send POST or PUT the error is "detail": "CSRF Failed: CSRF token missing." I logged in by admin. I took cookies from the session: sessionid and csrftoken but it did not work. In postman I tried copy CSRF token from headers. I used all this 3 tokens in fact. I tried usr each separately but all my attempts fold. What shall I do to send POST in Django 4 through Postman?????? I use here oauth with github but the error appears in both cases: login with admin or oauth. My code is below settings.py '''' """ Django settings for books project.`enter code here` Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # … -
Error with Django import-export. | unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'
I'm trying to import data with import-export to my model on the admin page. When I do this I get the following error: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta' I can trace the error back to my model. See below. It's in the 'def save' part. class MeetingDataLED(models.Model): led_date = models.DateField() led_meeting_date = models.DateField(blank=True) led_start_time = models.TimeField(blank=True) led_type_of_meeting = { ('GBS', 'Special one'), ('KO', 'Special two'), ('NM', 'Special three'), } led_meeting_type = models.CharField(max_length=3, choices=led_type_of_meeting) def save(self, *args, **kwargs): d = timedelta(days=MeetingSetting.objects.get(id=1).meeting_day_led) self.led_meeting_date = self.led_date + d self.led_start_time = MeetingSetting.objects.get(id=1).meeting_time_led super().save(*args, **kwargs) I've read in this post on stackoverlfow that it might have to do with the datetime instance (if I understand it correctly). I tried to adjust it, but got errors. But when I manually import 1 record on the admin page I do not get this error. So I don't now if I have to look for a solution in this direction. Also, in my resources.py file I do not ask to import the fields of led_meeting_date and led_start_time. See below for the admin and resource file. admin.py from import_export.admin import ImportExportModelAdmin from .resources import MeetingDataLedResource from django.contrib import admin from .models import MeetingDataLED, MeetingSetting admin.site.register(MeetingSetting) class … -
Get relative path in Django
I've created a map where I want to implement some kml files into it . If i harcode the url it works but im trying to pass it through a variable because Im dealing with many kml files in a for loop. Even though the url path im getting in console is right i dont get the result i need.Any idea how to fix that? view: def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) If i hardcode the url it goes like this : var polygon = omnivore.kml("{% static '../media/kml/user_admin/2022-04-07-2-Arnissa_cherry.kml' %}", ... ); I've tried doing it like this but even though the path Im getting is correct it seems django does not read the path(kml is the FileField in my model): map.html {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var kmldir = "../media/" + "{{field.kml.name}}" console.log(kmldir) // ../media/kml/user_admin/2022-04-07-2-Arnissa_cherry.kml var polygon = omnivore.kml("{% static 'kmldir' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 }} })); kml_arr.push([polygon, "{% static 'kmldir' %}"]); //file url {% endfor %} -
Django UserPassesTestMixin raises an unhandled exception
I'm using the UserPassesTestMixin on one of my views. It works fine, but every time a user fails the test (test_func returns False), an exception is raised in the server: Forbidden (Permission denied): /m/chats/8/ Traceback (most recent call last): ... .../django/contrib/auth/mixins.py", line 48, in handle_no_permission raise PermissionDenied(self.get_permission_denied_message()) django.core.exceptions.PermissionDenied: Sorry, you can't access this chat. [11/Apr/2022 11:53:04] "GET /m/chats/8/ HTTP/1.1" 403 135 Why doesn't it just show the last line? Like a 404 error when using a get_object_or_404 function. And also, it only uses the permission_denied_message attribute that I set for the exception message and it is not shown to the user. I know that I can override the handle_no_permission method, but is there a better way? Why does this even happen? get_object_or_404 raises an exception too; so how come that one is handled and this one is not?? -
TypeError: __str__ returned non-string (type tuple) , No sure where I got wrong
Customer ID is the foreign key in phones model, the idea is to populate PhonesForm with customers ID during Form creation on my views. Here my model.py class class Phones(models.Model): primaryimei = models.BigIntegerField(primary_key=True) customerid = models.ForeignKey(Customers,on_delete=models.CASCADE,max_length=200) def __str__(self): template = '{0.primaryimei}' return template.format(self) class Meta: ordering = ['status'] Here is my forms.py class class PhonesForm(forms.Form): customerid = forms.ModelChoiceField( queryset=Customer.objects.all().only('idno'),to_field_name="customerid") def label_from_instance(self): return str(self.customerid) class meta: model = Phones fields = '__all__' views.py file look like this class PhoneCreate(LoginRequiredMixin, CreateView): model = Phones form_class = PhonesForm() success_url = reverse_lazy('phones') def form_valid(self, form): form.instance.user = self.request.user return super(PhoneCreate, self).form_valid(form) ``` -
why do we get the below error in python django when the function is working postgresql [closed]
from rest_framework.response import Response from rest_framework.request import Request import json from django.db import connection from django.http import HttpResponse import psycopg2 from rest_framework.views import APIView from DBConnections.connections import executeGet, executePost, executeGetCustomer class getCoustomerDetails(APIView): def get(self, request): try: customerdata = 'public.fn_getcustomerudetails' customerno = request.data['Customer_No'] data = { "cust_id": customerno } result = executeGetCustomer(customerdata, data) return Response(result) except Exception as error: print("connection failed", error) finally: connection.close() print("connection closed") -
Element not hide when page is reloaded?
I use JQuery formset librairy to manage django inline formsets in my forms. I can add new formset using 'add' button and suppress formset using 'delete' buttons (django-inline-formet). But I have added "lock/unlock" functionality to my forms that disabled all fields when lock button (id = lock) is clicked. So, when form is "locked", fields are disabled and 'add' and 'delete' buttons must also be hidden. I manage to show/hide buttons on lock button click by user. But, when form is locked and page is reloaded by user (F5), 'add' and 'delete' buttons are displayed. It seems that code in function executed with document.ready is not fire. But if I 'manually execute' the code it works. What I have missed? function disabled_field(action) { $('#form').find(':input').not(':button,:hidden').each(function () { if (action == 'locked') { $(this).prop('disabled', true); } else { // only if user has write privilege on form if ($('#is_locked').data('add-privileges') === 'True') { $(this).prop('disabled', false); } } }); } //index of the last empty formset added with 'extra' inlineforsmet parameters var index = formsetnumber() - 1; /* lock a form */ $("body").on("click", '#lock', function (event) { // form is locked => hide inlineformset buttons if ($('#lock').attr('aria-pressed') == 'false') { // hide all formset … -
Reset Postgres' table sequence
I have a table in my application dockets for which I want to reset the sequence/pk I read that sqlsequencereset is used to do so but how do I do that for a single table and not the whole application I tried: python manage.py sqlsequencereset dockets and it produced the following: BEGIN; SELECT setval(pg_get_serial_sequence('"dockets_materialrequestflow"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "dockets_materialrequestflow"; SELECT setval(pg_get_serial_sequence('"dockets_materialrequest_flows"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "dockets_materialrequest_flows"; SELECT setval(pg_get_serial_sequence('"dockets_materialrequest"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "dockets_materialrequest"; COMMIT; How to proceed with only making changes in this particular table ? -
How to show files in django templates from database?
I am trying to display files in django templates. It's showing successfully from the database. I don't why it's not showing from templates. Here I am sharing my codes so far. #models.py class Answer(models.Model): description = models.TextField(blank=True, null=True) question_id = models.ForeignKey( Question, blank=False, on_delete=models.CASCADE) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) def __str__(self): return self.question_id.description class AnswerFile(models.Model): answer = models.ForeignKey( Answer, on_delete=models.CASCADE, related_name='files', null=True, blank=True) file = models.FileField( 'files', upload_to=path_and_rename, max_length=500, null=True, blank=True) def __str__(self): return str(self.answer) As I need multiple files so I have created another file model with foreign key #forms.py class AnswerForm(ModelForm): # question_id = forms.IntegerField(required=True) class Meta: model = Answer fields = ['description'] widgets = { 'description': forms.Textarea(attrs={"class": "form-control", "id": "exampleFormControlTextarea1", "rows": 5, "placeholder": "Add a reply"}), } class AnswerFileForm(AnswerForm): # extending Answerform file = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta(AnswerForm.Meta): fields = AnswerForm.Meta.fields + ['file', ] def clean(self): cleaned_data = super(AnswerFileForm, self).clean() file = cleaned_data.get("file") description = cleaned_data.get("description") if not file and not description: raise forms.ValidationError("This is a required field.") return cleaned_data in forms I also try to stay clear and everything is working perfectly in views.py #views.py def question_details(request, pk): question = Question.objects.filter(id=pk).first() # answers list answers = Answer.objects.filter(question_id=pk).order_by('-id') # end answers list answerForm = AnswerFileForm() … -
ABSTRACT USER IN DJANGO ALL AUTH
I use the Abstract User in my registration using the all auth plugin instead of the contrib auth. Here is my code in forms.py: class CustomSignupForm(UserCreationForm): first_name = forms.CharField(max_length=30, label='First Name', widget=forms.TextInput(attrs={'placeholder': 'First Name','required':'required'})) last_name = forms.CharField(max_length=30, label='Last Name', widget=forms.TextInput(attrs={'placeholder': 'Last Name','required':'required'})) email = forms.EmailField(max_length=40, label='Email Address', widget=forms.TextInput(attrs={'placeholder':'Email Address','required':'required'})) class Meta: model = Registrations fields = ['first_name', 'last_name','email', 'user_type'] In my models.py: class Registrations(AbstractUser): usertype =[ ('Student', 'Student'), ('Staff', 'Staff') ] user_type = models.CharField(max_length=10,choices=usertype, blank=True, null=True) And here is the settings.py for my registration: ACCOUNT_FORMS = {'signup': 'libraryApp.forms.CustomSignupForm',} AUTH_USER_MODEL = 'libraryApp.Registrations' My very concern is that if I did it right using the abstract user with the Django All Auth because I have not seen tutorials regarding the use of abstract user in All Auth. -
Django CheckboxSelectMultiple widget rendering as radio with Crispy Forms
The field was already set as a ModelMultipleChoiceField with the CheckboxSelectMultiple widget. It displays normally when rendering the form with { form.as_p } on the template, but using CrispyForms changes the field to radio buttons. forms.py: class RequisitionModelForm(forms.ModelForm): class Meta: ... def __init__(self, *args, **kwargs): super(RequisitionModelForm, self).__init__(*args, **kwargs) self.fields['reqItems'] = forms.ModelMultipleChoiceField( queryset=Inventory.objects.all(), widget=forms.CheckboxSelectMultiple, ) Images: Using { forms.as_p } Using { forms|crispy } -
Django - prevent function to execute multiple times
DJANGO: The form data is downloading multiple times when I call the function multiple times by clicking the form "submit" button. How do I avoid multiple function calls?