Auto fill update form - django

I have a date model and a Order model. The date model is connected to Order model by a foreignkey, I'm trying to update the date model feilds in Order model with a form. I want the form to autofill the fields with saved data in admin database. I tried a lot to find the solution but I couldn't find it.

In your view.
You need to edit the function
views.py
def orderDetailView(request, pk):
order = Order.objects.get(pk=pk)
date_instance = order.date
form = DateForm(request.POST, request.FILES, instance=date_instance)
if form.is_valid()
form.save()
.....
....
context = {
'order': order, 'form': form
}
return render(request, "date_list.html", context)

Related

Django update functionality

I've got a model, with two forms. When a calf is scanned in, it gets one set of information, then when it's shipped out, it's a separate form with different information. For example when scanned in, it takes DOB and arrival date, when scanned out we need ship out date, milk consumed during it's stay(2 quarts per day), where it is going, and any medication while at the depot.
Right now I have the two forms below:
Scan in form
scan out form
Now you can see when I try to update an entry I get an error that it already exists
Here is my view:
def scanoutcalf(request, id=None):
form = ScanOutForm(request.POST or None)
context = {
'form': form,
}
form = ScanOutForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'calves/scan_out.html', context)
And my forms:
class ScanOutForm(forms.ModelForm):
class Meta:
model = Calf
fields = [
'eid', 'ship_out_date', 'program', 'destination', 'medical_history', 'milk_consumed'
]
widgets = {
'ship_out_date': forms.widgets.DateInput(
attrs={'type': 'date'}
)
}
I've googled around, but couldn't find an example of how to update without having to create a queryset or a URL with instance ID.
The idea here is that a user can just scan when calves are leaving, update with the information that is essential, and the form will check the EID, and update the DB if it exists, or create it if it doesn't. Any help would amazing
Query the instance before saving and pass into ScanOutForm as keyword argument instance.
Like so:
def scanoutcalf(request, id=None):
form = ScanOutForm(request.POST or None)
context = {
'form': form,
}
if request.method == 'POST':
try:
calf = Calf.objects.get(eid=request.POST['eid'])
except:
calf = None
if calf is not None:
form = ScanOutForm(request.POST, instance=calf)
if form.is_valid():
form.save()
return render(request, 'calves/scan_out.html', context)
Note: As you use unique identifier in the form this must be directly extracted from request.POST with validation.

How to link two forms (wagtail form and django form) with a foreign key?

I'm using a django form in conjunction with a wagtail form. The django form will record some fields that will be on any form of this type: name, email and the wagtail form will record extra data defined by the form page creator specific to that instance.
I've overloaded the serve method to capture both sets of data and I can process both forms, but I'm stuck when trying to add the logic to relate the form contents to each other so that when one submission set is deleted, the other set will be as well. I think what I need is a foreign key.
The following code fails at form_submission.event_submission = a.id where I'd like to take the id from the wagtail form submission and add that as a foreign key to the django form, so that when the wagtail form portion is deleted, the other is deleted as well, and so that I can have a usable link between the two form submissions.
def serve(self, request, *args, **kwargs):
if request.method == 'POST':
form = EventSignupForm(request.POST)
wagtail_form = self.get_form(request.POST, request.FILES, page=self, user=request.user)
if form.is_valid() and wagtail_form.is_valid():
a = self.process_form_submission(wagtail_form)
form_submission = form.save(commit=False)
form_submission.event_submission = a.id
form_submission.save()
return self.render_landing_page(request, form_submission, *args, **kwargs)
else:
form = EventSignupForm()
wagtail_form = self.get_form(page=self, user=request.user)
context = self.get_context(request)
context['form'] = form
context['wagtail_form'] = wagtail_form
return TemplateResponse(
request,
self.get_template(request),
context
)
The form submission class and django model form looks like this. I think the ForeignKey I have in the Model isn't right, but I don't know. Any help?
class EventFormSubmission(AbstractFormSubmission):
cancellation_id = models.CharField(max_length=7)
class EventSignup(models.Model):
"""
A model to contain signup info for an event: name, email.
"""
event_submission = models.ForeignKey(EventFormSubmission, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
email = models.EmailField()
I solved this by adding the extra fields I wanted (name, email) to the EventFormSubmission and then using a regular django form (not a ModelForm) to collect these pieces of information.

Filtering a model on a foreign key

Alright, I am pulling my hair out (and I don't have much) I have created a FormView that uses 2 models. One model simply displays some information from a table (not editable) the other Model is a form that a user selects two items from a drop down box. I need to filter the first Dropdown box. Below is the code I am using that is not working:
views.py
def assign_load(request):
form = DispatchForm(request.POST or None)
loads = Load.objects.all().filter(active=True, dispatched=False,
picked_up=False, delivered=False,
billed=False,
paid=False).order_by('start_pickup_date')
context_dict = {'dispatch' : form, 'load' : loads}
if form.is_valid():
save_it = form.save()
save_it.save()
new_dispatch = Dispatch.objects.get(id=save_it.id)
fix_load = Load.objects.get(id=new_dispatch.load_number_id)
fix_load.dispatched = True
fix_load.save()
return HttpResponseRedirect('/dispatch/dispatch/')
return render(request, 'dispatch/dispatch_form.html', context_dict)
forms.py
class DispatchForm(ModelForm):
class Meta:
model = Dispatch
fields = ['load_number', 'truck', 'start_mileage', 'end_mileage',
'pickup_date',
'pickup_time', 'delivery_date', 'delivery_time', 'driver_pay',
'fuel_cost', 'miles',
'status']
def get_queryset(self):
return self.model.objects.filter(load_number__dispatched=False)
I am trying to filter the model in forms.py I have tried using def get(), def get_queryset() and def get_context_data, none of them are returning a filtered queryset...I know I am missing something simple but I am running out of ideas any help would be great...if you need more information let me know that as well.
Thanks for all your help!

Django initial value for MultiChoice Field ignored for ModelForm

this is my first post here and I am very new to Django but I just can't seem to find a solution for this problem... I've searched stackoverflow and google but nothing seems to work for me...
I have a wine-app and want to be able to add and remove wines from the user's stock. In the list of wines the user can choose a wine to add and the ID of this wine is passed in the POST data. Since the data is getting lost after the first time the view is rendered I saved the ID in a cookie, which is working, but the problem is when I work with ModelForm de user has to select the foreign key for the user and for the wine, which is bad, so I tried to make it hidden and set the Fk_user and Fk_wine after the user choose the number of bottles to be added but before validation. Here's the problem after google everyone suggested I should use the "initial" and pass that to the form, but this is clearly not working because if I make the fields visible in the form I can see that it is not preselected...
viewy.py:
def addStockView(request):
wineId = request.POST.get('addStock')
if 'addStock' in request.POST:
wine = get_object_or_404(Wine, idwine=int(wineId))
userId = request.user.id
user = get_object_or_404(AuthUser, id=userId)
if request.method == 'POST':
#wineIdNew = request.COOKIES.get('wineIdToAdd')
#wineNew = get_object_or_404(Wine, idwine=wineIdNew)
form = StockForm(request.POST, initial={'fk_wine': wineNew.idwine, 'fk_auth_user': user.id})
if form.is_valid():
form.save()
return redirect('home')
else:
form = StockForm(initial={'fk_wine': wine.id,
'fk_auth_user': user.id})
response = render(request, 'addToStock.html', {'form': form})
response.set_cookie('wineIdToAdd', wineId)
return response
forms.py:
class StockForm(forms.ModelForm):
#fk_wine = ModelChoiceField(queryset=Wine.objects.all(),
# widget=HiddenInput())
#fk_auth_user = ModelChoiceField(queryset=AuthUser.objects.all(),
# widget=HiddenInput())
class Meta:
model = UserWineStock
fields = ['fk_auth_user', 'fk_wine', 'number']
can anyone help me with this..?
Yes, initial data is ignored when a form is bound to submitted data.
Instead of using initial here, you should exclude those two fields from the form and set them on the created object:
form = StockForm(request.POST)
if form.is_valid():
item = form.save(commit=False)
item.fk_wine = wine
item.fk_auth_user = request.user
item.save()
return redirect('home')
(Also, please don't call your fields things like fk_auth_user. Just call it user.)

Django filtering based on data

I'm using django to develop a web app. Right now I am trying to make a page that will initially render a blank form and all data objects of a certain model, and then once the user submits the form, will then filter the objects displayed to show those that have the desired attributes.
My form class is as follows
class AreaForm(forms.Form):
seating = forms.IntegerField(label='Seating', default=False)
whiteboards = forms.BooleanField(label='Whiteboards', default=False)
outlets = forms.IntegerField(label='Outlets', default=False)
tables = forms.IntegerField(label='Tables', default=False)
And the view for this page thus far is
def search(request):
if request.method == 'GET':
form = NameForm(request.POST)
if form.is_valid():
# do filtering logic here somehow
return render(request, 'SpotMe/search.html', {'form': form}) # ????
else:
return render(request, 'SpotMe/search.html', {}) # ????
I'm as of yet unsure how to implement the templates page. Am I headed in completely the wrong direction?
To show the form empty and do some logic when user post data, you need to pass the form to the template and it'll render empty if there is not post data.
view.py
def search(request):
form = AreaForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
# do filtering logic here somehow
return render(request, 'SpotMe/search.html', {'form': form})
search.html
.....
{{ form.as_p }}
.....
Based on your reply to my question below your original post, this is an easy solution that will show all data object of a model, and then you can use an input and submit it from a template to filter the results on the same page.
Note: Substitute MODEL for your actually model name. You don't need a form if you are looking to filter results (it is an extra, unnecessary step).
def search(request):
if request.method == 'GET':
if request.GET.get('seating_no'):
seating_no = request.GET.get('seating_no')
queryset = MODEL.objects.filter(seating=seating_no)
else:
queryset = MODEL.objects.all()
return render(request, 'SpotMe/search.html', {'queryset': queryset})
and in your SpotMe/search.html you can have a <form><input name="seating_no" /></form> and submit button that will lead to the same URL, and make the input name(s) into whatever you want to capture via request.GET.get()