简体   繁体   English

Django - NOT NULL 约束失败

[英]Django - NOT NULL constraint failed

I'm currently working on a Django app that will parse the contents of an uploaded log file to the associated database in my Django project.我目前正在开发一个 Django 应用程序,该应用程序会将上传的日志文件的内容解析到我的 Django 项目中的关联数据库。 I've managed to get it all running as expected except it won't associate my uploaded data with the model's ForeignKey.我设法让它按预期运行,除了它不会将我上传的数据与模型的外键关联。 I can assign null=True which resolves the integrity error but then of course, it doesn't assign any of the uploaded data to that ForeignKey.我可以分配 null=True 来解决完整性错误,但当然,它不会将任何上传的数据分配给该外键。 Here's the code:这是代码:

models.py模型.py

class Case(models.Model):

    case_ref = models.CharField(max_length=8)
    oic = models.CharField(max_length=50)
    subject = models.CharField(max_length=100)
    submitted_date = models.DateTimeField(default=datetime.now, blank=True)

    def get_absolute_url(self):
        return reverse('case_list', kwargs={'pk': self.pk})

    def __str__(self):
        return self.case_ref + " " + self.subject
    
class TeamviewerLogs(models.Model):
    
        case = models.ForeignKey(Case, on_delete=models.DO_NOTHING) 
        teamviewer_id = models.IntegerField()
        teamviewer_name = models.TextField()
        connection_start = models.TextField()
        connection_end = models.TextField()
        local_user = models.TextField()
        connection_type = models.TextField()
        unique_id = models.TextField()
    
        def get_absolute_url(self):
            return reverse('case_list', kwargs={'pk': self.pk})
    
        def __str__(self):
            return str(self.teamviewer_id) + " - " + str(self.teamviewer_id)

forms.py表格.py

class UploadLog(forms.ModelForm):
    file = forms.FileField()
    
    class Meta:
      model = TeamviewerLogs
      fields = [
        'file'
      ]

views.py视图.py

def add_logs(request, pk):
  case = get_object_or_404(Case, pk=pk)

  if request.method == 'POST':
      form = UploadLog(request.POST, request.FILES)
      
      if form.is_valid():
          teamviewer = form.save(commit=False)
          teamviewer.case = case


          log_file = request.FILES['file']
          log_file = filter(None, (line.rstrip() for line in log_file))

          for lines in log_file:

              split = lines.decode('utf-8').split('\t')

              teamviewer_id = split[0]
              teamviewer_name = split[1]
              connection_start = split[2]
              connection_end = split[3]
              local_user = split[4]
              connection_type = split[5]
              unique_id = split[6]
          


              teamviewer = TeamviewerLogs(teamviewer_id=teamviewer_id, teamviewer_name=teamviewer_name, 
                                        connection_start=connection_start, connection_end=connection_end, 
                                        local_user=local_user, connection_type=connection_type, unique_id=unique_id)

              teamviewer.save()
              return redirect('tv_log_details', pk=case.pk)
      form.save()

  else:
      form = UploadLog()

  return render(request, 'teamviewer/add_logs.html', {'form': form})

But when I click to upload the file I'm hit with:但是当我点击上传文件时,我遇到了: 在此处输入图片说明

When it tries to execute teamviewer.save().当它尝试执行 teamviewer.save() 时。

I've been trying to resolve this issue for hours and have tried so many different variations of answers from Stackoverflow or previous code I've used that has worked for different models but I've hit a brick wall...hard!我已经尝试解决这个问题几个小时了,并尝试了许多不同的答案变体,来自 Stackoverflow 或我使用过的以前的代码,这些代码适用于不同的模型,但我遇到了砖墙......很难!

Any help anyone can offer would be greatly appreciated.任何人都可以提供的任何帮助将不胜感激。

Ok, so here's an example of the concept I've suggested in the comments.好的,这是我在评论中建议的概念的一个示例。

I've got a view which passes some data to the a form;我有一个视图将一些数据传递给 a 表单;

class ListingDetailView(DetailView):
    """ Listing detail page """
    model = Listing
    template_name = 'listing.html'

    def get_form_kwargs(self):
        """Return the kwargs for the form"""
        kwargs = {}
        initial = {
            'listing': self.object,
        }

        kwargs['initial'] = initial
        return kwargs

    def get_form(self):
        form = ApplicationSignupForm(
            **self.get_form_kwargs()
        )
        return form

    def get_context_data(self, **kwargs):
        """ Add our form to the context """
        context = super().get_context_data(**kwargs)
        context['form'] = self.get_form()
        return context

The form then makes use of that initial data and sets the field it relates to as hidden.然后该表单使用该初始数据并将其相关的字段设置为隐藏。 I don't validate this data, but I'll try to show how you might do that;我不会验证这些数据,但我会尝试向您展示如何做到这一点;

class ApplicationSignupForm(forms.ModelForm):


    class Meta:
        """ Setup the form """
        fields = (
            'listing',
            ...
        )
        model = Application
        widgets = {
            'listing': forms.HiddenInput()
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        initial_data = kwargs['initial']
        self.listing = initial_data.get('listing')
        

    def clean(self):
        """
        Custom form cleaning
        """
        cleaned_data = super().clean()

        listing = cleaned_data.get('listing')
        if listing != self.listing:
            self.add_error('listing', "You can't modify this value")

        return cleaned_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM