Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

561
Visualizações
how to build a bookmark system in django as in instagram

I wanna build this bookmarking system like in Instagram, I'm having problems writing the logic in views.py and displaying it. So what I want is to bookmark "Act" based on "act-id's" to Wishlist model if a user is authenticated and it would be better if we use Ajax for the post-call(when clicked on the bookmark icon) or open to new options really. Here's my current code... Please help me! if you need any extra bit of code just lemme know.

models.py

class Act(models.Model):
    label1 = models.CharField(max_length=50, blank=False)
    label2 = models.ImageField(blank=False, null=True)
    label3 = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    label4 = models.CharField(max_length=80)

    def __str__(self):
        return self.Name

class Wishlist(models.Model):
    user_id = models.ForeignKey(User, on_delete=models.CASCADE,null=True)
    act_id = models.ForeignKey(Act, on_delete=models.DO_NOTHING)

views.py

@csrf_exempt
def wishlist(request):
    act_id = request.POST.get('act_id')
    if not act_id:
        raise ValueError("Required act_id to set wishlist")
    user_id = request.user.pk
    try:
        act_id = Act.objects.get(pk=act_id)
        wishlist_obj = {
                        'user_id': user_id,
                        'act_id': act_id
        }
        Wishlist(**wishlist_obj).save()
    except ObjectDoesNotExist:
        return HttpResponse('Some error occured, unable to add to wishlist')
    return HttpResponse('Added to wishlist')

urls.py

urlpatterns = [
    path('signup/', views.signup, name='signup'),
    path('login/', views.login_req, name='login'),
    path("logout/", views.logout_req, name="logout"),
    path('home/', views.home, name='home'),
    path('wishlist/', views.wishlist, name='wishlist'),
]

for more context here's a conceptual pic of home.html

error img

[![enter image description here][3]][3]

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Here's my view on how you can do this.

Wishlist the model if a user is authenticated and it would be

I always prefer to use decorators to check if the user is authenticated. You can see here on how to achieve this - Writing your own decorator for login authentication. And then you can then simply apply @login_required to check if the user is authenticated or not.

You can also simply check in the views.py using the is_authenticated attribute to check if the user is logged in or not.

if request.user.is_authenticated:
  # do something if the user is authenticated

it would be better if we use Ajax for the post-call(when clicked on the bookmark icon)

I would also recommend an Ajax request to update this as this suited to an asynchronous task. You can see the example here on how you can write the ajax function. But in short, once the user clicks the bookmark button the ajax request will be made to the function in views.py with the relevant post data , you can then simply add your desired operations in the function.

Edit:

The problem is rather broad and though I do have a few solutions, writing most by words will simply get convoluted for you to take anything out of but I shall give it a try!

So given that you have the model which saves and displays the card which has been wish-listed; therefore in undoing that operation, you would simply have to reverse-engineer the logic using Ajax. So, firstly when a user clicks to undo a card that has been wish-listed, you make an ajax call, e.g. here and then in your views.py you simply verify if the clicked element is indeed is wish-listed by checking that the object exists in your database.

If it exists, you then simply return a success JSonResponse({}) from the function in views.py and then in your

success: function (response) { }

in your Js you simply add the relevant HTML code to unlist the card from the wishlist. A good example is shown here that demonstrates how you can use JSON and ajax to update the unlisted card.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda