title: How to pass a variable from one view to another in Django
body: <p>I would like to pass a variable from one view to another in Django and am not sure of the best method.</p>
  
  <p>The "defaultCreateView" below is a form that makes a new database entry and has a required field that I want to be filled automatically (device_id). So my thought is I could pass it through in the URL. This form is accessed using the button shown in my template below. So the idea is that the first view passes the variable to the template where the button is, then this button adds the device_id to the URL via the href. </p>
  
  <p>Is there a much easier/better way to accomplish this?</p>
  
  <p>Thanks in advance for any help.</p>
  
  <p><strong>urls.py</strong></p>
  
  <pre><code>urlpatterns = [
      path('&lt;int:pk&gt;/edit/', defaultUpdateView.as_view(), name='default_edit'),
      path('&lt;int:pk&gt;/', defaultDetailView.as_view(), name='default_detail'),
      path('&lt;int:pk&gt;/delete/', defaultDeleteView.as_view(), name='default_delete'),
      path('&lt;int:device&gt;', DefaultsListView.as_view(), name='Default_Listview'),
      path('&lt;int:device&gt;/new/', defaultCreateView.as_view(), name='default_new'),
      path('Defaultsapidata/', apiDefaultsListView.as_view(), name='Defaults_apidata_list'),
      path('&lt;int:pk&gt;/changedefaults/', changeDefaultsViewSingle.as_view()),
  ]
  </code></pre>
  
  <p><strong>Views.py</strong></p>
  
  <pre><code>class DefaultsListView(LoginRequiredMixin,ListView):
      model = models.DefaultDMLSProcessParams
      template_name = 'defaults_list.html'
      login_url = 'login'
      def get_queryset(self):
          return super(DefaultsListView, self).get_queryset().filter(device_id=self.kwargs['device'])
  
      def get_context_data(self, **kwargs):
          context = super().get_context_data(**kwargs)
          deviceID = self.kwargs['device']
          context['deviceID'] = deviceID
          return context
  
  class defaultCreateView(LoginRequiredMixin,CreateView):
      model = models.DefaultDMLSProcessParams
      template_name = 'default_new.html'
      fields= ['defaultParamDescrip','processType','processNotes',]
      login_url = 'login'
  
      def form_valid(self, form):
          form.instance.customerTag = self.request.user.customerTag 
          form.instance.device_id = self.kwargs['device']
          return super().form_valid(form)
  </code></pre>
  
  <p><strong>defaults_list.html</strong></p>
  
  <pre><code>&lt;a class="btn btn-primary btn-lg" 
  href="{% url 'default_new' {{deviceID}}  %}" role="button"&gt; Add New Default Parameter&lt;/a&gt;
  </code></pre>
  
  <p><strong>EDIT</strong>
  I get a "NoReverseMatch at /defaults/41" when I try to access defaults_list.html, but this is solved when I change the URL of defaultCreateView to:</p>
  
  <pre><code>        path('new/', defaultCreateView.as_view(), name='default_new'),
  </code></pre>