Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom template tag: where to actually put it in the template?
After completing the Django tutorial, I am trying to follow the instructions in the "Inclusion tags: section of https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ . I am not familiar with the syntax of template tags and I wasn't able to figure out reading the documents either. polls_extra.py : from django import template from django.template.loader import get_template register = template.Library() @register.inclusion_tag('results.html') def show_results(poll): choices = poll.choice_set.all() return {'choices': choices} results.html : <h1>{{ question.question_text }}</h1> {% load poll_extras %} <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href= {% show_results poll %}>Vote again?</a> Then when I submit a poll choice I get the error: AttributeError at /polls/1/results/ 'str' object has no attribute 'choice_set' How should it actually be included in the html? -
Models trained with TensorFlow are not available in Django
Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error: Key bias_1 not found in checkpoint [[node save_1/RestoreV2 (defined at Programing\web_programing\django\django-vegiter\predict\views.py:20) ]] Trace Back saver.restore(sess, save_path) … err, "a Variable name or other graph key that is missing") Run in Python virtual environment Django 2.2.5 Keras-Applications 1.0.8 Keras-Preprocessing 1.1.0 numpy 1.17.1 pandas 0.25.1 tensorboard 1.14.0 tensorflow 1.14.0 tensorflow-estimator 1.14.0 termcolor 1.1.0 Create your views here. def index(request): X = tf.placeholder(tf.float32, shape=[None, 4]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([4, 1]), name="weight") b = tf.Variable(tf.random_normal([1]), name="bias") hypothesis = tf.matmul(X, W) + b saver = tf.train.Saver() model = tf.global_variables_initializer() sess = tf.Session() sess.run(model) save_path = "./model/saved.cpkt" saver.restore(sess, save_path) if request.method == "POST": avg_temp = float(request.POST['avg_temp']) min_temp = float(request.POST['min_temp']) max_temp = float(request.POST['max_temp']) rain_fall = float(request.POST['rain_fall']) price = 0 data = ((avg_temp, min_temp, max_temp, rain_fall), (0, 0, 0, 0)) arr = np.array(data, dtype=np.float32) x_data = arr[0:4] dict = sess.run(hypothesis, feed_dict={X: x_data}) price = dict[0] else: price = 0 return render(request, 'predict/index.html', {'price': price}) POST Variable Value csrfmiddlewaretoken 'BeE48x03YbOY3tIC7eF8L0tKrZME' avg_temp '24' min_temp '12' max_temp '31' … -
Im tried to try many solution to solve HTTP status code must be integer in django when pass varible by render
Dears I have 3 model and i want pass them to teplate by render since when i put third array i get error : HTTP status code must be an integer My model is Calss Dashwidget(models.Model): Wname=models.charfield(max_lenght=200) Categoryw=models.ForeignKey(category,related-name='categorydashboard',one_delete=models.CASCADE) preserve_default=false, sql_query=models.TextField('sql',blank=False) My veiw: def dashbaord(request): domain_list=domain.objects.all() Context={'domain_list', domain_list} Category_list= Category.objects.all() Contextcategory={'Category_list', Category_list} Widget_list=Dashwidget.objects.all() Contextwidget={'Widget_list', Widget_list} return render(request,"Dashboard.html",Context,Contextcategory,Contextwidget) -
render staticfiles django with react redux
I have a few objects saved on database that I received by Django RestFramework. That database have a few columns e one of them is ImageField. I already have all setup and my image field's response is "media/product_path.jpg". When I tried render that image field shows me a invalid image, with a image icon and the alt tag. In console from browser don't show the image path. { this.props.products.map(product => ( <tr key={product.id}> <th scope="row"> <img src="{product.image}" alt="product.image" /> </th> <th scope="row"> {product.name} </th> </tr> )) } APIProduct do Django: class APIProduct(APIView): parser_class = (FileUploadParser,) def get_queryset(self): return Product.objects.all().order_by('-created_at') def get(self, request, *args, **kwargs): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): file_serializer = ProductSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: urlpatterns = [ path('', include(router.urls)), path('categories/', APICategory.as_view()), path('products/', APIProduct.as_view()), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get file name of script passed to manage.py shell?
I'm running a script by passing it to ./manage.py shell: ./manage.py shell < script.py Inside the script.py is: import sys from os.path import basename print(sys.argv[0]) print(basename(__file__)) print(__file__) When I run ./manage.py shell < script.py, it does not print 'script.py' but: ./manage.py shell.py [full_path_to]/shell.py How can I output the actual name that is 'script.py'? -
How to get Stripe subscription id?
I'm new to python and Stripe. How to get the subscription id to process a cancelation? # Here is my views.py where I create the plan stripe.api_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': try: token = request.POST.get('stripeToken') user = request.user plan = 'plan_xxxxxxx' order_number = x customer = stripe.Customer.create(description='Membership', source=token, email=user.email, plan=plan) charge = stripe.Subscription.create( customer=customer.id, items=[{'plan': plan}] ) In the view below, I have the customer information but not sure how to cancel. user = request.user cust_id = str(list(Premium.objects.filter(user=user).values_list('stripe_customer_id')))[3:-4] # this retrieves the customer information customer = stripe.Customer.retrieve(cust_id) # this does not work! stripe.Subscription.delete(customer['subscription']) This fails because and I get this error: KeyError: 'subscription' -
azure web app for containers uWSGI listen queue of socket full
My app running in a docker container on Azure Webapps for Containers (linux). I found out my server is getting error when listening queue increases. log: uWSGI listen queue of socket "127.0.0.1:37400" (fd: 3) full !!! **(101/100)** I have added '''--listen 4096''' option to increase the queue. but my server still throws error. log: uWSGI listen queue of socket "127.0.0.1:37400" (fd: 3) full !!! **(129/128)** some reference says need to increase net.core.somaxconn but I couldn't increase it. log: sysctl: error: 'net.core.somaxconn' is an unknown key Any idea what i am missing? Thanks -
How to add csv file that has foreign key value
I am trying to upload a csv file to my system with one foreign key.There are two models involved - Namelist.model : is used to insert the csv file and Groupinfo.model: one of the attribute in namelist is a FK to the groupinfo. Namelist.model: class Namelist(models.Model): name = models.CharField(max_length=100) program = models.CharField(max_length=10) year = models.IntegerField(default=1) studType = models.CharField(max_length=15) courseType = models.CharField(max_length=15) nationality = models.CharField(max_length=20) VMSAcc = models.CharField(max_length=30) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) GroupInfo.model: class GroupInfo(models.Model): classGrp = models.CharField(max_length=10) day = models.CharField(max_length=15) time = models.CharField(max_length=20) venue = models.CharField(max_length=10) language = models.CharField(max_length=30) Below is my view code: def import_studName(request): template = "import_stud.html" prompt = { 'order' : 'Order of the CSV should be id, name, program, year, studType,courseType,nationality,VMSAcc,classGrp' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Namelist.objects.update_or_create( id=column[0], name=column[1], program=column[2], year=column[3], studType=column[4], courseType = column[5], nationality=column[6], VMSAcc = column[7], classGrp =column[8]) context = {} return render(request,template, context) my template: {{order}} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label>Upload file</label> <input type="file" name="file"> <p>only accept csv file</p> <button type="submit">Submit</button> {% endif %} my urls … -
In Django getting errors based on dropdown selection
Getting error when fields are selected from the down. Not seeing why it is throwing error Django Dropdown form.error: ERROR ALERT: location_name Select a valid choice. That choice is not one of the available choices. Here is the model, form, view and html looks like MODEL class Code (models.Model): name = models.CharField(max_length=4, default=None, blank=True) def __str__(self): return self.name class Device (models.Model): code = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) ip = models.GenericIPAddressField(protocol='IPv4', unique=True) def __str__(self): return self.ip class SiteData (models.Model): site = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) site_ip = models.ForeignKey(Device, on_delete=models.SET_NULL, null=True) site_data1 = models.CharField(max_length=3, default='120') class CombineData(models.Model): location = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) device = models.ForeignKey(AddData, on_delete=models.SET_NULL, null=True) locdata = models.ForeignKey(SiteData, on_delete=models.SET_NULL, null=True) FORM class CombineData_form(forms.ModelForm): class Meta: model = P2_NexusLeafPair fields = '__all__' VIEW def comboView(request, *args, **kwargs): template_name = 'site_display.html' code = Code.objects.order_by('-name') device = Device.objects.order_by('-ip') sitename = SiteData.objects.order_by('-site') content = { 'code': code, 'device': device, 'sitename': sitename } if request.method == 'POST': form = CombineData_form(request.POST or None) print(form.is_valid()) #print(form.errors) if form.is_valid(): . . . else: messages.error(request, form.errors) else: form = CombineData_form() return render(request, template_name, content) HTML <form id="comboView" class="post-form" role=form method="POST" action="comboView">{% csrf_token %} <div name="code" class="dropdown" id="mainselection" required> <select name="dc_name"> <option class="dropdown-item" value="">---------</option> {% for item in code %} <option value="{{ … -
I can't sign into the Django admin login page
I have started multiple Django projects with like four different tutorials. Every single time I try "python manage.py createsuperuser", the admin login page just loads and loads and never goes anywhere. I want to make it absolutely clear that I haven't touched a thing in the code and everything is default code. I migrated everything before login. I've tried deleting the database and re-migrating. None of that works. Can someone help me? I have made around 10-15 accounts and NONE of them work. The page just keeps loading indefinitely and never goes anywhere. I've looked at EVERY stackoverflow post and no answers work. I started a virtualenv, downloaded Django, didn't touch the code, made migrations, I followed every tutorial TOO THE LETTER(!!!) and this is what I keep getting. The current tutorial hasn't changed in default code and he signed in with no problems. I'm assuming if he did, I can...I don't think putting code in is necessary since it's all virgin code, never touched. I didn't even make any apps yet. I've tried deleting database and re-migrating changing the password of current superuser deleting the entire project and following everything the instructor said (TO THE LETTER!!!) I have made … -
django rest-auth email confirmation with postmark
I've seen a fair bit about how to override the email templates, but they seem to mostly involve creating HTML templates and overriding the file location. I'm using postmark's templating which involves sending a post request with the email variables. I'm handling that with anymail, as shown below with a form that sends my customer service address an email: class PartnerContact(APIView): """Sends email to Partners@***.com""" @authentication_classes([]) @permission_classes([]) def post(self, request): """Sends Form Data""" print("PartnerContact data", request.data) status_code = status.HTTP_400_BAD_REQUEST msg = EmailMessage( from_email='Partners@***.com', to=['Partners@***.com'], reply_to=[request.data['email']] ) msg.template_id = *** logo = attach_inline_image_file(msg, finders.find("***.png")) msg.merge_global_data = { **{**request.data, **{"logo":logo} } } # <img alt="Logo" src="cid:{logo_cid}"> msg.send() status_code = status.HTTP_200_OK return Response(status=status_code) My goal is to use postmark templates for the account confirmation & password reset emails also, but I'm having a hard time figuring out how to override the send methods. -
Django ModelFormset error empty form field
Django has decided to throw an error when I am submitting the form. The form is a modelformset and I have made absolutely no change to the default, merely clicking on submitting button. Django complains that the only empty form needs to have a value and when I change it to required = False: forms.CharField(max_length = 40, required = False) it stops complaining. Here is my form: class RateForm(ModelForm): costcode = forms.CharField(max_length = 40, required = False) class Meta: model = Rate fields = ['costcode', 'rate', 'UOM', ] class BaseRateFormSet(BaseModelFormSet): def clean(self): ''' No custom cleaning at this point.''' cd = super(BaseRateFormSet, self).clean() To see what is going on, I wrote the custom cleaning and saw that the cd is None when I added assert False after it. the view: rate_formset = RateFormSet(request.POST if any(request.POST) else None, prefix = user.short_name, form_kwargs = the_form_kwargs, **user_form_kwargs) In reality, the field costcode should be required, but Django should realize that the user does not wish to submit any additional form, so it does not generate the error. How do I get Django to not throw an error on an empty form? -
Cannot import ReportLab or FPDF in Django project
I am trying to create a pdf in a Django project, I pip installed the latest version of reportlab successfully but when I tried to import reportlab.pdfgen I got an error modulenotfound for reportlab. So next I tired FPDF and I received the same results. I was able to successfully import both packages out side the Django project the only issues is once it is with in the Django project. -
How to extract a count from QuerySet relations?
I have the follow .model structure: class ArtistWorkPlaceQuerySet(models.QuerySet): def with_related(self): return self.select_related('artist','work', 'place') class ArtistWorkPlaceManager(models.Manager): pass class PersonWorkPlace(models.Model): artist = models.ForeignKey(Artist, verbose_name=_('artist'), related_name='work', on_delete=models.CASCADE) work = models.ForeignKey(Work, verbose_name=_('work'), related_name='place', on_delete=models.CASCADE) place = models.ForeignKey(Place, verbose_name=_('place'), on_delete=models.CASCADE) objects = PersonWorkPlaceManager.from_queryset(PersonWorkPlaceQuerySet)() class Work(models.Model): piece_type = models.CharField(max_length=100, null=True, blank=True) //This is like paintings or sculptures class Artist(models.Model): name = models.CharField(max_length=100) class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) Through this query I can get all of the work by this artist: works = PersonWorkPlace.objects.filter(person=self.kwargs['pk']) How do I go further and search for the number (a count) of works of the same the 'piece_type' at a particular place by the same artist? I would like to pass or extract from context for a particular view the following information: Artist A has 2 painting and 2 sculpture at Place A and 4 paintings at Place B 'context': { (place: 'Place A', painting: '2', sculpture: '2'), (place: 'Place B', painting: '4') } -
Django: How to Get the Result of a Raw SQL "COUNT(*)" Query?
I have a table of keywords that looks like this: CREATE TABLE `keywords` ( `keyword` VarChar( 48 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `id` Int( 11 ) AUTO_INCREMENT NOT NULL, `blog_posts_fulltext_count` Int( 11 ) NOT NULL, PRIMARY KEY ( `id` ) ) I also have a table of blog posts that looks like this: CREATE TABLE `blog_posts` ( `id` Int( 11 ) AUTO_INCREMENT NOT NULL, `title` LongText CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL, `summary` LongText CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL, PRIMARY KEY ( `id` ) ); CREATE FULLTEXT INDEX `title_summary_fulltext` ON `blog_posts`( `title`, `summary` ); As you can see, I have a full text index on the fields title, summary in blog_posts. The following search works correctly: select count(*) from blog_posts where match(title,summary) against ('paid'); Now I'd like to populate the field keywords.blog_posts_fulltext_count with the number of rows in blog_posts that the keyword appears in. When I run this: keywords = Keywords.objects.all() for the_keyword in keywords: query = "select count(id) from BlogPosts where match(title,summary) against ('{0}')".format(the_keyword.keyword) number_of_mentions = blog_posts.objects.raw(query) for obj in number_of_mentions: a = obj ...the RawQuerySet number_of_mentions appears to return without errors, and number_of_mentions.query contains: 'select count(id) from blog_posts where match(title,summary) against ('paid')' But when … -
How can I add parent fields to a Django InlineFormSet?
How can I add a parent field to an InlineFormSet? My attempt: models.py: from django.db import models class Parent(models.Model): parent_name = models.CharField(max_length=45) class Child(models.Model): child_name = models.CharField(max_length=45) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) forms.py: from .models import Parent, Child from django import forms FormSet = forms.inlineformset_factory(Parent, Child, fields='__all__' ) views.py: from .models import Parent from .forms import FormSet def view(req): instance = Parent.objects.get(pk=1) form = FormSet(instance=instance) This results in all of the fields from Child being displayed, but none from Parent. -
How to ignore certain Python errors from Sentry capture
I have Sentry configured to capture all errors from a Django+Celery application. It works ok, but I'm finding an obnoxious use case is when I have to restart my Celery workers, PostgreSQL database or messaging server, which causes thousands of various kinds of "database/messaging server cannot be reached" errors. This pollutes the Sentry reports, and sometimes even exceeds my event quota. Their docs mention an "ignore_exceptions" parameter, but it's in their old deprecated client that I'm not using, nor is recommended to be used for new projects. How would you do this in the new API? -
How to add prefetch_related to __str__
I would like to make my django admin faster and not do multiple queries. I know I can acievie such thing with for example prefetch_related/select_related, but I'm not sure how can I add the functionality of it to the str function. Below is my model: class Work(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(null=True, blank=True) book = models.ForeignKey('Chapter', on_delete=models.CASCADE) job = models.ForeignKey('Job', on_delete=models.CASCADE) user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=True, blank=True) prev_work = models.ForeignKey('self', on_delete=models.CASCADE, editable=False, null=True, blank=True) I would like to see something like this: def __str__(self): return self.book.project.slug + "-" + str(self.book.number) + "-" + self.job.name And once again - I know why it does so many queries, but I'm not sure what would be the best practice to fix the issue. -
Django: Improve queryset
I currently have the following query set and I wonder if there is a way to bring that part question.answers.all() into the questions= query set. def get_questions_and_answers(self): questions = ( self.request.event.surveys.get(template=settings.SURVEY_POST_EVENT) .questions.exclude(focus=QuestionFocus.EMAIL) .all() ) questions_and_answers = {} for question in questions: questions_and_answers[question] = question.answers.all() return questions_and_answers models.py class Question(TimeStampedModel[...]): survey = models.ForeignKey(related_name='questions') type = models.CharField([...]) focus = models.CharField([...]) class Answer(TimeStampedModel): question = models.ForeignKey(related_name='answers') response = models.ForeignKey(related_name='answers') answer = models.TextField([...]) class Survey(TimeStampedModel): event = models.ForeignKey(related_name='surveys') template = models.CharField([...]) -
How to create API to insert data in MySQL passing json with dublicate keys
I am creating a REST API using Django-Rest-Framework to insert data in MySQL database. The table has column like - id, meta key, meta value i.e for particular id it can have duplicate meta keys and their corresponding meta value. I want to pass all the meta keys and meta values of corresponding id in the json but it says Json does not support duplicate keys. What should be my approach to create the api which creates two rows in database if I am passing 2 meta key and value for a same id? The json looks like "order_item_id_2":"154", "meta_key":"_product_id", "meta_value":"602", "meta_key":"_variation_id", "meta_value":"0" "meta_key":"qty", "meta_value":"20" The table should look like: Final table should look like this -
facing problems in verify a token generated link
I am building my own password reset link. Since i do not want to use the default provided by django . Well i am facing a problem creating a token for the user This view get anonymous user email, search if this email is associated to a user. def Get_email(request): email_address= request.POST.get('emailadrees') user=User.objects.filter(email=email_address).first() try: if user is not None: current_site = get_current_site(request) mail_object= 'Password reset' message=render_to_string('password_reset/password_reset_email.html', { 'user':user, 'domain':current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':reset_password_token.make_token(user), }) to_email=user.email email=EmailMessage(mail_subject,message,to=[to_email]) email.send() This link receives the token and let the user change their password def Change_password(request,uidb64,token): try: uid=force_text(urlsafe_base64_decode(uidb64)) user=CustomUser.objects.get(pk=uid) if user is not None and reset_password_token.check_token(user,token): pass else: return HttpResponse("Activation link is invalid! ") except (TypeError,ValueError,OverflowError,CustomUser.DoesNotExist): return HttpResponse("Activation link is invalid! ") My token.py file class TokenGeneratorResetPassword(PasswordResetTokenGenerator): def _make_hash_value(self,user,timestamp): return(six.text_type(user.pk)+user.password+six.text_type(timestamp)) reset_password_token=TokenGeneratorResetPassword() The problem i am facing is like " reset_password_token.make_token(user) " does not create token for the user. What i am doing wrong? The link sent to the email, does not validate in "Change_password" function. -
How I do render a queryset in a Django base template?
I have a base template which extends to almost every other templates in my project. I am trying to populate my categories navigation bar with some queryset from my database but am failing with my approach. Since the base template has no url, I am finding it difficult to render. This is what I've tried: this is my views function def base(request): categories = list(Category.objects.all()) context = { 'categories': categories } return render(request, 'ads/base.html', context) this is my html {% for category in categories %} <div class="nav-item dropdown"> <a href="#" class="nav-link dropdown-toggle" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> { category.name }}&nbsp; <span class="float-right text-muted"> <small> <i class="fas fa-chevron-down"></i> </small> </span> </a> </div> {% endfor %} I just want to populate my navbar with the categories queryset -
Issue with creating an edit view in django
Trying to allow users to edit their data. However, when the link that would take them to the edit page is clicked, I get a "NoReverseMatch" error. I'm pretty sure that it has to do with my view. Any help would be greatly appreciated. I'm stuck like chuck... models.py class Rider(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthdate = models.DateField(verbose_name=None, auto_now=False) NOVICE = 'N' BEGINNER = 'B' COMPETENT = 'C' PROFICIENT = 'P' EXPERT = 'E' skill_level_choices = [ ('NOVICE', 'Novice'), ('BEGINNER', 'Beginner'), ('COMPETENT', 'Competent'), ('PROFICIENT', 'Proficient'), ('EXPERT', 'Expert') ] skill_level = models.CharField( max_length=20, choices = skill_level_choices, default = NOVICE, ) def __str__(self): return self.last_name + ', ' +self.first_name views.py def edit_rider(request, riders_id): riders = Rider.objects.get(id=riders_id) if request.method != 'POST': form = RiderForm(instance=riders) else: form = RiderForm(instanse=riders, data=request.POST) if form is valid(): form.save() return HttpResponseRedirect(reverse('riding_schedule:index')) context = {'riders':riders, 'form':form} return render(request, 'riders/edit_rider.html', context) urls.py path('edit_rider/<int:riders_id>', views.edit_rider, name = 'edit_rider'), edit_rider.html {% extends "riding_schedule/base.html" %} {% block content %} <p>Edit rider:</p> <form action="{% url 'riders:edit_rider' rider.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name = "submit">save changes</button> </form> {% endblock content %} Exception Type: NoReverseMatch at /riders/edit_rider/8 Exception Value: Reverse for 'edit_rider' with arguments '('',)' not found. 1 pattern(s) … -
In Django How to inherit field to populate data
In Django, how to populate data based on selected value from dropdown. Also those fields are inherited from another Model. For example: Class DeviceInfo has for 4 fields, like to inherit in to Class Links. How to setup view so that with dropdown selection of name it will pre-populate location, type and then user can fill out rest fields. MODEL: class DeviceInfo(models.Model): name = models.CharField(max_length=20, default='') location = models.GenericIPAddressField(protocol='IPv4', default='0.0.0.0') type = models.ForeignKey(Types, on_delete=models.SET_NULL, null=True) class Links(DeviceInfo, models.Model): {other fields} FORM class DeviceInfo_form(forms.ModelForm): class Meta: model = DeviceInfo fields = '__all__' field_classes = { 'json_field': JSONFormField, } Thanks for the taking your time, answering. -
Can't update datefield to null
cant insert and update datefield to null err ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] `class StudentUserMedicalRecord(models.Model): ImmnunBCGDateFirstDose=models.DateField(null=True, blank=True) ImmnunBCGDateSecondDose=models.DateField(null=True, blank=True) ImmununBCGDateThirdDose=models.DateField(null=True, blank=True) ImmnunBCGDateBooster1=models.DateField(null=True, blank=True) ImmnunBCGDateBooster2 = models.DateField(null=True, blank=True) def __str__(self): suser = '{0.Student_Users}' return suser.format(self) //my html <td><input type='date' name='firstdate' /></td> <td><input type='date' name='seconddate' /></td> <td><input type='date' name='thirddate' /></td> <td><input type='date' name='firstbooster' /></td> <td><input type='date' name='secondbooster' /></td> //my views first = request.POST['firstdate'] second = request.POST['seconddate'] third = request.POST['thirddate'] booster = request.POST['firstbooster'] secondbooster = request.POST['secondbooster'] V_insert_data = StudentUserMedicalRecord( ImmnunBCGDateFirstDose=first, ImmnunBCGDateSecondDose=second, ImmununBCGDateThirdDose=third, ImmnunBCGDateBooster1=booster, ImmnunBCGDateBooster2=secondbooster, ) V_insert_data.save()