I have the following form:
class locationForm(forms.Form):
existing_regions= forms.ModelChoiceField(queryset=Region.objects.none(), label="Region Name", required=False)
region_name = forms.CharField()
location_name = forms.CharField()
street_address = forms.CharField()
city = forms.CharField()
zip_code = forms.CharField()
And the following update view for this form:
class UpdateLocation(View):
template_name = "dash/location_update_form.html"
def get(self, request, *args, **kwargs):
loc = kwargs['name']
try:
location = Location.objects.get(name=loc)
form = locationForm(instance=location)
return render(request, self.template_name, {'form': form,'location': location})
except (ValueError, ObjectDoesNotExist):
return redirect(reverse('geofence_manager'))
def post(self, request, *args, **kwargs):
loc = self.kwargs['name']
try:
location = Location.objects.get(name=loc)
form = locationForm (request.POST, instance=location)
if form.is_valid():
form.save()
else:
form = locationForm(request.POST, instance=location)
return render(request, self.template_name, {'location': location, 'form': form})
except (ValueError, ObjextDoesNotExist):
return redirect(reverse('location_manager'))
return redirect(reverse('location_manager'))
I am receiving an error in regards to 'instance' key word argument being used. I believe this has something to do with me not using a Modelform(I could be wrong). But I do not want to use a Modelform to construct my form, so is there a way I can get around this?
class locationForm(ModelForm):
class Meta:
model = Location
fields = '__all__'
in your view:
...
locationForm.base_fields['existing_regions'] = forms.ModelChoiceField(queryset= ...)
form = locationForm()
Related
How can I write a url for a form using TemplateView. I wrote a method to validate and pass the company details through form. Using that form object that I'm trying to access the HTML fields.
Form.py
class CompanyDetailsForm(forms.Form):
class meta:
fields = ['company_name','contact_person','employee_count','email','mobile_number']
widgets = {
'comment':Textarea(attrs={'cols':30,'rows':5}),
}
company_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'company Name'}))
contact_person = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Contact Person'}))
email = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Email'}))
employee_count = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Number Of Employee'}))
mobile_number = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'placeholder':'Mobile Number'}))
View.py
class GetCompanyView(TemplateView):
template_name = "astra/company_details.html"
form = CompanyDetailsForm()
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['form']=self.form
return context
def company_details(request):
if request.method =="POST":
form = CompanyDetailsForm(request.POST)
if form.is_valid():
company_name = form.cleaned_data['company_name']
contact_person = form.cleaned_data['contact_person']
email = form.cleaned_data['email']
employee_count = form.cleaned_data['employee_count']
mobile_number = form.cleaned_data['mobile_number']
try:
form.save()
send_mail(company_name,contact_person,email,employee_count,mobile_number,['salesastra500#gmail.com'])
except BadHeaderError:
return BadHeaderError
return render(request,'astra/company_details.html',{'form':form})
else:
return render(request,'astra/company_details.html')
I want to run my company_details.html file using TemplateView. I'm not able to write the url for same. Plz suggest
TemplateView only have get method
def get(self, request, *args, **kwargs):
return render(request,self.template_name, {'form': self.form})
if you have get and post methods use FormView
I got a tracking model, and an evidence model wit ha foreign to it. Im trying to upload a file in evidence related to that tracking...but when i try to save i got this error:
Request Method: POST
Request URL: http://127.0.0.1:8000/myapp/change_actions/tracking/create/1/
Django Version: 1.10.1
Exception Type: RelatedObjectDoesNotExist
Exception Value:
Evidence has no tracking.
My view saves tracking form and then passes the id of that record to the evidence form as foreign.....but that error is like the form was eliminating the tracking field !!....these are my files :
Models.py
class Tracking(ModelBase):
activity = models.ForeignKey(
Activity,
verbose_name = 'Actividad', null = False)
code = models.CharField('Codigo de seguimiento', max_length=50)
observation = models.TextField('Avance a la fecha', max_length=2000)
tracking_date = models.DateTimeField('Fecha de seguimiento')
def __str__(self):
return self.observation
class Evidence(ModelBase):
tracking = models.ForeignKey(
Tracking,
related_name = 'Tracking_evidence',
verbose_name = 'Seguimiento', null = False)
evidence = models.FileField(verbose_name = 'Evidencia', null = True, upload_to='documents/')
This is the form.py:
class EvidenceForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.tracking = kwargs.pop('tracking')
super(EvidenceForm, self).__init__(*args, **kwargs)
def clean(self, *args, **kwargs):
cleaned_data = super(EvidenceForm, self).clean()
self.instance.tracking.id = self.tracking
class Meta:
model = Evidence
fields = ['tracking', 'evidence']
And the view to it :
class TrackingCreateView(View):
template_name = ['change_actions/tracking_create.html']
breadcrumb = [{'name': 'Registro de seguimiento', 'url': None}]
#method_decorator(login_required)
def get(self, request, *args, **kwargs):
form = TrackingForm()
form_evidence = EvidenceForm(tracking = None)
activity = Activity.objects.get(pk = kwargs['activity_id'])
return render(request, self.template_name,{
'form_tracking': form,'breadcrumb': self.breadcrumb,
'activity': activity,'form_evidence': form_evidence})
def post(self, request, *args, **kwargs):
form = TrackingForm(request.POST)
activity = Activity.objects.get(pk = request.POST['activity_id'])
self.breadcrumb[0]['url'] = reverse(
'change_actions:tracking_create',
kwargs = {'activity_id': activity.id })
context = {
'breadcrumb': self.breadcrumb, 'activity': activity,
'form_tracking': form}
if form.is_valid():
form.save()
form_evidence = EvidenceForm(
request.POST, request.FILES, tracking = form.instance.id)
if form_evidence.is_valid():
form_evidence.save()
messages.success(request, 'Seguimiento registrado correctamente')
return HttpResponseRedirect(reverse(
'change_actions:activity_detail',
kwargs = {'activity_id': activity.id }))
else:
context.update({'form_evidence': form_evidence})
return render(request, self.template_name, context)
else:
context['form_tracking'] = form
return render(request, self.template_name, context)
Any idea why I am getting this error? Thanks in advance!
i am using django formset to save multiple form at a time.but data is not saving in my database.I am using class based views.This is the model where i want to save my data.
Model
class Period(AbstractBaseModel):
validators = [ScreenMethodValidator, ChainIntegrityValidator]
chain = models.ForeignKey(
'customers.Chain',
help_text=_('chain to which period belongs to'),
verbose_name=_('chain')
)
start_date = models.DateTimeField(
default=datetime.datetime.now,
help_text=_('Starting date of a period'),
verbose_name=_('start date')
)
end_date = models.DateTimeField(
default=datetime.datetime(1970, 01, 01),
help_text=_('Ending date of a period'),
verbose_name=_('end date')
)
year = models.IntegerField(
default=0,
help_text=_('Financial year'),
verbose_name=_('year'),
null=True,blank=True
)
description = models.TextField(
help_text=_('Description of a period'),
verbose_name=_('description'),
null=True,blank=True
)
class Meta:
app_label = 'accounting'
and View
class PeriodCreate(RequestPassingFormViewMixin, WammuCreateView):
model = Chain
template_name = 'dashboard/period_form.html'
form_class = ChainForm
def get_object(self):
chain = Chain.objects.get(pk=self.kwargs['chain_pk'])
return chain
def get_success_url(self):
return reverse('dashboard_period_list', kwargs={'chain_pk': self.object.chain.id, })
def get_context_data(self, **kwargs):
context = super(PeriodCreate, self).get_context_data(**kwargs)
return context
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(PeriodCreate, self).get_form_kwargs(*args, **kwargs)
chain = get_object_or_404(Chain, pk=self.kwargs['chain_pk'])
period = Period(chain=chain)
kwargs['instance'] = period
return kwargs
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
PeriodInlineFormSet = inlineformset_factory(Chain, Period,
form=PeriodInlineForm,
can_delete=True,
extra=12)
PeriodInlineFormSet.form = staticmethod(curry(PeriodInlineForm, request=request, chain=self.object))
period_formset = PeriodInlineFormSet()
return self.render_to_response(
self.get_context_data(form=form,
period_inline_formset=period_formset))
def post(self, request, *args, **kwargs):
self.object = Chain()
form = self.get_form(self.form_class)
PeriodInlineFormSet = inlineformset_factory(Chain, Period,
form=PeriodInlineForm,
can_delete=True,
extra=12)
PeriodInlineFormSet.form = staticmethod(curry(PeriodInlineForm))
if form.is_valid():
self.object = form.save(commit=False)
period_formset = PeriodInlineFormSet(request.POST, instance=self.object)
if period_formset.is_valid():
self.object.save()
period_formset.save()
return super(PeriodCreate, self).form_valid(form)
else:
return self.render_to_response(
context=self.get_context_data(form=form, period_inline_formset=period_formset))
else:
period_formset = PeriodInlineFormSet(request.POST,instance=self.object)
return self.render_to_response(
context=self.get_context_data(form=form, period_inline_formset=period_formset))
and use the following link to see my other code related to this issue where i have tried to use django formset and faced an argument error which has been solved
but now data is not saving in data base when i am trying to post data.surely the error is occurring in my post method,but as i am not used to work with django formset,i can't figure it out after a long findings.
django __init__ method causing argument error
I am trying to show logged in users a form where they can input name and sensitivity, however this needs to be associated with the logged in user (currently attempting this with the foreign key and init). This is my approach:
Views:
#login_required
def restricted(request):
context = RequestContext(request)
if request.method == 'POST':
form = TrackForm(request.user, request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print form.errors
else:
form = TrackForm()
return render_to_response('tracker/restricted.html', {'form': form}, context)
Forms:
class TrackForm(forms.ModelForm):
name = forms.CharField(help_text="Please enter a name")
sensitivity = forms.IntegerField(help_text="Sensitivity: 1=Low Sensitivity, 2=Standard Sensitivity, 3=Highly Sensitive", initial=0)
def __init__(self, user, *args, **kwargs):
self.user = user
super(TrackForm, self).__init__(*args, **kwargs)
class Meta:
model = ToTrack
fields = ('name','sensitivity')
Models:
class ToTrack(models.Model):
name = models.CharField(max_length=128)
sensitivity = models.IntegerField(default=0)
user = models.ForeignKey(User)
def __unicode__(self):
return self.name
I currently get the error message:
TypeError at /tracker/restricted/
__init__() takes at least 2 arguments (1 given)
change views.py like this(I comment changed line):
#login_required
def restricted(request):
context = RequestContext(request)
if request.method == 'POST':
form = TrackForm(request.POST, user=request.user) #this line change
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print form.errors
else:
form = TrackForm(user=request.user) #this line change
return render_to_response('tracker/restricted.html', {'form': form}, context)
And change form like this:
class TrackForm(forms.ModelForm):
name = forms.CharField(help_text="Please enter a name")
sensitivity = forms.IntegerField(help_text="Sensitivity: 1=Low Sensitivity, 2=Standard Sensitivity, 3=Highly Sensitive", initial=0)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
if user:
self.user = user
super(TrackForm, self).__init__(*args, **kwargs)
class Meta:
model = ToTrack
fields = ('name','sensitivity')
i m not working with the admin.py
is there any way i could have the foreign key field instead of a drop down select box , a dynamic search box(suggestive for the user) like we have raw_id_fields in admin.py.
models.py
class model2(models.Model)
reg = models.ForeignKey(model1, db_column='reg')
class Meta:
db_table = u'table2'
forms.py
class model2Form(ModelFOrm)
def __init__(self, *args, **kwargs):
super(model2Form, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.id:
self.fields['reg'].required = False
self.fields['reg'].widget.attrs['disabled'] = 'disabled'
def clean_regid(self):
if self.instance and self.instance.pk:
return self.instance.reg
else:
return self.cleaned_data['reg']
class Meta:
model = model2
exclude = ('id')
views.py
def add(request):
if request.method == 'POST': # If the form has been submitted...
form = model2Form(request.POST)
if form.is_valid():
form.save()
return list(request)
else :
raise RuntimeError('Form is invalid')
else :
action = model2().get_add_url()
form = model2Form()
c = {'form': form, 'action' : action}
c.update(csrf(request))
return render_to_response('add.html', c, context_instance=RequestContext(request))
You can easily have autocomplete.