How to create a submit button with multiple options that can alter a csv file and post it back

huangapple go评论73阅读模式
英文:

How to create a submit button with multiple options that can alter a csv file and post it back

问题

我试图创建一个提交按钮,列出特定用户的文件,并为每个下拉列表添加相关操作。我可以下载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')

html

{% 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})

How to create a submit button with multiple options that can alter a csv file and post it back


请注意,这是您的代码的翻译部分,不包括代码块中的具体细节和操作。

<details>
<summary>英文:</summary>

I&#39;m trying to create a submit button that lists files for a particular user that has actions associated to each drop down. I can download the csv file and alter it, save it as a new file but I can not seem to repost the file and add it to the list. 

I am stuck how to add the newFile.csv to the 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 = (&#39;description&#39;, &#39;document&#39;)

html

             {% for file in files %}
             &lt;form id=&quot;file&quot; action= &quot;{% url &#39;process&#39; %}&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
              {% csrf_token %}
              &lt;select name=&quot;selectedOption&quot;&gt; 
                  &lt;option value=&quot;1&quot;&gt;1&lt;/option&gt;
                  &lt;option value=&quot;2&quot;&gt;2&lt;/option&gt;
                  &lt;option value=&quot;3&quot;&gt;3&lt;/option&gt;
              &lt;/select&gt;
              &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; class=&quot;btn btn-sm&quot;&gt;
            &lt;/form&gt;
            {% endfor %}

views.py

    def process(request):
         selected_option = request.POST.get(&#39;selectedOption&#39;)

         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(&quot;Body&quot;), encoding=&#39;utf-8&#39;, dtype=str)
         df.to_csv(&#39;temp/temp.csv&#39;, index=False, header=True, encoding=&#39;utf-8-sig&#39;)
        newFile = &#39;temp/temp.csv&#39;

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

    return render(request, &#39;accounts/filelist.html&#39;, {&#39;selected_option&#39;:selected_option, &#39;form&#39;: form, &#39;files&#39;: files})

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/PX51M.png

</details>


# 答案1
**得分**: 0

更改了views.py中的post如下。

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

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

changed the views.py post to the below.

if request.method == &#39;POST&#39;:
         file_path = newFile

        with open(file_path, &#39;rb&#39;) as file:
            document_instance = Document(
                user_id = request.user.id,
                description = &quot;new file&quot;
                )
            document_instance.document.save(os.path.basename(file_path), file)
            document_instance.save()

huangapple
  • 本文由 发表于 2023年7月28日 02:31:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定