简体   繁体   中英

How can i call class function thats insert row into db properly from my django template?

Hellow, I am noob and I make instagram followers scraper on Django.

I make a function that should add 1 (only 1 cos it works really slow) new follower in to db which takes from already working sсraping functions and place it into class.

class ListOfFollowers(ListView):
    model = Followers
    context_object_name = 'followers_of'
    template_name = 'insta/followers.html'

    def get_follower(self, username):

        loader = instaloader.Instaloader()
        loader.login('***', '***')

        profile = instaloader.Profile.from_username(loader.context, username)
        followers = profile.get_followers()
        followers_tuple = tuple(followers)

        i = random.randint(0, len(followers_tuple) - 1)

        login = followers_tuple[i].username
        photo = followers_tuple[i].get_profile_pic_url()
        url = f'https://www.instagram.com/{login}/'
        mutual_subscription = followers_tuple[i] in profile.get_followees()
        res = {'login': login, 'photo': photo, 'url': url, 'mutual_subscription': mutual_subscription}

        return res

    def add_followers(self):
        username = WhoFollow.objects.get(follow_on__contains=self.kwargs['follow_id']).title
        context = None
        while not context:
            try:
                context = get_follower(username)
            except:
                next
        context.update({'follow_on': self.kwargs['follow_id']})
        res = Followers(context)
        res.save()

    def get_queryset(self):
        return Followers.objects.filter(follow_on=self.kwargs['follow_id'])

function calls add_followers (try block is just because its not always working from 1st try)

My models

class WhoFollow(models.Model):
title = models.CharField(max_length=255)

    def __str__(self):
        return self.title

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

class Followers(models.Model):
    login = models.CharField(max_length=255)
    photo = models.ImageField(upload_to="photos/", blank=True)
    url = models.URLField()
    mutual_subscription = models.BooleanField(default=False)
    time_add = models.DateTimeField(auto_now_add=True)
    time_unfollow = models.DateTimeField(blank=True)
    follow_on = models.ForeignKey(WhoFollow, on_delete=models.PROTECT)

    def __str__(self):
        return self.login

And my template

{% extends 'insta/Base.html' %}

{% block content %}

<h1>Who we find</h1>
<ul>
    {% for l in object_list %}
    <li>
        <h5>{{l.login}}</h5>
    </li>
    {% endfor %}
</ul>

<!-- from there i dont understand what i should do too -->

<form action="{% url views.ListOfFollowers.}">
    <button type="submit" onclick="">add another 1</button>
</form>

{% endblock %}

urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('', Home.as_view(), name='home'),
path('add/', AddWhoFollow.as_view(), name='add'),
path('follow/<int:follow_id>', ListOfFollowers.as_view(), name='follow'),]

Sorry for too many code but my head already broken on this task.

There are some issues with your code:

First, you have added the two methods get_follower() and add_followers() to the your ListView, but it is unclear how (if at all) they are called. It looks to me like you might be misunderstanding the concept of the ListView. The purpose of the ListView is to render a list of objects, not add something. So instead you want to create a new view for adding followers. You can just define a simple function view for that, does not have to be a CBV.

Second, each view needs to have it's own URL defined. You did not post your urls.py , but I suppose {% url views.ListOfFollowers.} in the template will not work. Instead, you need to define a URL name in your urls.py (one for each view) and out that in your template.

I was totaly misunderstand the concept of the CBV.

The answer is that i should do it inside CreateVeiw after form validation where i choose which login to scrap.

There is result:

class AddFollowers(CreateView):
form_class = AddFollower
model = Followers
template_name = 'insta/add_follower.html'

def get_success_url(self):
    return reverse_lazy('home')

def form_valid(self, form):

# Here is a body of scraping script where i creating a list of objects to add in db

Followers.objects.bulk_create(objs=res)

return HttpResponseRedirect(f'http://127.0.0.1:8000/)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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