python 如何创建一个带有多个选项的提交按钮,可以改变一个csv文件并将其回发

y0u0uwnf  于 2023-08-02  发布在  Python
关注(0)|答案(1)|浏览(82)

我试图创建一个提交按钮,列出了一个特定的用户,每个下拉相关的动作的文件。我可以下载csv文件并修改它,将其保存为新文件,但我似乎不能重新发布该文件并将其添加到列表中。
我被如何将newFile.csv添加到DocumentForm(request.POST,request.FILES)的问题卡住了
models.py

class Document(models.Model):
     user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
     description = models.CharField(max_length=255, blank=False)
     document = models.FileField(upload_to=fileLocation)
     uploaded_at = models.DateTimeField(auto_now_add=True)

字符串
forms.py

class DocumentForm(forms.ModelForm):
class Meta:
    model = Document
    fields = ('description', 'document')


超文本标记语言

{% for file in files %}
         <form id="file" action= "{% url 'process' %}" method="post" enctype="multipart/form-data">
          {% csrf_token %}
          <select name="selectedOption"> 
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
          </select>
          <input type="submit" value="Submit" class="btn btn-sm">
        </form>
        {% endfor %}


views.py

def process(request):
     selected_option = request.POST.get('selectedOption')

     form = DocumentForm(request.POST, request.FILES)
     current_client = request.user
     files = Document.objects.filter(user=current_client)

     fileResponse = s3_client.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=document)
     df = pd.read_csv(fileResponse.get("Body"), encoding='utf-8', dtype=str)
     df.to_csv('temp/temp.csv', index=False, header=True, encoding='utf-8-sig')
    newFile = 'temp/temp.csv'

if request.method == 'POST':
    form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        return redirect('/filelist')
else:
    form = DocumentForm()

return render(request, 'accounts/filelist.html', {'selected_option':selected_option, 'form': form, 'files': files})


的数据

e0uiprwp

e0uiprwp1#

将views.py帖子更改为以下内容。

if request.method == 'POST':
         file_path = newFile

        with open(file_path, 'rb') as file:
            document_instance = Document(
                user_id = request.user.id,
                description = "new file"
                )
            document_instance.document.save(os.path.basename(file_path), file)
            document_instance.save()

字符串

相关问题