在django中是一对一关系时上传文件



对不起,所有的代码给出,但我已经努力了一天,仍然结束了一个问题,当传递stage_id作为一个参数的形式动作url

我有一个类Rapports,它持有一个文件(我更喜欢pdf文件),并与来自其他应用程序的其他类有1to1关系,我正在发送阶段。id从阶段应用程序的html页面,它的工作id被传递,我可以把它传递到另一个html页面,但当我写我需要的代码,并在模板的动作属性传递相同的url模式,我想显示(rapport/test.html下面)它返回NoReverseMatch,我不知道为什么。是因为我要上传文件还是别的什么?(第一次处理文件)

{% block rpt %}
<li class="nav-item">
<a class="nav-link" href="{% url 'rapport:depo' stages.id %}">
déposer le rapport
</a>
</li>
{% endblock rpt %}

关系。怎样的

from django.db import models
from satges.models import Stages
class Rapports(models.Model):
stage=models.OneToOneField(
Stages,
on_delete=models.CASCADE,
primary_key=True,
)
src=models.FileField(
("rapport"),
upload_to='rapports/',
max_length=100
)
r_soummit=models.DateTimeField(
auto_now=False,
auto_now_add=False,
)

舞台。阶段

class Stages(models.Model):
#Stages attrs that are saved so i think no need to show them here
def est_ete(self):
# comment: this fn returns true if it's a summer intership
if(self.deb.month in[6,7,8]):
return True
# end def
def get_absolute_url(self):
return reverse("satges:det_stg", kwargs={"pk": self.pk})
#saving Stages to database with CreateView is working
def __str__(self):
return self.etd + ' ' + self.nature + " - " + self.au

rapport.forms.py

from django import forms
from .models import Rapports
class RapportsForm(forms.ModelForm):
class Meta:
model = Rapports
fields = ['src']

widgets = {
'src': forms.FileInput(),
}

rapport.views

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.views.generic import CreateView
from satges.models import Stages
from .models import Rapports
from .forms import RapportsForm
# Create your views here.
def afficher(request, stage_id):
# comment: 
#return HttpResponse('stage: %s'% stage_id)
if request.method == 'POST':
form = RapportsForm(request.POST, request.FILES)
else:
form=RapportsForm()
return render(request, 'rapport/test.html', {'form': form})
class RapportCreateView(CreateView):
model = Rapports
form_class=RapportsForm
template_name = "rapport/test.html"

# end def
'''
def afficher_depo(request, stage_id):
form=RapportsForm()
print(stage_id)
return render(request,'rapport/depo.html', {'form': form})
def depo(request, stage_id):
if request.method == 'POST':
form = RapportsForm(request.POST)
stage=get_object_or_404(Stages, pk=stage_id)
src = form.cleaned_data['src']
rpt=Rapports(stage=stage,src=src)
rpt.save()
else:
return HttpResponse('rapport isn't saved')

return render(request,'rapport/depo.html', {'form':form})
'''

项目url conf

from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('satges.urls')),
path('journal/', include('journaux.urls')),
path('rapport/<int:pk>', include('rapport.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rapport.urls.py

from django.urls import path, re_path
from . import views
app_name = 'rapport'
urlpatterns = [
path('',views.RapportCreateView.as_view(), name='depo'),
]

test.html(此文件仅用于测试主文件称为depo.html,它扩展了其他页面,并具有相同的行为,当我删除url在行动的形式出现)

<html>
<head>
<title>test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="{% url 'rapport:depo' satge_id %}">
<!--when i remove the url tag the input form appears and i can choose a file but i ofc can't send it without the action-->
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="déposer votre rapport" name="depo">
</form>
</body>
</html>

这应该是所有与问题相关的代码,我已经尝试过谷歌,youtube, django文档和我所做的改变沿着一天的错误不同,但我无法通过的是NoReverseMatch

误差

Error during template rendering
In template /home/ssoya/Documents/pfe/new/pages/templates/rapport/test.html, error at line 6
Reverse for 'depo' with arguments '('',)' not found. 1 pattern(s) tried: ['rapport/(?P<pk>[0-9]+)\Z']

在第一个答案之后,我的视图变成了这样,但无论我改变它仍然没有用

class RapportsCreateView(CreateView):
model = Rapports
form_class=RapportsForm
template_name = "rapport/depo.html"
def get_context_data(self, **kwargs):
context=super(RapportsCreateView, self).get_context_data(**kwargs)
#stage=Stages.objects.get(pk=self.kwargs.get('pk'))
context['stages'] = Stages.objects.filter(pk=self.kwargs.get('pk'))
return context

然后我尝试了别的方法:我替换了舞台。先输入1,再输入13,看看会发生什么。引发IntegrityError

NOT NULL constraint failed: rapport_rapports.stage_id
The above exception (NOT NULL constraint failed: rapport_rapports.stage_id) was the direct cause of the following exception:
response = get_response(request)

一旦我找到了解决方案或对问题有了更多的了解,我愿意重新构建这个问题

这是因为stage_id没有定义所以找不到url因为它需要stage_id参数,检查呈现模板的视图它没有返回stage_id变量
把这个添加到你的创建视图

def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# context is a dict so 
#update it with your stage id
return context

在此函数中添加stage_id,以便将其传递给模板

我可以说是90%解决了

我在这个问题中遇到的问题与我认为的上下文有关,在@mohamed的回答和一些谷歌搜索和尝试之后,我使视图最终工作并将文件保存到服务器和数据库并将sges对象的id作为rapport的id作为属性satge_id然后将用户重定向到另一个页面

这里是我所做的修改

views.py

class RapportsCreateView(CreateView):
model = Rapports
form_class = RapportsForm
template_name = "rapport/depo.html"
def form_valid(self, form):
self.stage_id = self.kwargs['pk']
stage = Stages.objects.get(id=self.stage_id)
form.instance.stage_id = stage.id
form.instance.r_soummit = timezone.now()
return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
stage = Stages.objects.get(pk=self.kwargs.get('pk'))
context['stage'] = stage
context['stage_id'] = stage.id
return context

模型。怎样的

def get_absolute_url(self):
return reverse("rapport:det_rpt", kwargs={"pk": self.pk})
def __str__(self):
return self.src

相关内容

  • 没有找到相关文章

最新更新