What's the best method of saving an existing record as a new record when in a specific view?
I cannot use default values in a CreateView because the defaults will change depending on the type of record the user is creating.
models.py
class videos(models.Model):
title = models.CharField(max_length=250)
fk_type = models.ForeignKey('mediaTypes',on_delete=models.CASCADE)
b_template = models.BooleanField(default=False)
class mediaTypes(models.Model):
name = models.CharField(max_length=250)
e.g.
1 - Football game - 4 - TRUE
2 - Superbowl X highlights - 4 - FALSE
3 - Superbowl XX highlights - 4 - FALSE
4 - Home movies - 2 - TRUE
5 - Finding Holy Gail under house - 2 - FALSE
forms.py
from django import forms
from django.forms import ModelForm
from .models import (videos)
class create_football(ModelForm):
class Meta:
model = videos
fields = '__all__'
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.contrib.auth.decorators import login_required
from django.db.models import Q # filter using operators '&' or '|'.
from django.utils import timezone
from users.models import Profile
from django.forms import ModelForm
from django.http import HttpResponseRedirect
from .models import (videos)
from .forms import (create_football)
class templates(LoginRequiredMixin, ListView):
model = videos
template_name = 'videos/templates.html'
context_object_name = 'video'
def get_queryset(self):
profile = get_object_or_404(Profile, user=self.request.user)
queryset = videos.objects.filter(Q(fk_type="4")
return queryset
class create_football(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = videos
form_class = create_football
template_name = 'videos/create_football.html'
def form_valid(self, form):
messages.success(self.request, 'form is valid')
form.instance.user = self.request.user
form.save()
To create a new football video, the user selects the record titled 'football game' from the templates view - which opens an update view. This dummy template record has the fk_type and other fields automatically set to the appropriate value.
I need this view to save the changes the user will make, such as to the title, as a new record.