Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models, Gathering models.AutoField number while overriding save() method
I have a Django Model for Users and then a Separate model for AccessLevels. When saving a User using Django's ORM, I want to also place an entry in the AccessLevels table. My issue is that the PK of AccessLevels is the PK of Users and I cannot seem to override the save() method and gather the value of id = models.AutoField(primary_key=True). Here is my relevant code: class Users(models.Model): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # pk id = models.AutoField(primary_key=True) # client_id client_id = models.IntegerField(null=False, blank=False, default="-1") ... def save(self, *args, **kwargs): AccessLevel(user_id=self.id, client_id=self.client_id).save(using='default') print('Access Level Set for User while saving') super(Users, self).save(*args, **kwargs) Here is the important part of AccessLevel class AccessLevel(models.Model): # pk id = models.AutoField(primary_key=True) # this is the id for the user, but I get null value user_id = models.IntegerField(null=False, blank=False, default="-1") client_id = models.IntegerField(null=False, blank=False, default="-1") When I call this code I get the error. root_user = Users(username='root', email='root', first_name='root', last_name='root', phone='root', password=make_password(default_root_pw), type='root').save(using='default') Here is the error django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (3, null, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0). -
create view of oneToMany object in related object view
I have a questionnaire, containing many questions with their answers. My main objective is to create a webpage where I can show the details of a questionnaire with the list of rules (question/answer) and in the bottom of the page I want to call the create rule page: def create_rule_view(request, id, sc_id): if request.method == "POST": input = InputForm(request.POST) answer = AnswerForm(request.POST) rule = RuleForm(request.POST) if rule.is_valid() and input.is_valid() and answer.is_valid(): r = rule.save() i = input.save(commit=False) a = answer.save(commit=False) i.rule_id = r i.save() a.rule_id = r a.save() question = input.cleaned_data["patterns"] else: input = InputForm() answer = AnswerForm() rule = RuleForm() return render(request, "rule/create_rule.html", { 'rule': rule, 'input': input, 'answer': answer }) def detail_scenario(request, id, sc_id): object = get_object_or_404(Scenario, id=sc_id) # TODO : add rule in the same view create_rule_div = create_rule_view(request, id, sc_id) print("content", create_rule_div) context = { 'scenario': object, 'create_rule_div': create_rule_div } return render(request, "scenario/detail_scenario.html", context) This is rule_create.html: {% block content %} <form method="POST"> {% csrf_token %} <h2>Create Rule</h2> {{ rule.name}} {{ input.patterns }} {{ answer.text }} <input type="submit" value="Save Rule"/> </form> {% endblock %} This is detail_senario.html: {% block content %} <h2>Scenario {{ scenario.id }}</h2> <p>Scenario for : {{ scenario.chatbot_id }}</p> <p>Name: {{ scenario.name }}</p> <p>Description: … -
Django admin send email for new user registration
In my project i'm trying to send an email after new user creation. I try like this in my models.py: @receiver(post_save,sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: first_name = instance.first_name last_name = instance.last_name email = instance.email context = { 'news': 'Your testdemo account', 'user': instance.username, 'pass': "test" } html_content = render_to_string('email_demo.html', context) message=EmailMessage(subject='Test Demo Account Registration',body=html_content,to=[email]) message.content_subtype='html' message.send() If i run my user creation proces nothing appen, but if i remove the if created: statement all works ok, execpt for the fact that email was send also when user logged in (i would that email was send just when user is register first time, not when he logged in) So many thanks in advance -
Form Previous to stripe script needs to be fully filled before being able to pay
I have a form previous to a stripe payment button(which is created by a script) that i need people to actually fill properly before paying. this is the script to gray out payment until form is filled (problem it is only for text inputs) <script> $('.stripe-button-el').attr('disabled', true); $('input:text').keyup(function () { var disable = false; $('input:text').each(function () { if ($(this).val() == "") { disable = true; } }); $('.stripe-button-el').prop('disabled', disable); }); </script> the form goes like this <div class="container" style="padding:40px 0px;text-align: center;"> <form method="POST" action="{% url 'charge' %}" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' %}"> {% csrf_token %} <p><label for="id_patient_name">{% trans "Patient Name:"%}</label> <input type="text" name="patient_name" maxlength="60" id="id_patient_name"></p> <p><label for="id_phone_number">{% trans "Phone Number:"%}</label> <input type="tel" name="phone_number" id="id_phone_number"></p> <p><label for="id_patient_country">{% trans "Country:"%}</label> <input type="text" name="patient_country" id="id_patient_country"></p> <p><label for="id_email">{% trans "Email:"%}</label> <input type="email" name="email" maxlength="254" id="id_email"></p> <p><label for="id_event_date">{% trans "Event Date:"%}</label> <input type="date" name="event_date" id="id_event_date"></p> <p><label for="id_start">{% trans "Time:"%}</label> <select class="specialselect" name="start" required id="id_start"> <option value="" selected>---------</option> </select></p> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_KPSQTmUOl1DLP2eMc7zlvcnS" data-description="Buying a 30mn Skype Session" data-amount="3000" data-locale="auto"></script> </form> </div> the code work as for graying out the button, BUT, even with everything filled the button doesnt become available <div class="container" style="padding:40px 0px;text-align: center;"> <form method="POST" action="{% url 'charge' %}" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' … -
ModuleNotFoundError: No module named 'channels' even after rechecking that i have installed the package
there is an issue with my packages, i have installed django channels(just channels) using pip install channels command and when i tried to run server command i just got an error sayinh the module not found but when i run the command pip list | grep channels there are two modules installed channels 2.1.6 channels-redis 2.3.3 i dont know the reason behind the error can somone help me figure out if i have done anything wrong i have added them in insalled app section of settings.py -
Override instance data in a ModelForm
I have a form which includes nested forms for polymorphic related objects: class MyForm(forms.ModelForm): class Meta: model = MyModel exclude = [] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) if self.instance: self.related_forms = [] # our form happens to include nested forms for related objects for related in instance.related_models.all(): # our related_models are polymorphic form_class = modelform_factory(related.__class__, form=RelatedModelForm, exclude=[]) form = form_class(instance=related.__class__.objects.filter(mymodel=instance)[0]) self.related_forms.append(form) I am trying to implement a way to provide initial data to preload the form with a different MyModel instance. Note that I am not trying to define self.initial, this is different. If such a secondary instance is passed to the form constructor, the form and related forms should take its values instead of self.instance, but the form and related forms should remain bound to their original self.instance so that the appropriate entries are updated. How can I do this? Feeding those values to self.initial is not the way to go because all this does is fill in empty values. Passing a different instance to the forms when instantiated is no good either. We would be then filling in the values we want but the form would now be bound to the wrong objects. -
Django Modelform password validate iteration
I am trying to write Django Modelform to prompt user to register an account with a robust password (contains Uppercase, lowercase, digits and special chars). If the multiple conditions for a password are not met, it will raise multiple field level validation error. For example, if I enter a password "shafin071", the Validation errors should say - The password must contain at least 1 uppercase letter, A-Z. - The password must contain at least 1 symbol But right now I'm not getting the 2nd validation error. 1) Can you please help me find a better iteration that will check all the conditions? 2) How can I use clean() to throw a field level validation error instead of form level? I'm fairly new to coding so some explanation will be appreciated. Thank you! forms.py: import re from django import forms from django.utils.translation import gettext_lazy as _ from .models import Students class StudentRegisterForm(forms.ModelForm): class Meta: model = Students fields = [ 'firstName', 'lastName', 'email', 'password', 'password2', 'street', 'apt', 'city', 'state', 'zipcode', ] labels = { 'firstName': _('First Name'), 'lastName': _('Last Name'), 'password2': _('Confirm Password'), 'Apt': _('Apt/House'), 'zipcode': _('Zip Code'), } widgets = { 'password': forms.PasswordInput, 'password2': forms.PasswordInput } help_texts = { 'password': … -
Sorl-Thumbnail : Clear cache of only one image?
Is it possible to clear cache of only one image from a folder. I need to use this command line : python manage.py thumbnail clear_delete_all but on one image and not on all images. Is it possible to give it an image path or name? Thanks ! -
manage.py migrate cannot access remote MySQL database
I have a Django app on that connects to a remote MySQL database (both on AWS, just different servers). The connection works fine and the app properly interacts with the database (fetches from and adds data to it). However, when I am trying to perform a manage.py migrate, I get the following error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Is there something specific to do for manage.py to interact with the remote database instead of trying to hit a local one (that doesn't exist)? -
Django Rest Framework - Use all query params not part of standard filters as postgres JSON field query
I have a Model (call it Thing), it has 4 fields, thing1, thing2, thing3, thing4. I want to filter normally, using query params, against thing1, and thing2, I don't want to filter against thing3, and thing4 is a JSON Field. All query params not thing1 and thing2 should be combined together to form the filter for thing4 (the JSON field). Right now I have the following: models.py from django.contrib.postgres.fields import JSONField class Thing(models.Model): thing1 = models.CharField() thing2 = models.CharField() thing3 = models.CharField() thing4 = JSONField() views.py class ThingViewSet(viewsets.ModelViewSet): queryset = Thing.objects.all() serializer_class = ThingSerializer filter_fields = ('thing1', 'thing2') class Meta: model = Thing fields = '__all__' def filter_queryset(self, *args, **kwargs): query_dict = self.request.GET.dict() thing4_filter_dict = {} for field, value in query_dict.items(): if field in self.filter_fields: continue thing4_filter_dict['thing4__%s' % key] = value return super().filter_queryset(*args, **kwargs).filter(**thing4_filter_dict) you can then call this using, for example GET http://localhost:8000/things/?thing1=some_value&other_thing=1&some_other_thing=2 And here, other_thing=1 and some_other_thing=2 will be used to filter against the JSONField (thing4) Does anyone have any suggestions on a better way to do this? In the django source code the docs for filter_queryset says something like "you probably don't want to override this method". So I'm wondering is there some other better way I … -
What is diff bw declared-services and service in manifest.yml?
In the manifest.yml for a django application deployed on cloud foundry PAAS, i can see there are two labels for services :declared-services and services . I want to know what is the difference and for Oracle database which is the actual service bound? declared-services: oracle_db: label: oracle-ods plan: shared-nr services: - applogger - oracle_ods - odsui-kerberos-sso -
Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried:
I can't seem to spot the error in my code and I have tried everything. It is probably something simple that is escaping my eye. Please help! Any input is appreciated. New Django learner here. template <header class="w3-container w3-blue"> <h1><a href="{% url 'details' Testimony.id %}"</a>{{testimony.Title}} </h1> </header> models.py class Testimony(models.Model): ... def __str__(self): return int(self.id) urls.py urlpatterns = [ ... path('<int:id>/details/', views.detail, name='details'), ] views.py def details(request, id=None): print('1') testimony=get_object_or_404(Testimony, id=id) print('2') return render(request, 'details.html', {'testimony': testimony}) -
Can internal ip addresses of the worker machines be used to connect the worker to rabbitmq queue?
the two machines the "master rabbitmq queue handler" and the "worker machine are servers of same platform (i.e digitalocean)". Can their internal ips be used to connect them? If yes will it be any faster than the external ip connection? -
passing arguments in django
I am implementing a search function in django and I want to use ListView. how do a pass the search string to my function in views.py? here is my view function that I want to modify: class PersonList(ListView): model=Person context_object_name='persons' and here is the template: <form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" method="post">{% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{name}}"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form>r code here -
How to bind multiple models to one ManyToManyField?
There are,for example, such classes: class A(models.Model): id = models.CharField(max_length=256, primary_key=True) mtm = models.ManyToManyField(B, C, D) class B(models.Model): id = models.CharField(max_length=256, primary_key=True) class C(models.Model): id = models.CharField(max_length=256, primary_key=True) class D(models.Model): id = models.CharField(max_length=256, primary_key=True) I know the implementation class of the field And the wrong, did so to make it clearer. You need to have that model And had a relationship ManyToMany with models b,C,D. How can this be done? Is there a special field? -
Dynamic url for list of charts by category issue (queryset filter)
Django 'CategorisedListView' object has no attribute 'slug' or Page not found (error 404) issue I'm on Django 2.0, using generic class list view. I have tried dynamic url based on slug and queryset filter on slug to get list of charts by category. Please help! I've been stuck here for a couple of days since. views.py class CategoriesView(generic.ListView): template_name = 'Bokeh/categories.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() class CategorisedListView(generic.ListView): model = Category template_name = 'categories/list_of_charts_by_category.html' context_object_name = 'categorised' def get_queryset(self): self.category = get_object_or_404(Category, name = self.kwargs['slug']) return Chart.objects.filter(category=self.slug) models.py class Category(models.Model): name = models.CharField(max_length=100) image_file = models.ImageField(default=None, unique=True) slug = models.SlugField(max_length=100, unique=True) parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True, null=True, related_name='children') def __str__(self): return self.name def get_absolute_url(self): return '{slug}/'.format(slug=self.slug) class Meta: ordering = ('name',) verbose_name = 'Category' verbose_name_plural = 'Categories' class Chart(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(max_length=250) url = models.URLField(default=None, blank=True) embed_url = models.TextField(default=None, blank=True) image_file = models.ImageField(default=None, unique=True) code_file = models.FileField(default=None, blank=True, unique=True) chart_library = models.CharField(max_length=250) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) tag = TaggableManager() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name + ' - ' + self.chart_library def get_absolute_url(self): return reverse('Bokeh:detail', kwargs={'pk': self.pk}) def read_file(self): data = self.code_file.path with open(self.code_file.path, 'r', encoding='UTF-8') … -
How to get response of chatterbot in image/hyperlink format?
Not able to get response of ChatterBot as image/hyper link. I tried to place html image tag in my training data set i.e., . Training data set: image_response_data_set.yml categories: - myown conversations: - - can you show me image link? - <img src="example.jpg" alt="Smiley face" height="42" width="42"> As my tag is considering as a string, it won't show me as image. Can any one help me, how can i train bot to give response as image? Do I need to use any other format instead of .yml? Note: I'm doing this using ChatterBot/examples/django_app from github. -
Django: Creating a new Object from an HTML form
I'm happy to join stackoverflow :) This is my problem/question: I am working on Django (pretty newbie... yet), and I'm building a dynamic website (frontend/backend) just for practice. My problem is that I need to make my site able to build a new Model Object, from an user's HTML Form (tempalte), I have been searching on google for days, but I always find the vice-versa answer to my problem (How to create a new form from a model object). Python version: 2.7.15 Django version: 1.11 My model (in models.py): class Orden(models.Model): nombre = models.CharField(max_length=24, blank=True, null=True) email = models.EmailField() mensaje = models.CharField(max_length=1024, blank=True, null=True) My view (in views.py): def products(request): return render(request, "products.html", {}) In my urls.py: urlpatterns = [ url(r'^$', views.inicio, name='inicio'), url(r'^products/$', views.products, name='products'), url(r'^about/$', views.about, name='about'), url(r'^admin/', admin.site.urls), ] And this is my html template from where I'm trying to make users able to create new objects (from a class called Orden, which means Orders) {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <form enctype="multipart/form-data" method="POST">{% csrf_token %}{{ form.as_p }} <div class="col-sm-8 col-sm-offset-2"> </div> <div class="col-sm-4 col-sm-offset-2"> <input value="{{ nombre }}" id="{{ nombre }}" name="{{ nombre }}" type="text" class="form-control" placeholder="Su nombre" … -
Django: Array value must start with "{" or dimension information
I try to add some array like in the example tags = ArrayField(models.CharField(max_length=200),default=list) I get this error: django.db.utils.DataError: malformed array literal: "" DETAIL: Array value must start with "{" or dimension information. using postgresql_psycopg2... -
One form field alone fails to display value from database
My model: class DirectoryDoctors (models.Model): num = models.AutoField(primary_key=True) name = models.CharField(max_length=100) design_choices = ( ('IMO', 'IMO'), ('AIMO', 'AIMO'), ('Dental Surgeon', 'Dental Surgeon'), ('Regional Deputy Director', 'Regional Deputy Director'), ('Joint Director', 'Joint Director'), ('Director', 'Director'), ('unspecified', 'Unspecified') ) designation = models.CharField( choices=design_choices, max_length=30, default='unspecified') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) email = models.CharField(max_length=50, default='', blank=True) dob = models.DateField(null=True, blank=True) specialiast_or_not_choices = ( ('Yes', 'Yes'), ('No', 'No'), ('Unspecified', 'Unspecified') ) specialiast = models.CharField( choices=specialiast_or_not_choices, max_length=30, default='Unspecified') specialty_choices = ( ('Internal Medicine', 'Internal Medicine'), ('General Surgery', 'General Surgery'), ('ENT', 'ENT'), ('Ophthalmology', 'Ophthalmology'), ('Dermatology', 'Dermatology'), ('Paediatrics', 'Paediatrics'), ('Respiratory Medicine', 'Respiratory Medicine'), ('Psychiatry', 'Psychiatry'), ('Obstetrics and Gynaecology', 'Obstetrics and Gynaecology'), ('Physical Medicine', 'Physical Medicine'), ('Radiodiagnosis', 'Radiodiagnosis'), ('Anaesthesia', 'Anaesthesia'), ('Unspecified', 'Unspecified'), ('Not Applicable', 'Not Applicable') ) specialty = models.CharField( choices=specialty_choices, max_length=30, default='Unspecified') institution = models.ForeignKey(DirectoryHospital, on_delete=models.DO_NOTHING) bloodgroup_choices = (('apos', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ('AB+', 'AB+'), ('AB-', 'AB-'), ('-', '-') ) bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=15, blank=True) spousename = models.CharField(max_length=100, blank=True) children = models.CharField(max_length=200, blank=True) present_address = models.CharField(max_length=200, blank=True) permanent_address = models.CharField(max_length=200, blank=True) class Meta: unique_together = ["name", "mobile", "email"] My form: class DirectoryDoctorsForm(ModelForm): class Meta: model = DirectoryDoctors fields = [ 'name', 'designation', 'mobile', 'alternate', 'email', 'dob', … -
Can I search through Serializer fields instead of Model Fields in ListAPIView?
I have a Serializer which has values from OneToMany and ManyToOne Relation. class A(models.Model): abc = AnyField() bcd = AnfField() class B(models.Model): xyz = ForeignKey(A) pqr = CharField() class C(models.Model): lmn = ForeignKey(A) def = CharField() My Serializers are as follows: class BSerializer(ModelSerializer): class Meta: fields = '__all__' class CSerializer(ModelSerializer): class Meta: fields = '__all__' class ASerializer(ModelSerializer): B = SerializerMethodField() C = SerializerMethodField() class Meta: fields = ('id', 'abc', 'bcd', 'B', 'C') def get_B(self, obj): return BSerializer(queryset=obj.b_set.all(), many=True).data def get_C(self, obj): return CSerializer(queryset=obj.c_set.all(), many=True).data Now, In my views: class AListView(ListAPIView): serializer_class = ASerializer queryset = A.objects.all() search_fields = ('id', 'abc', 'bcd', 'B__pqr', 'C__def', ) I want to search in the serializer fields. Is there a way, where I can search in B's fields or 'C's fields. Using search_fields, I can only search in A's fields (abc, bcd). -
How to get saved value in select tag in generic UpdateView?
I'm editing a form a with generic UpdateView, when i open the form i'm unable to get saved value in select tag other fields are working properly. forms.py class EmployeeForm(forms.ModelForm): city = forms.ModelChoiceField(queryset=city_master.objects.all()) state= forms.ModelChoiceField(queryset=state_master.objects.all()) country = forms.ModelChoiceField(queryset=country_master.objects.all()) class Meta: model=employee_master fields = '__all__' widgets= { 'name':forms.TextInput(attrs={'class':'form-control'}), 'for_station': forms.TextInput(attrs={'class': 'form-control'}), 'contact_no': forms.TextInput(attrs={'class': 'form-control'}), 'email_id': forms.TextInput(attrs={'class': 'form-control'}), 'joining_date': forms.TextInput(attrs={'class': 'form-control'}), 'date_of_birth': forms.TextInput(attrs={'class': 'form-control'}), 'address': forms.Textarea(attrs={'class': 'form-control','rows':2, 'cols':10}), 'country': forms.Select(attrs={'class': 'form-control'}), 'state': forms.Select(attrs={'class': 'form-control'}), 'city': forms.Select(attrs={'class': 'form-control'}), 'pin_code': forms.TextInput(attrs={'class': 'form-control'}), 'remarks': forms.Textarea(attrs={'class': 'form-control','rows':2, 'cols':10}), 'active': forms.CheckboxInput(attrs={'class': 'form-check-input'}), } views.py for create and update i am using the same form class EmployeeCreate(CreateView): model = employee_master form_class = EmployeeForm class EmployeeUpdate(UpdateView): model = employee_master form_class = EmployeeForm I expect that country, state and city should appear with saved data when i edit. -
NewConnectionError raise while installing requirements.txt certifi
I try to run docker-compose up to build django app but I got this error message. Building web Step 1/6 : FROM python:2.7 ---> bfa54426aeda Step 2/6 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 52295fd3b228 Step 3/6 : RUN mkdir /deniz1 ---> Using cache ---> dff17bbae4d8 Step 4/6 : WORKDIR /deniz1 ---> Using cache ---> 0f95497fe436 Step 5/6 : ADD . /deniz1/ ---> Using cache ---> 750b3033f58d Step 6/6 : RUN pip install --upgrade -r requirements.txt ---> Running in 0559d5fd6935 Processing ./cve2NVT/PyCVESearch Collecting certifi==2018.4.16 (from -r requirements.txt (line 1)) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070c10>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/certifi/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070450>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/certifi/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070710>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)': /simple/certifi/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7fc254070d50>: Failed to establish a new connection: [Errno -3] Temporary failure in name … -
Proccess data from multiple forms in request.POST
Within my CreateView and UpdateView I am using a form for the main model and multiple forms to directly create/update related models: class MyModelCreateView(CreateView): model = MyModel form_class = MyModelForm MyModelForm instantiates the required forms for the related fields I mentioned within itself. My problem is that when I serialize the data and send it to the view, it doesn't know how to handle the data from the extra forms. When I access to request.POST this data gets discarded. I am serializing the forms like this: let data = $('#main-form').serializeArray(); $('.other-form').each(function() { data.push({name: 'id-' + $(this).data('id'), value: $(this).serializeArray()}); }); This sends the following array to the server (I stringified it here for a clear display): [ { "name": "name", "value": "some name" }, { "name": "id-194", "value": [ { "name": "prop1", "value": "on" }, { "name": "prop2", "value": "some prop" }, { "name": "prop3", "value": "other prop" } ] }, { "name": "id-195", "value": [ { "name": "prop2", "value": "some prop" }, { "name": "prop3", "value": "other prop" } ] } ] However the contents of request.POST are these: <QueryDict: {u'name': [u'some name']}> Notice how all other data is ignored. I can get to send it to the server the … -
Setting local variables in a django model
I have the following model: class MeasurementParameter(models.Model): tolerance = models.FloatField() set_value = models.FloatField() tol_low = None tol_high = None def tolerance_band(self): tol = self.set_value * self.tolerance/100 self.tol_high = self.set_value + tol self.tol_low = self.set_value - tol print self.tol_low return self.tol_high, self.tol_low I wish to set the calculated local variables tol_low and tol_high using the tolerance_band method. The model is has a ManyToMany relationship with another model called Product. class Product(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) parameters = models.ManyToManyField(MeasurementParameter, related_name='measurement') def calc_all_tol_bands(self): for parameter in self.parameters.all(): hi, lo = parameter.tolerance_band() def __str__(self): return self.name So in my view I attempt to calculate all tolerance bands by: product.calc_all_tol_bands() However if I try and get the local variables: product.parameters.all()[0].tol_low I get None all the time. What do I need to do to be able to set calculated values in the MeasurementParameter model? John.