Updating Django Object Without Using Model or Template from a View

Combining the form and template of different URLs may not provide any benefits. However, if you have shared “housekeeping” code for creating or updating objects, you can use a mixin or create a custom view that inherits from both use cases.


Question:

At present, I’m developing a Django application that enables users to establish synonyms for keywords, and it is supported by the subsequent model:

class UserSynonym(models.Model):
    user = models.ForeignKey(Tenant)
    key = models.CharField(max_length=255)
    value = models.CharField(max_length=255)

The ListView presents an overview, accompanied by an ‘edit’ button for each entry. This button directs the user to the corresponding EditView, which facilitates modification of the ‘value’ parameter.

To enable users to reset the object to its original meaning, I seek to add a button that sets the ‘value’ to the ‘key’ value. This button should be a standalone feature on the list, without requiring any forms or HTML templates. By clicking this button, the model’s value can be ‘reset’.

To accomplish this task, it seems necessary to modify an EditView. However, these views require a form or an HTML template/page, which is not the desired course of action.

Can the EditView be modified to update the object’s value without requiring the user to be redirected to a form or a different webpage?

To ensure inclusivity, I’ve included the UpdateView in my current usage.

class SynonymUpdate(UserRootedMixin, UpdateView):
    model = UserSynonym
    form_class = SynonymCreateForm
  def get_form_kwargs(self):
      kwargs = super(SynonymUpdate, self).get_form_kwargs()
      kwargs['user'] = self.request.user
      return kwargs
  def form_valid(self, form):
      form.instance.linked_user = self.kwargs.get('user')
      return super(SynonymUpdate, self).form_valid(form)
  def get_success_url(self, **kwargs):
      return reverse('synonym_list', args=[self.request.user.id])



Solution:

I found a solution to my issue by abandoning the use of the class
based view
and implementing the following function instead.

def SynonymReset(request, user_id, pk):
  """(re)sets the Synonym.value to the value of Synonym.key"""
  #Get relevant variables
  currentuser = User.objects.get(id=request.user.id)
  currentsynonym = Synonym.objects.get(id = pk)
  #(re)set object & save
  currentsynonym.value = currentsynonym.key
  currentsynonym.save()
  #Return to the listview.
  return redirect('synonym_list', user=current_user)

By resetting the value without navigating to a different webpage, I am able to achieve my goal. Although I am still searching for a way to accomplish this using a class-based view, I am content with this solution for the time being.

Frequently Asked Questions