如何使用Django和 AJAX 发送选定的选项?

nvbavucw  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(96)

我有一个关于发送或保存我选择选项到数据库的问题。我已经尝试了所有我知道的方法来运行这个程序,但总是不保存所选的选项。我已经删除了我试图解决这个问题的代码行,以便你们可以用自己的方式提出解决方案。如果你们需要更详细的代码,请告诉我。我希望你能明白我在说什么
我的models.py:

class Category(models.Model):
    category = models.CharField(max_length=200)
    slug = models.SlugField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

class Gallery(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)
    category = models.ManyToManyField(Category,blank=True)
    thumbnail = models.ImageField(upload_to='thumbnails')
    slug = models.SlugField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

我的forms.py:

class GalleryForm(forms.ModelForm):
    category = forms.ModelMultipleChoiceField(
        queryset=Category.objects.all(),
        widget=forms.SelectMultiple,
        required=False
    )
    
    class Meta:
        model = Gallery
        fields = ['title', 'description', 'category','thumbnail']

我的views.py:

def gallery_list_and_create(request):
    form = GalleryForm(request.POST or None, request.FILES or None)
    if(request.user.is_authenticated):
        user = User.objects.get(username=request.user.username)
        gallery_user = user.gallery_set.all()
        if(is_ajax(request=request)):
            if(form.is_valid()):
                instance = form.save(commit=False)
                instance.author = user
                instance.save()
                return JsonResponse({
                    'id': instance.id,
                    'title': instance.title,
                    'description': instance.description,
                    # 'category': [category.category for category in instance.category.all()],
                    'thumbnail': instance.thumbnail.url,
                    'slug': instance.slug,
                    'author': instance.author.username,
                    'since': instance.updated_timesince,

                })
        
        context = {
            'form': form,
            'gallery': gallery_user,
        }
    
        return render(request, 'Post/index.html', context)
    return render(request, 'Post/index.html')

我的js文件:

postForm.addEventListener("submit", e => {
    e.preventDefault()

    const fd = new FormData()
    fd.append('csrfmiddlewaretoken', csrf[0].value)
    fd.append('title', titleID.value)
    fd.append('description', descriptionID.value.length > 0 ? descriptionID.value : "")
    **'how to append category'?**
    fd.append('thumbnail', thumbnailID.files[0])

帮帮我

t40tm48m

t40tm48m1#

这是使用commit=False的结果:它防止保存多对多字段,因为这是在创建对象之后完成的:

if form.is_valid():
    form.instance.author = user
    instance = form.save()  # saves object and m2m
    return JsonResponse({})  # return data

相关问题