foreign key django createview

  1. Import necessary modules:
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .models import YourModel
  1. Define the CreateView class:
class YourModelCreateView(CreateView):
    model = YourModel
    template_name = 'your_app/your_model_form.html'
    fields = ['field1', 'field2', 'field3']  # Specify the fields you want in the form
  1. Override the form_valid method to handle the foreign key:
    def form_valid(self, form):
        form.instance.your_foreign_key = self.kwargs['pk']  # Replace 'your_foreign_key' with the actual name of your foreign key field
        return super().form_valid(form)
  1. Define the success URL:
    success_url = reverse_lazy('your_success_url_name')  # Replace 'your_success_url_name' with the actual name of your success URL
  1. Set up your URLs:
from django.urls import path
from .views import YourModelCreateView

urlpatterns = [
    path('your_model/create/<int:pk>/', YourModelCreateView.as_view(), name='your_create_view_name'),  # Replace 'your_create_view_name' with the actual name of your create view
]
  1. Create a template for the form (your_model_form.html):
{% extends 'base.html' %}

{% block content %}
  <h2>Create YourModel</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>
  </form>
{% endblock %}
  1. Link to the create view in your template or views where appropriate:
<a href="{% url 'your_create_view_name' pk=your_foreign_key_value %}">Create YourModel</a>
  1. Ensure your foreign key is set up correctly in your model:
class YourModel(models.Model):
    your_foreign_key = models.ForeignKey(OtherModel, on_delete=models.CASCADE)  # Replace 'OtherModel' with the actual related model
    # Other fields in your model

Note: Make sure to replace placeholders such as 'YourModel', 'your_foreign_key', 'your_app', 'field1', 'field2', 'field3', 'your_success_url_name', 'your_create_view_name', 'OtherModel', and any other placeholders with your actual model, field, app, URL, and model names.