Django: how to insert data into 2 tables

时间:2017-08-05 12:25:55

标签: django postgresql inner-join

I am trying to create an application that takes the URL of a website and returns its TLD. TLD is the foreign key of its respective table. I want to insert into the URL table that takes the TLD and inserts it into the TLD table. So that when I access the URL table I see only the ID of the TLD. The problem is that it gives me this error:

The view website.views.UrlExtractorView didn't return an HttpResponse object. It returned None instead.

This is my models.

TLD

class TLD(models.Model):
    name = models.CharField(max_length=10, unique=True)

    def save(self, *args, **kwargs):
        super(TLD, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.name)

UrlExtractor

class UrlExtractor(models.Model):
    url = models.CharField(max_length=255)
    tld_id = models.ForeignKey(TLD, null=True, blank=True)
    status = models.BooleanField(default=True)
    created = models.DateTimeField(auto_created=True, auto_now=True)

    def save(self, *args, **kwargs):
        super(UrlExtractor, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.url)

This is my view functions:

def tld_of_url(thestring):
    link = ""
    for i in thestring[::-1]:
        link += i
        if i == ".":
            break
    tld_more = link[::-1]
    tld = ""
    for i in tld_more:
        if i != "/":
            tld += i
        else:
            break

    return tld

class UrlExtractorView(View):
    def get(self, request):
        the_form = UrlExtractorForm()

        context = {
            "title": "Enter website",
            "form": the_form
        }
        return render(request, "website.html", context)

    def post(self, request):
        url_form = UrlExtractorForm()

        if url_form.is_valid():
            url_form = UrlExtractorForm(request.POST)
            url = url_form.cleaned_data.get('url')
            true_tld = tld_of_url(url)

            tld = TLD(name=true_tld)
            tld_form=TLDForm(request.POST)

            if tld_form.is_valid():
                tld_form.save()

            obj = UrlExtractor.objects.get_or_create(url=url)

            context = {
                "title": "Enter website",
                "object": obj,
                "form": url_form
            }

            return render(request, 'website.html', context)

and this is my forms:

class UrlExtractorForm(forms.Form):
    url = forms.CharField(label='Enter website')

class TLDForm(forms.Form):
    name = forms.CharField()

0 个答案:

没有答案