Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Making a Reservation system
As a part of a task, I created an "apartment listings" website. I managed to get that done, but now I need to make a "reservation system" for it. The basic idea is that a logged in user can select an apartment from the listed apartments, pick a "start_date" and an "end_date" and (if the apartment already isn't booked ) and book the apartment. Im a total Django newbie, and need some pointers in order to start somewhere with this task. I have an Apartment model which contains all of the Apartments info that I use to print everything out with the template. I'm using the provided django user models to register / log-in. What kind of model do I need for the reservation, and how could I connect everything ? I tried making a reservation model, but I got no idea where to go next. I'm not asking for you to solve this for me, I'm asking for someone to explain (if possibile in detal) to me how could I go on about achieving this on my own. this is my apartment model: class Apartment(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = … -
Breadcrumbs in custom admin view (Django)
I have custom admin view which works fine, except that I would like to add breadcrumbs. Up to now I only see "Start". But I would like to see "Start > Foo". What do I need to add to my template? -
django google_cloud_logging json format
I am trying to use google_cloud_logging with Django to log JSON logs to Stackdriver. However, the received format on Stackdriver is not as I would expect. My settings.py LOGGING setup looks like: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'stackdriver_logging': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': log_client, }, }, 'loggers': { '': { 'handlers': ['console', 'stackdriver_logging'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['console', 'stackdriver_logging'], 'level': 'INFO', 'propagate': True } } and I write dictionary logs like: _logger.info({'message_type':'profile', 'runtime': 500}) I would expect on Stackdriver for messages to appear as: { ... jsonPayload:{ 'message_type':'profile', 'runtime': 500 } } However they appear with the following format: { ... jsonPayload:{ 'message': "{'message_type':'profile','runtime': 500}" } } where instead of the jsonPayload being directly the sent dictionary, it is string encoded in 'message'. It's unclear what I should change in order to have the desired format on Stackdriver. Could anyone point me in the right direction? -
How to limit items that appear in a form dropdown within a sub form based on the selected value in the main form
I am in the process of creating a purchase order application but am strugging with limiting the products that a user can select based on a selected supplier. I have the following models within models.py: class PurchaseOrders(models.Model): po_number = models.AutoField(primary_key=True) po_date = models.DateField( verbose_name='Purchase Order Date', auto_now_add=True, auto_now=False) supplier_ref = models.ForeignKey( Suppliers, verbose_name='Supplier', on_delete=models.SET_NULL, null=True,) order_net = models.DecimalField( verbose_name='Order Net', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) order_vat = models.DecimalField( verbose_name='Order VAT', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) order_gross = models.DecimalField( verbose_name='Order Gross', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) total_items = models.PositiveIntegerField( verbose_name='Total Items', blank=True, null=True, default=0) delivered = models.BooleanField(default=False, blank=False) def __str__(self): return str(self.po_number) class Meta: verbose_name_plural = "Purchase Orders" class PoLines(models.Model): po_number = models.ForeignKey( PurchaseOrders, verbose_name='Purchase Order', on_delete=models.SET_NULL, null=True,) product_code = models.ForeignKey( Products, verbose_name='Product', on_delete=models.SET_NULL, null=True,) supplier_ref = models.ForeignKey( Suppliers, verbose_name='Supplier', on_delete=models.SET_NULL, null=True,) product_movement = models.OneToOneField( ProductMovement, on_delete=models.CASCADE) product_price = models.DecimalField( verbose_name='Product Price', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) item_quantity = models.PositiveIntegerField( verbose_name='Item Quantity', blank=True, null=True, default=0) item_net = models.DecimalField( verbose_name='Item Net', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) item_vat = models.DecimalField( verbose_name='Item VAT', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) item_gross = models.DecimalField( verbose_name='Item Gross', blank=True, max_digits=12, decimal_places=2, null=True, default=Decimal('0.00')) def __str__(self): return self.product_code.name class Meta: verbose_name_plural = "Purchase Order Lines" class Products(models.Model): product_code = models.CharField( … -
getting error " list indices must be integers or slices, not str "
I am new to Django. in the below data I need to get the values of text(key) from the options list of dicts and return them in list. when i trying to get the values compiler throwing the error saying 'list indices must be integers or slices, not str'.I already spent more than 3hrs on this. Thanks in advance This is my data { 'text':'man', 'offset':0, 'length':3, 'options':[ { 'text':'manglore', '_index':'locations', '_type':'_doc', '_id':'5', '_score':2.0, '_source':{ } }, { 'text':'manipal', '_index':'locations', '_type':'_doc', '_id':'6', '_score':2.0, '_source':{ } } ] } This is my code def search(request): message = request.POST['x'] res = es.search(index = "locations", body = { "_source": "suggest", "suggest": { "places": { "prefix": message, "completion": { "field": "name", "fuzzy": { "fuzziness": "AUTO", "transpositions": "true" } } } } }) city_list = [] output = res['suggest']['places'] for val in output['options']: print(val['text']) city_list.append(val['text']) return HttpResponse(output) -
How can I filter the array contain condition in Django Rest Framework?
I have a model REST list API result like this: URL localhost:8000/api/server/list: [ { "id": 320, "ipv4s": [ { "id": 1393, "vlanedipv4networkgroup": { "name": "52", "id": 147 }, "ip": "43.224.225.89", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null }, { "id": 1394, "vlanedipv4networkgroup": { "name": "52", "id": 147 }, "ip": "43.224.225.90", "netmask": "255.255.255.248", "prefix": 29, "is_gateway": false, "is_network_ip": false, "is_broadcast_ip": false, "desc": null } ], "bandwidth": 1000, "user": null, "is_applied": true, "is_finish_task": true, "simple_hardware_text": "E3-1230v5/16G/256G(SSD)/ ", "switch_management_server_ip": "43.224.224.29", "all_disk_dict": { "total_count": 1, "disk_type": [ 1, 0 ], "total_size": 256 }, "name": "LA-C03-A1", "desc": "2008", "cpu": "Intel Xeon E3-1230 v5", "ram": "Supermicro DDR4___16", "disk": "Intel SSD___256", "disk2": null, "disk3": null, "disk4": null, "disk5": null, "disk6": null, "disk7": null, "disk8": null, "disk9": null, "disk10": null, "price": "1000.00", "pay_time": null, "expire_time": null, "ipmi_addr": "172.18.16.197", "ipmi_account": null, "ipmi_pwd": null, "has_intranet": false, "intranet_ip": null, "customer_desc": null, "whmcs_tblorders_id": null, "recycle_time": null, "ctime": "2019-01-16T21:27:10.870288+08:00", "uptime": "2019-06-25T09:30:55.652359+08:00", "switches": { "id": 14, "name": "LA-C03-A", "desc": "LA-C03-A", "manage_ip": "192.168.200.17", "manage_uname": "ADMIN", "manage_pwd": "ADMIN", "is_listing": true, "ctime": "2019-01-16T17:20:00.458601+08:00", "uptime": "2019-06-12T14:14:19.904123+08:00", "switch_type": 2, "routerdevice": 4, "gatewaydevice": 3 }, "physical_server_model": { "id": 11, "cpu": "Intel Xeon E3-1270 v5", "ram": "Supermicro DDR4___16", "disk": "Intel SSD___1000", "price": "2000.00", "ctime": "2019-01-16T18:42:17.308968+08:00", "uptime": … -
How to load data from variable into django paginator?
I need to create paginator based on data from variable. Variable is just python lists. views.py: def test(request): db = MySQLdb.connect(host="localhost", # your host, usually localhost user="pc", # your username passwd="3346378", # your password db="mc") cur = db.cursor() cur.execute('''SELECT * FROM hello left join hell on hello.Id=hell.Id ''') row = cur.fetchall() So, row is lot's of lists. And how can I load it into paginator? Or one way is to create table and model for data and work with it? -
int() argument must be a string, a bytes-like object or a number, not 'ForeignKey'
I am beginner in Django. I need columns showing only the type_of_due_date that exists in the selected country. In "class InputType" I tried use limit_choices_to and Q function, but see mistake like int() argument must be a string, a bytes-like object or a number, not 'ForeignKey' Please, help. What I did wrong? My models: class InputVatDueDate(models.Model): country = models.ForeignKey(Country, verbose_name='Country', on_delete=models.CASCADE, db_index=True, blank=True) date = models.DateField(_('date'), default=datetime.datetime.now) class Meta: verbose_name = _('input vat due date') verbose_name_plural = _('input vats due date') unique_together = (('country', 'date'),) def __str__(self): return self.country.name class TypeOfVatDueDate(models.Model): vat_due_date = models.ForeignKey(InputVatDueDate, on_delete=models.CASCADE) type_of_due_date = models.CharField(max_length=100, choices=enum_to_choice(TypeDueDates)) date_of_start = models.IntegerField(_('day of start date')) def __str__(self): return self.type_of_due_date class InputType(models.Model): vat_due_company = models.ForeignKey(CompanyVatDueDate, on_delete=models.CASCADE) country = models.ForeignKey(InputVatDueDate, on_delete=models.CASCADE,) type_of_due_date = models.ForeignKey(TypeOfVatDueDate, on_delete=models.CASCADE, limit_choices_to=Q(vat_due_date_id=country), ) -
getting only the date on datetime
Good day! I'm new in using Django and python and I wanted to check only the date in DateTime inside my database. model = Employee_Salary Employee_Salary.objects.filter(emp_id=employee_id, emp_in=datetime.today().date()).exists() so the code I'm currently using is this datetime.today().date() to get only the date if Employee_Salary.objects.filter(emp_id=employee_id, emp_in=datetime.today().date()).exists(): # if emp out exist then stop if Employee_Salary.objects.filter(emp_id=employee_id, emp_out=datetime.today().date()).exists(): messages.info(request,'you are already logged out...') return render(request, 'registration/register.html', locals()) else: Employee_Salary.objects.filter(emp_id=employee_id).update(emp_out=datetime.today()) # should be emp out, rendered and salary messages.info(request,'logged out...') return render(request, 'registration/register.html', locals()) else: #command if employee does not exist add employee register_emp = Employee_Salary(emp_id=employee_id, emp_in=datetime.today()) register_emp.save() messages.info(request,'logged in') return render(request, 'registration/register.html', locals()) #this is my entire code I expected it to check my model Employee_salary's emp_in, which emp_in is a DateTime, then I wanted to check only the date and if there is a date already this day, it will now put a data inside the emp_out instead, but it didn't happen, it made another login of emp_in instead... I really hope I explained it well and thanks in advance on your help! -
Django - Admin - Add link in a change_form that redirect to another change_form
I am newbie inDjango/Python I've started to implement admin forms and try to personnalize behavior I would like to add a link on a specific change_form (not all change forms) that will open a new windows that allow the user to enter data in another change_form without leaving the first change form the 2 forms correspond to 2 models linked (related tables) is-it possible with admin forms? enter image description here -
Django : dynamically update via request.data error
Stock.objects.get(id=1).update( **request.data ) data = request.data print(data) I get this - <QueryDict: {'discount_margin': ['77'], 'rack': ['77'], 'demand': ['77']}> I am getting this - float() argument must be a string or a number, not 'list' -
Is django automatically handle auto-escaping & context aware?
As now I am developing website using django web framework of python. I have very concerned with XSS & security of website. I have read some references related XSS & prevent them using escaping , encoding etc.. so my question is does Django autoescape every input data & handle XSS attacks automatically or explicitly do we need to implement code to prevent XSS attack ? How can we prevent all kinds of XSS attacks in Django ? -
Django, Ajax set progress bar
i have problem of updating html data with ajax while loading file with Django template. Some help: link_1 Data path: In my Progress object is stored updated progress value Ajax is getting this value and updating html tag text with it every second code: view.py def progress(request): if request.method == 'GET': progress_object = Progress.objects.get(id=1) data = dict({'value': str(progress_object.value)}) return JsonResponse(data) template.html <center> <p id="message">bb</p> </center> <script> function fetchdata(){ $.ajax({ url: '/products/progress/', type: 'GET', dataType: 'json', success: function (data) { $( '#message' ).text(data.value); console.log(data.value); if (data.value == 100) { clearInterval(id); } }, }); } $(document).ready(function(){ id = setInterval(fetchdata,1000); }); </script> Result: get progress value is working but is not updating the html tag text while file is processing [spinning]. I get only last result - 100 %. Question: how to update template every second with progress value? -
How to use two user of model to login in website
I am making 3 models in models.py 1)Patients, 2)Doctor, 3)Record. I need a patient and doctor to login to a website. I tried to separate both authentications in one view but I'm not able to login in actual. here Models.py from django.db import models from django import forms from django.contrib.auth.models import AbstractUser # Create your models here. class Patient(models.Model): ppname = models.CharField(max_length=264,unique=True) patient_name = models.CharField(max_length=264) pemail = models.CharField(max_length=264) ppass = models.CharField(max_length=264) page = models.FloatField(max_length=20) padd = models.CharField(max_length=264) ppin = models.PositiveSmallIntegerField() pstate = models.CharField(max_length=264) def __str__(self): return self.patient_name class Doctor(models.Model): dpname = models.CharField(max_length=264, unique=True) dname = models.CharField(max_length=264) dedu = models.CharField(max_length=264) dexpr = models.FloatField() dhadd = models.CharField(max_length=264) dhpin = models.PositiveSmallIntegerField() dhstate = models.CharField(max_length=264) demail = models.EmailField(max_length=264) dpass = models.CharField(max_length=264) dcerti = models.ImageField(upload_to = "media/doc_certi", blank=False) dpic = models.ImageField(upload_to = "media/doc_certi", blank=False) def __str__(self): return self.dname class Record(models.Model): ppname = models.ForeignKey(Patient,on_delete = models.PROTECT) dpname = models.CharField(max_length=264) disease = models.CharField(max_length=264) medicine = models.TextField() rname = models.CharField(max_length=264) rdoc = models.FileField(upload_to='media/pat_report',blank=True) def __str__(self): return self.rname my view.py :- from django.shortcuts import render from django.views.generic import View,TemplateView #for password from passlib.hash import pbkdf2_sha256 #for forms from .forms import PatientForm,DoctorForm,RecordForm,DLoginForm,PLoginForm #for login from django.urls import reverse from django.http import HttpResponseRedirect,HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout … -
Django Python arrange json into a single node
I'm working with a legacy database which has 2 records, the data in each record contain the following values: Name, Email, Company, Phone These 2 records contain the same data value except the value for Phone which is different. When I retrieve them in JSON I get the following output: "results": [ { "Name": "Mack", "Email": "Mack@email.com", "Company": "Company Name", "Phone": "123456789" }, { "Name": "Mack", "Email": "Mack@email.com", "Company": "Company Name", "Phone": "1111111" } ] My question: As you can see there is some duplicate data in the output above, so is there a way to arrange the JSON output to the following: "results": [ { "Name": "Mack", "Email": "Mack@email.com", "Company": "Company Name", "Phone": "123456789" "Phone 2": "1111111" } ] Here is the code for Views.py file: class DataView(viewsets.ModelViewSet): queryset = DataList.objects.all() serializer_class = DataSerializer Here is the code for Serializers.py file: class DataSerializer(serializers.ModelSerializer): data_details = serializers.SerializerMethodField() class Meta: model = DataList fields = 'data_details' def get_data_details(self, obj): return [{ 'name': obj.name, 'email': obj.email, 'company': obj.company, 'phone': obj.phone, }] Here is the code for models.py file: class Data(models.Model): name = models.CharField(db_column='name', primary_key=True, max_length=50) email = models.CharField(db_column='email', max_length=50) company = models.CharField(db_column='company', max_length=100) phone= models.TextField(db_column='phone') class Meta: managed = False db_table = … -
Form is not responding to submit
I have form, user must fill it and submit but I have no reaction from this form First I thought there is a problem with action directive of the form, so used redirect method in the views but no help def organization_info(request): organization_form = OrganizationInformationForm() context = { 'organization_form': organization_form } if request.method == "POST": print("POST") organization_form = OrganizationInformationForm(request.POST, request.FILES) if organization_form.is_valid(): print("VALID") new_org = OrganizationInformation.objects.create(**organization_form.cleaned_data) print("FILLED") return redirect(organization_list) return render(request, 'organization_form.html', context) <form method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-sm-4 control-label">Organization Name:</label> . . . <div class="form-group"> <div class="col-sm-4 col-sm-offset-4"> <button type="submit" class="btn btn-pink">Submit</button> </div> </div> </form> I only have the "POST" printed on the log no any errors -
When i try to run makemigrations command in django it gave me an error
When i try to run makemigrations command in django it gave me an error TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not list Help me to resolve this issue. This is my static root and media roots all stuffs. STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = [os.path.join(BASE_DIR, 'static_root')] MEDIA_ROOT = [os.path.join(BASE_DIR, 'media_root')] -
Django form requires resubmission
I have a simple form in Django, and in my template I want to display each individual object for the whole queryset which I am saving the form to. The error I am getting is that my form does not seem to submit on the first attempt. Only when I click the submit button, manually refresh the page and then 'confirm form resubmission' do I see my updated queryset objects displayed in the template. I am saving my form like this in my views: exercise_name = ExerciseName.objects.all() if request.method == 'POST': form = ExerciseNameForm(request.POST) if form.is_valid(): form.save(commit=True) else: form = ExerciseNameForm() and passing the queryset to the template through the following context: { 'exercise_name': exercise_name } and iterating through it like {% for exercise_title in exercise_name %} #content displaying each iteration {% endfor %} with my form to update it like: <div> <form method = "POST">{% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default">Save</button> </form> </div> I am not sure why it is making me refresh the page and resubmit the form again in order to see the updated queryset after submitting the form? -
Django ManyToManyField Unique item
I am writing a model which is below: class Person(models.Model): name = models.CharField(max_lenght=50) class Group(models.Model): admins = models.ManyToManyField( Person, related_name='group_admins' ) members = models.ManyToManyField( Person, blank=True, related_name='group_members' ) I want a Person Can't join another group if he belongs to a Group. I mean, group members or a Group admin can't join a new group if he/she belongs to in a group. Can anyone help me to make it happen? -
How to send html as Json response in Django?
How can i get the whole data from get_context_data(), and pass it to the template as JSON?I want to send back the html to the template, and to use it's context data in ajax success method. -
Compare values from a form field value and a queryset value
In my app the SignUp form looks like this: Forms.py class EmployeeSignUpForm(UserCreationForm): company = forms.ModelChoiceField(queryset=Company.objects.all(), required=True, label='Select Company') company_code = forms.IntegerField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save (self): user = super().save(commit=False) user.is_employee = True user.save() c_company = self.cleaned_data['company'][0] employee = Employee.objects.create(user=user, company=c_company) return user How can I compare the c_code with the company_code in my models.py and save the form only when both of them matches else throw an error? Models.py class Company(models.Model): company_name = models.CharField(max_length=255, default=0) company_email = models.EmailField(max_length=255, default=0) company_phone = models.CharField(max_length=255, default=0) company_code = models.IntegerField(default=0) def __str__ (self): return self.company_name -
How do I use a jQuery gallery (fotorama) in my Django project?
I've created a page in Django which serves images of a specific car into a gallery slider like this My problem is that it's not even recognizing the fotorama gallery. The <div class="fotorama"></div> shows up in the inspect code, but the images are still spread out in html's default layout. Jquery isn't linked because I've linked to it in the base.html file for bootstrap, so I know it works. I'm hosting the fotorama.js and .css locally since they didn't work when served via CDN. Yes, I've already run collectstatic. <head> ... {% load static %} <link href="{% static 'css/fotorama.css' %}" rel="stylesheet"> <script src="{% static 'js/fotorama.js' %}"></script> </head> ... <div class="container"> <div class="row"> <div class="col justify-content-center"> <div class="fotorama"> <img src="/static/images/placeholder.jpg"> {% for image in car.image_set.all %} <img src="{{ image.image.url }}"> {% endfor %} </div> </div> </div> </div> Just as a quick test, I served a normal image outside of all the other container, row, and col divs. It also didn't make a difference. <div class="fotorama"> <img src="/static/images/placeholder.jpg"> </div> This is what the page looks like: I made a quick page outside my django project, and fotorama works perfectly. Could this be a django-specific issue? Is there an extra plugin/extra code I … -
Proper implementation of Django model inheritance architecture?
I'm building simple Django app for reviews of diffrent objects (restaurants, car services, car wash etc), so I started with the app, but soon I faced first problem, every object have features (but every type of object have different features), for example restaurants have (garden, playground, seats etc, type of kitchen), car washes have (external cleaning, internal cleaning etc). So I started to build typical DB implementation with ManyToMany tables, but then I found Django Model Inheritance, so I implement it in my APP, as you can see: urls.py: from django.urls import path from . import views urlpatterns = [ path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects'), path('add/', views.add_object, name='add-object'), path('<str:category>/<int:pk>/', views.show_object, name='show-object'), path('all/<str:category>/', views.show_all_objects, name="show-all-objects"), ] models.py: from django.db import models from users.models import ProfileUser from django.utils import timezone # Create your models here. class Object(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) address = models.CharField(max_length=300) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class SportFitness(Object): is_fitness_trainer = models.BooleanField(default=False) class CarService(Object): is_parts_clients = models.BooleanField(default=False) class BeautySalon(Object): is_hair_salon = models.BooleanField(default=False) is_laser_epilation = models.BooleanField(default=False) class FastFood(Object): is_pizza … -
i am suffering with the problem of the message dialog box in the django????Help me out his
I tried the message box code in my django frame work for whenever any action perform on the button it will show the dialog box says data entered or any other messgae like this.But Nothing is appear on the window IN THE VIEWS PANEL:- from django.contrib import messages def form(request): if request.method=="POST": n = request.POST['fname'] fnumber = request.POST['fphonenumbe'] ft = request.POST['ftime'] fgend=request.POST['gender'] fdob = request.POST['fdob'] s= Officers() s.fname=n s.dsg=Designations.objects.get(id=request.POST['desigid']) s.dpt=Departments.objects.get(id=request.POST['departid']) s.pst=Postings.objects.get(id=request.POST["postid"]) s.ftime=ft s.image = request.FILES['photo'] s.fphonenumber=fnumber s.fgender=fgend s.fdob=fdob s.save() messages.success(request,"Officer Added Successfully.") return render(request,'form.html') else: d = Designations.objects.all() dp = Departments.objects.all() p=Postings.objects.all() return render(request,'form.html',{'desig':d,'depart':dp, 'post':p}) FORM PANEL:- <div class="form-group"> <label for="middle-name" class="control-label col-md-3 col-sm-3 col-xs-12">Phone Number</label> <div class="col-md-6 col-sm-6 col-xs-12"> <input name="fphonenumbe" id="" class="form-control col-md-7 col-xs-12" type="text" name="middle-name" placeholder="Enter Phone Number"> </div> -
Django - How to prevent empty record in admin subform?
I am newbie in Django and Python so hope you will be indulgent I've read and read again the Django documentation but for now, some concept still are very abstract for me... I have a database and I use ModelForm and I try to customize this admin forms I currently have a main form with a subform and both forms are customized I noticed 'abnormal' behavior (unwanted): even when no entry is made in the subform, empty record is stored in the table corresponding to the subform in the database how to prevent this? I have compared with other forms/subforms in my app that did not have this behavior but coul not find what is wrong because code seems to be the same... thanks in advance fory your help models.py : class SuiviAppuiCommunitaire(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE com_ide = models.AutoField(primary_key=True) pat = models.ForeignKey(Participante, verbose_name='Participante', related_name='community', on_delete=models.CASCADE) com_dat = models.DateField("Date de la demande",null=True,blank=True) com_mot = models.IntegerField("Motif", max_length=1,null=True,blank=True) com_det = models.CharField("Détails", max_length=255,null=True,blank=True) com_com = models.CharField("", max_length=255,null=True,blank=True) log = HistoricalRecords() class Meta: db_table = 'crf_com' verbose_name_plural = '5.1-Appuis / Suivis communautaires(COM)' ordering = ['pat', 'com_dat','com_ide'] def __str__(self): return f"{self.com_ide} / {self.pat.pat_ide_prn_cse} / {self.com_dat}" @property def participante(self): return self.pat.pat_ide_prn_cse participante.fget.short_description = 'Participante' class InterventionCommunautaire(SafeDeleteModel): _safedelete_policy …