Oghomwen Oguns
Oghomwen Oguns

Reputation: 161

Django form manytomany field not saving to database

I am new to Django and i am working on a website where user can submit a post. Django Form is not saving in database when i have manytomany field in model. I do not know if i can achieve this in Django, I want to attached other user names to the post so that when i submit the form the user name is selected automatically when i check on the post in admin. I will attach a screenshots for clarity.

This image below is my form, as you can see 'My post' is the image_caption while 'andy' is another user name, i want 'andy' selected automatically in manytomany field when form is submitted.

enter image description here

This is what i want when the form is submitted then i check in admin. The other user name (andy) is selected in manytomany field when the form is submitted. I did this manually

enter image description here

Model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
    profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True)

class Post(models.Model):
    poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
    image_caption = models.TextField(blank=True, null=True)
    tag_someone = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='tagged_users', blank=True)

Forms:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            'image_caption', 
            'tag_someone',
        )

Views:

def upload_view(request):
    ImageFormset = modelformset_factory(File, fields=('files',), extra=20)
    if request.method == "POST":
        form = PostForm(request.POST)
        formset = ImageFormset(request.POST, request.FILES)
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.poster_profile = request.user
            post.save()
            form.save_m2m()

            for f in formset:
                try:
                    photo = File(post=post, files=f.cleaned_data['files'])
                    photo.save()
                except Exception as e:
                    break
            return redirect('/')

    else:
        form = PostForm()
        formset = ImageFormset(queryset=File.objects.none())

    #User Name Auto-complete In Tag Form
    all_users = User.objects.values_list('username', flat=True) 

    context = {
        'form': form,
        'formset': formset,
        'all_users': all_users,
    }
    return render(request, 'upload.html', context)

Upload.html:

 <form method="POST" enctype="multipart/form-data">
 {% csrf_token %}
  {{ form }}
  {{ formset }}
  <button type="submit" class="btn btn-primary btn-sm btn-block w-25">Post</button>
 </form>

Upvotes: 0

Views: 519

Answers (2)

Oghomwen Oguns
Oghomwen Oguns

Reputation: 161

I was able to get this working by changing widget to:

widget = { 
    forms.Select(),
 } 

Upvotes: 1

ngawang13
ngawang13

Reputation: 673

You can change the widget here. Widgets are the thing that is responsible for outputting the inputs to HTML. So you just need:

class PostForm(forms.ModelForm):
class Meta:
    model = Post
    fields = (
        'image_caption', 
        'tag_someone',
    )
  widgets = {'tag_someone': forms.TextInput}

Upvotes: 0

Related Questions