Django 1.11 Add data to form after POST - django-views

I am using Django 1.11 and I'm trying to add data to a ModelForm using CreateView after POST submit. The form first submits data to a linked MS exchange account using the exchangelib library. I then return the exchange id created and this is what Im trying to add to the ModelForm so that it is captured in my Model database. Everything is working fine up to the point I return the exchange id. My issue is I am unsure how to add this into the form for capturing.
Does anyone have any advice on how to add this returned datapoint to the form? I am using def post if form.is_valid() and have tried setting self.initial unsuccessfully.
Any help would be greatly appreciated!

Ok so I was going about this the wrong way. Ended up getting it to work by using def form_valid(self, form) with form.instance.exchange_id = ex.uid

Related

Autocomplete Django form jQuery

I'm kind of new to Django. Anyway, I want my form to have JavaScript Autocomplete. An example of what I'm trying to do is this: https://www.w3schools.com/howto/howto_js_autocomplete.asp. So, here is my question: should I go for all HTML and JavaScript and then try to pass the user input manually by declaring this in my views.py?
def register(request):
country = request.POST['mycountry']
Or, is there any Django way of handling this?
I have used this in the past. little tricky to get up and running from what I remember. Also active on github.
http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html

In Django how to do filter, followed by get queries and get a field value?

Following is a simplified models.py of one of the apps of my Django program:
#This is the custom queryset manager
class TenantManager(models.Manager):
def for_tenant(self, tenant):
return self.get_queryset().filter(tenant=tenant)
#This is one of the models:
class accountChart(models.Model):
name=models.CharField(max_length =200)
remarks=models.TextField(blank=True)
key=models.CharField(max_length=20)
tenant=models.ForeignKey(Tenant,related_name='accountchart_account_user_te nant')
objects = TenantManager()
#This is another data model, related ith FK to 1st model shown here
class paymentMode(models.Model):
name = models.TextField('Payment Mode Name')
payment_account=models.ForeignKey(accountChart,related_name='paymentMode_accountChart')
default=models.CharField('Default Payment Mode ?', max_length=3,choices=choice, default="No")
tenant=models.ForeignKey(Tenant,related_name='paymentmode_account_user_tenant')
objects = TenantManager()
Now, I'm doing the following queryset based on user inout. However, Django is throwing up errors. Request your kind help, as this thing is killing me for more than 2 days.
#Queryset:
payment_mode=paymentMode.objects.for_tenant(request.user.tenant).get(name__exact=request.POST.get('payment_mode'))
payment_account=payment_mode.account
However, Django is throwing up error with the second line of queryset. Even if I use filter instead of get, its showing error - Queryset doesn't have filter!!
From what I understand, first django is giving me all the payment modes related to this user, then getting the payment mode from the request.POST.get object and then in the second line it's trying to get the
related foreignkey. Can anyone kindly tell where I'm going wrong?
Well, sorry to disturb you all, I just got my answer as there was a typo in Queryset.
And as it should be, once I use "get" the solution is fine. Now, I'm not sure if there's a better way to do it except for caching the sessions data!!
This is an answer I wrote for future reference of others.

How to update Django modelform without inserting?

I am having a problem with my Django code inserting new rows instead of updating existing ones. Many people on here have asked for help with a similar problem, but generally they forget about setting instance as in form = SomeModelForm(request.POST or None, instance=some_model_instance). I seem to be doing that right, but it still doesn't save over existing data.
One other poster had the exact same issue (see Django form INSERTs when I want it to UPDATE). It looks like the code given to him to fix the problem resolved the issue, but no one explained why it worked when he asked!
VIEW
if form_type == "edit_event":
# we need to load all the data based on the event_id
event_id = request.POST['event_id'] or None
event_to_edit = mapDataManager.getEvent(event_id)
if event_to_edit and mapDataManager.userCreatedEvent(request.user, event_to_edit):
# this user actually created this event
# let them edit it
event_form = EventModelForm(request.POST or None, instance=event_to_edit)
location_form = LocationModelForm(request.POST or None, instance=event_to_edit.location)
list_of_event_scheds = EventSchedule.objects.filter(pk=event_id).values()
event_sched_formset = EventScheduleModelFormSet(request.POST or None, initial=list_of_event_scheds)
if event_form and location_form and event_sched_formset:
if event_form.is_valid() and location_form.is_valid() and event_sched_formset.is_valid():
# update event
mapDataManager.updateEvent(event_form, location_form, event_sched_formset)
# redirect
return HttpResponseRedirect(reverse('map'))
else:
# set feedback to show edit event form
feedback = "edit_event"
updateEvent()
def updateEvent(self, event_form, location_form, event_sched_forms):
event = event_form.save(commit=False)
location = location_form.save()
event.location = location
event.save()
for event_sched_form in event_sched_forms: # loop through formset
event_sched = event_sched_form.save(commit=False)
event_sched.event = event
event_sched.save()
Can anyone help me out? Am I missing something really basic?
EDIT: Just to clarify, NONE of my forms were updating, all were inserting. Based on Daniel's suggestion I think I need to use formsets to link all three modelforms that are being edited.
For some strange reason, you're correctly passing instance to the main forms, but initial to EventScheduleModelFormSet, which is the immediate cause of the problem.
However, since these models obviously have a foreign key relationship, it sounds like you should be using a inline model formset:
from django.forms.models import inlineformset_factory
eventschedule_formset_class = inlineformset_factory(Event, EventSchedule)
event_sched_formset = eventschedule_formset_class(request.POST or None,
instance=event_to_edit)
Now there is no need for that updateEvent logic - you can just save event_sched_formset and it will correctly reference the event.
you are trying to save the EventScheduleModelFormSet form? there is no instance set only initial data so you are creating a new object every time. or am I missing something?
I was able to get the inline model formset working as per Daniel's suggestion with help from this blog post: http://charlesleifer.com/blog/djangos-inlineformsetfactory-and-you/
Just as an FYI, one crucial point I was missing is that the formset's instance refers to the parent model. Also, if you're displaying the formset manually in your template, don't forget to include {{ formset.id }}.

Django Forms and Buttons

I have been working on forms only recently and I am still puzzeld by them.
What I want are standard Forms:
Next Button
Submit Data to Db
Timestamp
Clickable Images with Regions defined where when I click I get to the next page
And
I would like to combine these.
E.g. have a next button + Record the Timestamp.
or
E.g. Click into an Image + Next + Timestamp
If anybody could give me some examples for code that can achieve that or a good online resource on where to get info on that, that would be awesome.
Thanks for the time!!
I'm a little unclear about what you're trying to accomplish, but if you're trying to move data from an HTML form to the database, I'd suggest looking at how to use ModelForms. In a nutshell, you create a model class, like this:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
Then you create a ModelForm class that references that model:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
You can render an instance of MyModelForm in a view function. Inside of a POST request in that view, you bind the POST data to the form, validate it, and call save() on it to commit it to the database:
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
model_instance = form.save()
This really isn't a question, I'm not exactly sure what you're trying to accomplish.
If you want to use Django forms, start here, or here.
I assume the stuff you mention about a timestamp should probably be an auto_now field in a model. Take a look at this.
The stuff you mention about buttons and click-able images is really just HTML and has nothing to do with Django. I would try Google for that.

Django Dynamic Forms

I am using James Bennetts code to create a dynamic form. I have everything working but want to save the data to a database. Has anyone got any code which does this or could show me what the best way to do this would be e.g. how the model should be set up etc?
Override the save() method on your form class:
def save(self):
new_user = User.objects.create_user(username=self.cleaned_data['username'],
email=self.cleaned_data['email'],
password=self.cleaned_data['password1'])
return new_user
(taken from James Bennett's blog at Newforms, part 2)