我如何将获取值传递给views.py中的特定模型字段

时间:2019-09-03 05:13:45

标签: python django django-forms

如何将request.GET.get值传递给Django中的另一种形式。

views.py

def bacadmininvitoBid_views(request):
    project_list = ProjectNameInviToBid.objects.all()
    query = request.GET.get('query')
    if query:
        project_list = project_list.filter(ProjectName__icontains=query)
        if request.method == 'POST':
            form = invitoBidForm(request.POST, request.FILES)
            if form.is_valid():
                    form.ProjectName = project_list
                    form.save()
                    messages.success(request, 'File has been Uploaded')
            else:
                form = invitoBidForm()

        args = {
            'form': form,
            'project_list': project_list

        }
        return render(request, 'content/invitoBid/bacadmininvitoBid.html', args)

model

class InviToBid(models.Model):
    today = date.today()
    ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE, null=True)
    NameOfFile = models.CharField(max_length=255, verbose_name='Name of File')
    Contract_No = models.IntegerField(verbose_name='Contract No')
    Bid_Opening = models.CharField(max_length=255, verbose_name='Bid Opening')
    Pre_Bid_Conference = models.CharField(max_length=255, verbose_name='Pre Bid Conference')
    Non_Refundable_Bidder_Fee = models.CharField(max_length=255, verbose_name='Non Refundable Fee')
    Delivery_Period = models.CharField(max_length=255, verbose_name='Delivery Period')
    Pdf_fileinvi = models.FileField(max_length=255, upload_to='upload/invitoBid', verbose_name='Upload Pdf File Here')
    Date_Upload = models.DateField(auto_now=True)
def __str__(self):
    return self.NameOfFile

我想将其传递给ProjectName字段

2 个答案:

答案 0 :(得分:1)

如果要将query保存到ProjectName字段中,可以尝试执行以下操作

form = invitoBidForm(request.POST, request.FILES)
    if form.is_valid():
            obj = form.save(commit=False)
            obj.ProjectName = query
            obj.save()
            messages.success(request, 'File has been Uploaded')

答案 1 :(得分:0)

您可以使用Django会话框架或Django缓存框架将数据从一个视图传递到其他视图,包括模板。

Django会话使用request变量。因此,您可以在视图和模板中使用会话请求变量

示例:

def exampleView(request):
    x = "some variable"
    request.session["exampleKey"] = x

def someOtherView(request)
    exampleData = request.session["exampleKey"]
    print (exampleData) -> This will return the value of x from the first view

使用django会话的唯一缺点是,您只能存储可序列化的数据,因此不能存储对象或查询集。

另一个高效而有效的解决方案是Django Cache Framework

from django.core.cache import cache
def exampleView(request):
    x = "some data"
    y = Model.objects.all()
    cache.set("professorX", x)
    cache.set("xmen",y)

def anotherView(request):
    charlesXavier = cache.get("professorX")  --> Will return the value of from the first view.
    xmen = cache.get("xmen") --> Will return the value of y from the first view.

您可以将变量传递给context()和其他渲染方法