I try to fill empty fields when I save model form, but unfortunately, it doesn't work properly.
this is my view:
def bylaw_save(request):
form = BylawForm(initial={'who_created': request.user.username})
if request.method == 'POST':
form = BylawForm(request.POST)
if form.is_valid():
gdn = GlobalDocNumber.objects.get(pk=1)
gdn.gdn += 1
gdn.save()
raspr_num = form.cleaned_data['raspr_num'][:]
raspr_num = raspr_num.split('/')
bylaw = form.save(commit=False)
bylaw.district = 'unfilled'
bylaw.department = 'unfilled'
bylaw.performer = 'unfilled'
bylaw.check_type = 'unfilled'
bylaw.save()
return bylaw_form(request, msg='test')
else:
return bylaw_form(request, msg='test')
return render(request, 'bylaw/bylaw_form.html', {'form': form})
this is fraction of my form:
district = ModelChoiceField(required=False, queryset=DistrictsMenu.objects.all(), to_field_name="district",
widget=Select(attrs={'id': "district", 'class': 'form-control col-6'}))
department = ModelChoiceField(required=False, queryset=DepartmentsMenu.objects.all(), to_field_name="department",
widget=Select(attrs={'id':"department", 'class': "form-control col-6"}))
UPDATE: This is my model with default='Unfilled', according to Arthur M and Rohan suggestions (But it also doesn't work, it gives me a "NOT NULL constraint failed: bylaw_bylawmodel.department" error, in this case I don't fill department field):
class BylawModel(models.Model):
raspr_date = models.DateField()
district = models.CharField(max_length=255, default='Unfilled')
department = models.CharField(max_length=255, default='Unfilled')
organization = models.CharField(max_length=255, default='Unfilled')
inn = models.IntegerField()
performer = models.CharField(max_length=255, default='Unfilled')
check_type = models.CharField(max_length=255)
date_proved = models.DateField()
raspr_num = models.CharField(max_length=255, unique=True)
who_created = models.CharField(max_length=255)
when I save this from, it always fills with 'unfilled'. How can I fill empty values only if they are really empty?
By doing
bylaw.fieldName = 'unfilled' you're overwriting the value sent from your form.
If you don't want to add a default value in your model (which I would recommend) you can add a simple :
if not bylaw.fieldName:
bylaw.fieldName = 'unfilled'
For every one of your fields.
Related
Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.
I am trying to save form data into a postgres table 'Student_Events' that is linked via foreign key to the 'Student_INFO table' but keep on receiving an integrity error:
'insert or update on table "entry_student_event" violates foreign key constraint "entry_student_event_nsn_id_2499e7fd_fk_entry_student_info_id"
DETAIL: Key (nsn_id)=(123556789) is not present in table "entry_student_info".'
There is one student in Student_INFO that has the nsn '123556789' so I am unsure to why it "is not present" in that table. Any help would be greatly appreciated as I am quite new to Django and PostgresSQL,
thanks
Views.py:
def Grouplist(request):
student_list = Student_INFO.objects.order_by('name')
for student in student_list:
if request.method == 'POST':
form = EntryForm(request.POST)
context = {
'student_list':student_list,
'form': form
}
if form.is_valid():
event_save = form.save(commit=False)
event_save.nsn_id = student.nsn
event_save.save()
return redirect('grouplist')
else:
form = EntryForm()
context = {
'student_list':student_list,
'form': form
}
return render(request, 'grouplist.html', context)
Models.py:
class Student_INFO(models.Model):
nsn = models.IntegerField(blank = False)
birthdate = models.DateField("BirthDate", blank = False)
name = models.CharField(max_length=30, blank = False)
age_catagory = models.CharField(max_length=8, blank = True, default = '')
grouproom = models.CharField(max_length=3, blank = False)
year_lvl = models.IntegerField(blank = False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Student_Event(models.Model):
nsn = models.ForeignKey(Student_INFO, on_delete=models.CASCADE)
event1 = models.CharField(max_length=15, blank=False, default = '')
event2 = models.CharField(max_length=15, blank=False, default = '')
event3 = models.CharField(max_length=15, blank=False, default = '')
event4 = models.CharField(max_length=15, blank=False, default = '')
event5 = models.CharField(max_length=15, blank=False, default = '')
event6 = models.CharField(max_length=15, blank=False, default = '')
def __str__(self):
return self.nsn
Forms.py
class EntryForm(forms.ModelForm):
class Meta:
model= Student_Event
fields= ["event1", "event2", "event3", "event4", "event5", "event6"]
widgets = {
'event1':forms.Select(choices=EVENT_CHOICES),
'event2':forms.Select(choices=EVENT_CHOICES),
'event3':forms.Select(choices=EVENT_CHOICES),
'event4':forms.Select(choices=EVENT_CHOICES),
'event5':forms.Select(choices=EVENT_CHOICES),
'event6':forms.Select(choices=OPEN_CHOICES),
}
Returns the error:
insert or update on table "entry_student_event" violates foreign key constraint "entry_student_event_nsn_id_2499e7fd_fk_entry_student_info_id"
DETAIL: Key (nsn_id)=(123556789) is not present in table "entry_student_info".
Thank you #BearBrown for solving it! student.nsn should be student.pk.
Good days guys need help for my ForeignKey Relationship in my models,
i want my foreignkey values is equal to the user choose
Here's my model view
class ProjectNameInviToBid(models.Model):
ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True)
DateCreated = models.DateField(auto_now=True)
def __str__(self):
return self.ProjectName
have relations to ProjectNameInviToBid
class InviToBid(models.Model):
today = date.today()
ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE, null=True)
NameOfFile = models.CharField(max_length=255, verbose_name='Name of File')
Contract_No = models.IntegerField(verbose_name='Contract No')
Bid_Opening = models.CharField(max_length=255, verbose_name='Bid Opening')
Pre_Bid_Conference = models.CharField(max_length=255, verbose_name='Pre Bid Conference')
Non_Refundable_Bidder_Fee = models.CharField(max_length=255, verbose_name='Non Refundable Fee')
Delivery_Period = models.CharField(max_length=255, verbose_name='Delivery Period')
Pdf_fileinvi = models.FileField(max_length=255, upload_to='upload/invitoBid', verbose_name='Upload Pdf File Here')
Date_Upload = models.DateField(auto_now=True)
This is my form view
class invitoBidForm(ModelForm):
class Meta:
model = InviToBid
fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening',
'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee',
'Delivery_Period',
'Pdf_fileinvi')
and Lastly this my view Forms
def project_name_details(request, sid):
majordetails = ProjectNameInviToBid.objects.get(id=sid)
if request.method == 'POST':
form = invitoBidForm(request.POST, request.FILES)
if form.is_valid():
majordetails = form.ProjectName
form.save()
messages.success(request, 'File has been Uploaded')
else:
form = invitoBidForm()
args = {
'majordetails': majordetails,
'form': form
}
return render(request,'content/invitoBid/bacadmininvitoBid.html', args)
but im have a error,, hope you can help me. thank you in advance
In models.py:
class Client(AbstractBaseUser):
username = models.CharField(max_length=32, unique=True)
email = models.EmailField('email address', unique=True, db_index=True)
avatar = models.ImageField('avatar', upload_to='avatars')
id = id(object)
class Order(models.Model):
class Meta():
db_table = 'order'
short_desc = models.CharField(max_length=30)
subject = models.ForeignKey(Subject, blank=True)
user_id = models.ForeignKey('Client', to_field='id', related_name='client_id', default='0', blank=True)
performer_id = models.ForeignKey('Client', to_field='id', related_name='performer_id', default='0', blank=True)
worktype = models.ForeignKey(Type, blank=True)
level = models.IntegerField(default=0, blank=True)
readiness = models.BooleanField(default=False, blank=True)
description = models.TextField(max_length=2000, blank=True)
file = models.FileField(upload_to='orderfiles', blank=True)
#maxdate = models.DateField(blank=True)
addate = models.DateField(auto_now=True, blank=True)
price = models.IntegerField(max_length=10, blank=True)
responses = models.IntegerField(blank=True)
In forms.py:
class AddOrderForm(forms.ModelForm):
short_desc = forms.CharField(widget=forms.TextInput,label="Краткое описание(послужит именем)")
subject = forms.ModelChoiceField(queryset=Subject.objects.all(), label="Предмет")
worktype = forms.ModelChoiceField(queryset=Type.objects.all(), label="Тип")
level = forms.IntegerField(widget=forms.TextInput,label="Уровень сложности (от 1 до 5)")
description = forms.CharField(widget=forms.TextInput,label="Полное описание")
#maxdate = forms.DateField(widget=forms.TextInput,label="maxdate")
price = forms.IntegerField(widget=forms.TextInput,label="Ваша цена")
responses = forms.IntegerField(widget=forms.TextInput,label="Кол-во ответов на заказ")
class Meta:
model = Order
fields = ['short_desc', 'level', 'description', 'price', 'responses', 'subject', 'worktype']
In views.py:
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html', { 'form': form,'username' : auth1}, context_instance=RequestContext(request))
I need the field user_id in class Order to be initialized immediately after adding order(). Where should I do it and in which way? I need something like this logic: Client adds an Order through AddOrderForm and then user_id field of just added object of class Order has to be initialized with an object of class Client, whose id equals user_id in parameters of addorder() function.
You can do that using commit=False while saving the form. This is typical way of saving the object using model form which has fewer fields.
def addorder(request, user_id):
"""
Adding Order view
"""
if request.POST:
form = AddOrderForm(request.POST)
if form.is_valid():
order = form.save(commit=false)
order.client_id = Client.objects.get(id=user_id)
order.save()
return redirect('/')
else:
return redirect('/')
auth1 = auth.get_user(request).username
return render_to_response('customer.html',
{ 'form': form,'username' : auth1},
context_instance=RequestContext(request))
Disclaimer: Handle errors e.g. Client.objects.get() may fail. Use appropriate fields to search.
this is my model :
class Member(models.Model):
profile = models.OneToOneField(Profile, editable=False, null=True)
title = models.CharField(max_length=4, choices=TITLE_TYPES, null=True)
name = models.CharField(max_length=100, null=True, verbose_name='Name')
lastname = models.CharField(max_length=100, null=True, verbose_name='LastName')
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, verbose_name='Gender')
dob = models.DateField('dob')
redressno = models.CharField(max_length=100, null=True, verbose_name='RedressNo')
this is my form
class MemberForm(ModelForm):
dob = forms.DateField(required=False, input_formats=('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y'))
class Meta:
model = Member
exclude = ('profile',)
this is my view :
members = Member.objects.filter(profile=profiles)
data1 = serializers.serialize( "python", members)
print data1[0]['fields']
memarr=[]
for index, a in enumerate(data1):
memarr.append(a['fields'])
print memarr
MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet)
member_formset = MemberFormSet(initial=memarr)
#here setting intial array of mem
mdata['form-TOTAL_FORMS']=u'2'
mdata['form-INITIAL_FORMS']=u'0'
mdata['form-MAX_NUM_FORMS']=u''
member_formset = MemberFormSet(mdata)
memberform = MemberForm(mdata)
c = {'form': form, 'memberform': memberform, 'member_formset': member_formset}
c.update(csrf(request))
return render_to_response('edit_profile.html', c, RequestContext(request))
m passing the initial data but still the initial data is not being shown in the form?
Here's your problem:
member_formset = MemberFormSet(initial=memarr)
...
member_formset = MemberFormSet(mdata)
You're setting the initial data on one FormSet instance, and then throwing away that instance with the initial data and overwriting with another new FormSet instance.
You can simplify your view to this:
# If you are not using csrf middleware, use this decorator instead of ghetto magic
#csrf_protect
#render_to('edit_profile.html') # handy decorator from django-annoying
def profile_members_edit(request.profile):
members = Member.objects.filter(profile=profiles)
# iterate over the ValuesQuerySet gives a list of dicts for initial data
member_data = list(members.values())
# setting extra=<> and max_num=<> is easier than setting internal form data
MemberFormSet = formset_factory(MemberForm, formset=BaseFormSet, extra=2)
member_formset = MemberFormSet(initial=member_data)
return {'member_formset': member_formset }