Django - Problems with get_or_create()
<p>I'm facing problems using get_or_create() in my view.
What I want to do is have the User get or create an instance of the Keyword model whenever he wants to add a keyword.</p>

<p>I have a Keyword model that looks like this:</p>

<pre><code>class Keyword(models.Model):
    word = models.CharField(max_length=30, unique=True, default=None)
    members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, default=None)

    def __str__(self):
        return self.keywords
</code></pre>

<p>I have a form to create the keyword:</p>

<pre><code>class KeywordForm(forms.ModelForm):
    keywords = forms.CharField(max_length=30)

    def __init__(self, *args, **kwargs):
        super(KeywordForm, self).__init__(*args, **kwargs)
        self.fields["keywords"].unique = False

    class Meta:
        fields = ("keywords",)
        model = models.Keyword
</code></pre>

<p>I've tried different things in the view and here is my current version, without the use of get_or_create. It only creates the keyword:</p>

<pre><code>class KeywordCreationView(LoginRequiredMixin, generic.CreateView):
    form_class = forms.KeywordForm
    model = models.Keyword
    page_title = 'Add a new keyword'
    success_url = reverse_lazy("home")
    template_name = "accounts/add_keyword.html"

    def form_valid(self, form):
        var = super(KeywordCreationView, self).form_valid(form)

        self.object.user = self.request.user
        self.object.save()
        self.object.members.add(self.object.user)

        return var
</code></pre>

<p>How should my view look in order to get the keyword if it exists and if it does, add the User as 'member'. If it doesn't, create the Keyword.</p>

<p>Thanks for your help!</p>

<p>I do believe CreateView isn't the right class for this. You should use <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#updateview" rel="nofollow">UpdateView</a> instead and override the <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_object" rel="nofollow">get_object</a> method (which is actually a part of the SingleObjectMixin) ancestor of this class based view. </p>

<p>The <a href="https://github.com/django/django/blob/master/django/views/generic/detail.py#L22" rel="nofollow">source code</a> of this mixin is rather daunging but in your case something as simple as </p>

<pre><code>def get_object(self, queryset=None):
    pk = self.kwargs.get(self.pk_url_kwarg)
    if queryset:
        obj, c = queryset.get_or_create(pk=pk)

    else:
        obj, c = MyModel.get_or_create(pk=pk)

    return obj
</code></pre>

<p>might work. But frankly, it's alot simpler to use a simple (non class based view)</p>

python django