0

I have relationship 1 -> M (case -> document) and how can I set default relationship when I am creating new document. My goal is: I have a list of cases, I open a case and I create new document in case and this document has default value (not blank) with document which was open.

I have

enter image description here

I want to have (default)

enter image description here

view.py

def sprawa(request, id):
    users = get_object_or_404(User, pk=id)
    users.save()
    cases = get_object_or_404(Case, pk=id)
    cases.save()
    documents = Dokument.objects.all()

    return render(request, 'sprawa.html', {'users': users, 'cases': cases, 'documents': documents})

def new_document(request):
    form = NewDocumentForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('/sprawy/')
    return render(request, 'nowydokument.html', {'form': form})

nowydokument.html

<form method='POST' enctype='multipart/form-data'>
            {% csrf_token %}
            {{ form.as_p }}

      <button type="submit">Dodaj sprawÄ™</button>
</form>
pkucinski
  • 75
  • 5

2 Answers2

1

I think that what you want is initial when creating a form instance.

Checkout Django documentation: https://docs.djangoproject.com/en/2.2/ref/forms/api/#dynamic-initial-values

And this StackOverflow question: Setting the selected value on a Django forms.ChoiceField

One way to do it would be just to add when creating a form, or you can add it in your form directly if the value is same all of the time.

def new_document(request):
form = NewDocumentForm(request.POST or None, request.FILES or None, initial={"field_name": "field_value"})
if form.is_valid():
    form.save()
    return redirect('/sprawy/')
return render(request, 'nowydokument.html', {'form': form})
1

If you want to have specific case default for all new document then you can do that from the model.

DEFAULT_CASE_ID = 1
class Document(models.Model):
    ...
    case = models.ForeignKey("Case", default=DEFAULT_CASE_ID)

But you want to have create level default on the form you can do that from the view:

DEFAULT_CASE_ID = 1
form = NewDocumentForm(request.POST or None, request.FILES or None, initial={'case': Case.objects.get(id=DEFAULT_CASE_ID)})
Bikash kharel
  • 472
  • 7
  • 16