Set field form value from view - django

How to add field value manually from view?
model.py
class Connect(models.Model):
username = models.CharField(max_length=255)
password = models.CharField(max_length=255,null=True, blank=True)
conft = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.username)
form.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
conft = forms.Textarea()
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
view.py
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
i want to set "conft" value manually, maybe like
configuration = "some config"
conft = configuration
i already tried
configuration = "some config"
NacmForm(initial={'conft': configuration })
or
formm.fields['conft'].initial = configuration
or
formm = NacmForm(request.POST, initial={"conft": configuration })
when i use that code above, the value isnt save to database, then i tried this
Connect.objects.create(conft=configuration)
its save to database but not in same row

formm.cleaned_data returns dictionary. So, you can add/update/remove keys manually. initial={} This is for rendering purposes (Which adds in html forms initial values value="something"). As far as i understand you want to modify incoming data when HTTP POST is made. Try like this.
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
# If both form is valid
formm.cleaned_data['conft'] = '<new_value>' # + this is added logic
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
forms.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
# conft = forms.Textarea()
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
Hope, it helps you.

so after googling, i just add this line
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
# If both form is valid
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanForm.conft = "ip route configuration" # i add this
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//

Related

Django: how to modify form field order of bound form with one unbound field?

I have an update form with 4 fields to display
3 of them are related to a class to which the form is bound
the last field (country) is only for information and I would like that field to be display in first position
currently, it is displayed at the end of my form...
I tryed to use field_order but country field is ignored...
form.py
class ParametrageForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
super(ParametrageForm, self).__init__(*args, **kwargs)
self.request = request
self.language = request.session.get('language')
self.user = request.user.id # id de l'utilisateur
self.user_pays = request.session.get('user_pays') # pays de l'utilisateur
self.user_site_type = request.session.get('user_site_type')
self.user_site = request.session.get('user_site')
instance = Parametrage.objects.get(asp_par_cle = kwargs['instance'].asp_par_cle)
SITE_CONCERNE = Site.option_list_sites(self.language)
if self.language == 'en':
country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng
elif self.language == 'fr':
country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_fra
else:
country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng
self.fields["country"] = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True)
self.fields["asp_par_loc"] = forms.ChoiceField(label = _("Site concerned by settings"), widget=forms.Select, choices=SITE_CONCERNE,)
self.fields["asp_par_ale"] = forms.IntegerField(label = _("Stock alert value for this site"), widget=forms.TextInput,)
self.fields["asp_par_con"] = forms.IntegerField(label = _("Stock confort value for this site"), widget=forms.TextInput,)
class Meta:
model = Parametrage
fields = ('asp_par_loc','asp_par_ale','asp_par_con',)
field_order = ['country','asp_par_loc','asp_par_ale','asp_par_con',]
Replace
self.fields["country"] = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True)
with
country = forms.CharField(label = _("Country"),widget=forms.TextInput,initial=country, disabled=True)
I found how to solve my issue:
I defined 'country' field outside of the init
and then filed_order works
but doing that, I do not have access to my initial country value, set in init (country= Site.objects.get(sit_abr = instance.asp_par_loc).reg.pay.pay_nom_eng)
I must improve my Python understanding...

How to update specific model fields using Django UpdateView

How can you update certain model fields when a form is posted using Django's UpdateView?
When the user checks complete = True on the form, and submits it, I want their name and date to be saved to this record (fields not visible on the form). The code below isn't throwing any errors, but it also isn't updating the fields requested.
Is it potentially because the view is already updating this record with the form, so they conflict?
view:
class maintenanceEdit(LoginRequiredMixin,UpdateView,):
model = Maintenance
form_class = EditMaintenance
template_name = 'maintenance_edit.html'
login_url = 'login'
success_url = reverse_lazy('equipmentdashboard')
def form_valid(self, form,):
instance = form.save(commit=False)
instance.user = self.request.user
user = instance.user.first_name +" "+instance.user.last_name
completed = form.instance.completed
dateCompleted = form.instance.dateCompleted
if (dateCompleted is None):
if completed == True:
updateMaintenance = Maintenance.objects.get(id = instance.id)
updateMaintenance.dateCompleted = timezone.now()
updateMaintenance.completedBy = user
updateMaintenance.save(update_fields=['dateCompleted','completedBy',])
return super(maintenanceEdit, self).form_valid(form)
model:
class Maintenance(models.Model):
device = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,)
customerTag = models.CharField(max_length=50,)
maintenanceItem = models.CharField(max_length=35,blank=True,)
maintenanceDescrip = models.TextField(max_length=300,blank=True,)
maintenanceNotes = models.TextField(max_length=300,blank=True,)
dateCreated = models.DateTimeField(auto_now_add=True,)
dateDue = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True)
dateCompleted = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True)
completed = models.BooleanField(default = False)
createdBy = models.CharField(max_length=35,blank=True,)
completedBy = models.CharField(max_length=35,blank=True,)
form:
class EditMaintenance(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(EditMaintenance, self).__init__(*args, **kwargs)
self.fields['maintenanceItem'].required = True
self.fields['dateDue'].required = True
class Meta:
model = Maintenance
fields = ['maintenanceItem','dateDue','maintenanceDescrip',
'maintenanceNotes','completed',]
labels = {
'maintenanceItem': ('Maintenance Item'),
'dateDue': ('Maintenance Due'),
'maintenanceDescrip': ('Maintenance Description'),
'maintenanceNotes': ('Maintenance Notes'),
'completed': ('Complete Maintenance'),
}
I also tried, in my view:
def form_valid(self, form,):
instance = form.save(commit=False)
instance.user = self.request.user
user = instance.user.first_name +" "+instance.user.last_name
completed = form.instance.completed
dateCompleted = form.instance.dateCompleted
if (dateCompleted is None):
if completed == True:
Maintenance.objects.filter(id = instance.id).update(dateCompleted = timezone.now(),completedBy = user)
return super(maintenanceEdit, self).form_valid(form)

Matching query doesn't exist?

I am making a retweet function and it works quite smooth but I am not able to retweet my own tweets , I am able to retweet other users tweets but not mine
. It shows that matching query doesn't exist.
Here is the tweets models
class TweetManager(models.Manager):
def retweet(self,user,parent_obj):
if parent_obj.parent:
obj_parent = parent_obj.parent
else:
obj_parent = parent_obj
qs = self.get_queryset().filter(user = user, parent = obj_parent)
if qs.exists():
return None
obj = self.model(
user = user,
parent = obj_parent,
content = parent_obj.content
)
obj.save()
return obj
class Tweet(models.Model):
parent = models.ForeignKey("self",blank = True,null = True)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
content = models.CharField(max_length = 130)
time = models.DateTimeField(auto_now_add = True)
objects = TweetManager()
def __str__(self):
return self.content
class Meta:
ordering = ['content']
Here's the views.py
class Retweet(View):
def get(self, request, pk, *args, **kwargs):
tweet = get_object_or_404(Tweet, pk=pk)
if request.user.is_authenticated:
new_tweet = Tweet.objects.retweet(request.user, tweet)
return HttpResponseRedirect("/")
return HttpResponseRedirect(tweet.get_absolute_url())

django-select2 not working with inlines in django-admin

Here are my models and admin classes:
---------------------Models-----------------------
from django.contrib.auth.models import User
class PurchaseOrder(models.Model):
buyer = models.ForeignKey(User)
is_debit = models.BooleanField(default = False)
delivery_address = models.ForeignKey('useraccounts.Address')
organisation = models.ForeignKey('useraccounts.AdminOrganisations')
date_time = models.DateTimeField(auto_now_add=True)
total_discount = models.IntegerField()
tds = models.IntegerField()
mode_of_payment = models.ForeignKey(ModeOfPayment)
is_active = models.BooleanField(default = True)
class Meta:
verbose_name_plural = "Purchase Orders"
def __unicode__(self):
return '%s' % (self.id)
----------------------------------Admin----------------------------------------
"""
This class is used to add, edit or delete the details of item purchased
"""
class PurchasedItemInline(admin.StackedInline):
form = ItemSelectForm
model = PurchasedItem
fields = ['parent_category', 'sub_category', 'item', 'qty', ]
extra = 10
class BuyerChoices(AutoModelSelect2Field):
queryset = User.objects.all()
search_fields = ['username__icontains', ]
class BuyerForm(ModelForm):
user_verbose_name = 'Buyer'
buyer = BuyerChoices(
label='Buyer',
widget=AutoHeavySelect2Widget(
select2_options={
'width': '220px',
'placeholder': 'Lookup %s ...' % user_verbose_name
}
)
)
class Meta:
model = PurchaseOrder
fields = '__all__'
"""
This class is used to add, edit or delete the details of items
purchased but buyer has not confirmed the items purchased, this class
inherits the fields of PurchaseOrder derscribing the delivery address of
buyer , is_debit , total discount , tds and mode of payment
"""
class PurchaseOrderAdmin(admin.ModelAdmin):
form = BuyerForm
#list_display = ['id','buyer','delivery_address','date_time','is_active']
inlines = [PurchasedItemInline]
# model = PurchaseOrder
#actions = [mark_active, mark_inactive]
#list_filter = ['date_time']
#search_fields = ['id']
list_per_page = 20
def response_add(self, request, obj, post_url_continue=None):
request.session['old_post'] = request.POST
request.session['purchase_order_id'] = obj.id
return HttpResponseRedirect('/suspense/add_distance/')
I am trying to implement django-select2, but when I use inlines in
PurchaseOrderAdmin it doesn't show the field where I have implemented
django-select2:
But when I remove inlines, it works fine:
Edit
Here is the ItemSelectForm
class ItemSelectForm(forms.ModelForm):
class Media:
js = (
'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
'js/ajax.js',
)
try:
parent_category = forms.ModelChoiceField(queryset=Category.objects.\
filter(parent__parent__isnull=True).filter(parent__isnull=False))
sub_category_id = Category.objects.values_list('id',flat=True)
sub_category_name = Category.objects.values_list('name',flat=True)
sub_category_choices = [('', '--------')] + [(id, name) for id, name in
itertools.izip(sub_category_id, sub_category_name)]
sub_category = forms.ChoiceField(sub_category_choices)
except:
pass
item = forms.ModelChoiceField(queryset = Product.objects.all())
def __init__(self, *args, **kwargs):
super(ItemSelectForm, self).__init__(*args, **kwargs)
self.fields['parent_category'].widget.attrs={'class': 'parent_category'}
self.fields['sub_category'].widget.attrs={'class': 'sub_category'}
self.fields['item'].widget.attrs={'class': 'item'}
It worked for me by adding the following line in the static/suit/js/suit.js
Add:
(function ($) {
Suit.after_inline.register('init_select2', function(inline_prefix, row){
$(row).find('select').select2();
});

Django ModelForm returning a database error on excluded fields

Here is models.py:
class User(TimeStampedModel):
id = models.AutoField(primary_key=True)
class Shoe(models.Model):
size = models.IntegerField(help_text="The shoe\'s size", choices=sizeChoices)
user = models.ForeignKey('User', related_name='shoes')
brand = models.ForeignKey('Brand', related_name='shoes')
class Brand(models.Model):
name = models.CharField(max_length=64, choices = brandChoices)
class ShoeForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ShoeForm, self).__init__(*args, **kwargs)
self.fields['brand'].required = True
self.fields['size'].required = True
class Meta:
model = Shoe
fields = ['brand', 'size']
exclude = ['user']
views.py:
def index(request):
ShoeFormSet = modelformset_factory(Shoe, form=ShoeForm, extra=3)
NewShoeFormSet = modelformset_factory(Shoe, form=NewShoeForm)
if request.method == 'POST':
shoe_formset = ShoeFormSet(request.POST, request.FILES, prefix='shoes')
new_shoe_formset = NewShoeFormSet(request.POST, request.FILES, prefix='new_shoes')
if shoe_formset.is_valid() and new_shoe_formset.is_valid():
#do something with the cleaned data
else:
shoe_formset = ShoeFormSet(prefix='shoes')
new_shoe_formset = NewShoeFormSet(prefix='new_shoes')
return render(request, 'shoes/input_shoes.html', {
'shoe_formset': shoe_formset,
'new_shoe_formset': new_shoe_formset,
})
But I get this error: DatabaseError: no such column: shoes_shoe.user_id, which occurs on the line shoe_formset = ShoeFormSet(prefix='shoes') when the form renders. What's going wrong?