Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get last_error of background_task_completedtask in django for a specific run
I use django-background-tasks to run queued tasks. the tasks are triggered by a client request and when a task fails, I want to show client the last_error field of background_task_completedtask table so they know why their request has failed. I tried the documents but did not find anything useful so I'd be glad if anyone shares a way to achieve this goal -
I am using Django Elasticsearch and currently I'm getting this kind of error:
from django_elasticsearch_dsl import ( Document, Index, fields ) from django_elasticsearch_dsl.registries import registry from accounts.models import Profile PUBLISHER_INDEX = Index('profile') @registry.register_document @PUBLISHER_INDEX.doc_type class DisbtrAdSale(Document): class Django: model = Profile fields = [ 'user', 'referral_id', 'phone_number', 'first_name', 'last_name', 'email' ] -
Django Rest Framework AttributeError 'CustomUser' object has no attribute 'user'
I have different types of users. That's why, each user type should have own profile details. So I am trying to code API for these profiles. However, I couldn't resolve this error. I am following an example from a course. My code is completely similar as this example. I don't understand where am I going wrong. It seems that I am making a mistake in reconciling the related models. I checked the aliases and tried over and over to solve it. I tried many alises to solve it but i couldn't be successful each time. Error message AttributeError at /api/account/child-profile-update Got AttributeError when attempting to get a value for field user on serializer ChildProfileSerializer. The serializer field might be named incorrectly and not match any attribute or key on the CustomUser instance. Original exception text was: 'CustomUser' object has no attribute 'user'. Custom User Model class CustomUser(AbstractUser): GENDER_CHOICES = ( (1, AccountStrings.CustomUserStrings.gender_choice_male), (2, AccountStrings.CustomUserStrings.gender_choice_female), (3, AccountStrings.CustomUserStrings.gender_choice_other), ) USER_TYPE_CHOICES = ( (1, AccountStrings.CustomUserStrings.user_type_choice_default), (2, AccountStrings.CustomUserStrings.user_type_choice_child), (3, AccountStrings.CustomUserStrings.user_type_choice_parent), (4, AccountStrings.CustomUserStrings.user_type_choice_instructor), ) objects = CustomUserManager() email = models.EmailField(max_length=255, unique=True, null=False, blank=False) identity_number = models.CharField( max_length=11, unique=True, verbose_name=AccountStrings.CustomUserStrings. identity_number_verbose_name) birth_date = models.DateField( null=True, blank=True, verbose_name=AccountStrings.CustomUserStrings.birth_date_verbose_name) gender = models.PositiveSmallIntegerField( choices=GENDER_CHOICES, default=1, verbose_name=AccountStrings.CustomUserStrings.gender_verbose_name) user_type = models.PositiveSmallIntegerField( … -
Django aggregating records for each foreign key
class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey( Category, null=True, on_delete=models.SET_NULL ) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) placed = models.DateTimeField(auto_now=True) shipped = models.DateTimeField(null=True) delivered = models.DateTimeField(null=True) I want to calculate statistics on how fast the order has been processed for each category where process time is delivered - shipped In result I want to achieve something like this: [ { "category": <category 1> "processed_time": <average processed time in seconds> }, { "category": <category 2> "processed_time": <average processed time in seconds> }, { "category": <category 3> "processed_time": <average processed time in seconds> }, ] I can calculate this outside of the ORM but I'd like to achieve this somehow with annotation/aggregation delivered = delivered_qs.annotate(first_processed=Min("delivered"), last_processed=Max("delivered")) \ .aggregate(processed_time=F("last_processed")-F("first_processed")) This QS returns time only for all categories and I dont know how to retrieve time for each individual category -
Using double url tag in django
I got two urls.py file first one is for project urls.py urlpatterns = [ path('admin/', admin.site.urls , name = 'admin'), path('',homeView, name='home'), path('post/',post, name='post'), path('post/',include('post.urls'), name='posturl'), path('student/',studentM, name = 'student' ), path('student/',include('student.urls') , name='studenturl'), ] second one is url for app urlpatterns = [ path('index', post_index, name = 'index'), path('details/' + '<int:id>', post_detail, name = 'detail'), path('create', post_create, name = 'create'), path('update', post_update , name = 'update'), path('delete', post_delete , name = 'delete'), ] I am trying to reach the adress like :8000/post/details/5 but when i try to use in html <a href = "{ % url 'post.detail' %}"> =>> {{post.id}}</a> <a href = "{ % url 'detail' %}"> =>> {{post.id}}</a> <a href = "{ % url 'post' %}"> =>> {{post.id}}</a> None of these are not working I got 404 error. How can I reach the link which I want def post(request): context = { } return render(request,'post/post.html',context) def post_detail(request,id): post = get_object_or_404(Post,id=id) context = { 'post' : post } return render(request,"post/details.html",context) -
Issue with using django celery when django signals is being used to sent email?
I have used the default Django admin panel as my backend. I have a Blogpost model. What I am trying to do is whenever an admin user saves a blogpost object on Django admin, I need to send an email to the newsletter subscribers notifying them that there is a new blog on the website. I have to send mass emails so I am using django-celery. Also, I am using django signals to trigger the send email function. But Right now, I am sending without using celery but it is too slow. class Subscribers(models.Model): email = models.EmailField(unique=True) date_subscribed = models.DateField(auto_now_add=True) def __str__(self): return self.email class Meta: verbose_name_plural = "Newsletter Subscribers" # binding signal: @receiver(post_save,sender=BlogPost) def send_mails(sender,instance,created,**kwargs): subscribers = Subscribers.objects.all() if created: blog = BlogPost.objects.latest('date_created') for abc in subscribers: emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) else: return Using celery documentation i have written following files. My celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE','travel_crm.settings') app = Celery('travel_crm') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Mu init file: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ … -
How can I attach a newly created file to the model
The user adds a video and a watermark is automatically applied to the video. It turns out to process the user's video and put a watermark, but I don't know how to attach this video to the model, so that later this video with a watermark would be displayed on the site. Just attach obj.video_uploaded = final_ to the model - it doesn't work, writes the error object has no attribute '_committed' model.py class Video(models.Model): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title') photo = models.ImageField(upload_to='photo/%Y/%m/%d') video_uploaded = models.FileField(upload_to='video/%Y/%m/%d',blank=True,null=True) views.py def add_video(request): if request.method == "POST": form = VideoUploaderForm( data=request.POST, files=request.FILES, ) if form.is_valid(): obj = form.save(commit=False) vid = request.FILES['video_uploaded'] clip = VideoFileClip(vid.temporary_file_path()) # watermark video = VideoFileClip(clip.filename) logo = (ImageClip('faiklogo.png') .set_duration(video.duration) .resize(height=50) .margin(right=8, top=8, opacity=0) .set_pos(("center", "bottom"))) final_ = CompositeVideoClip([video, logo]) final_.write_videofile('media/video/videwithwatermark.mp4') obj.save() else: form=VideoUploaderForm() return render(request, 'firstapp/add_video.html', {"foenter code hererm": form}) form.py class VideoUploaderForm(forms.ModelForm): class Meta: model = Video fields = '__all__' -
How can I Create Stripe Checkout Session for multiple products with Django and JavaScript?
I'm building a site with a few products for purchase using Django and Stripe Checkout. I can get the checkout page for one product without a problem. But what I would like to do is create a checkout page with multiple products. This is my function in my Django views.py. Note that it takes product name as a parameter. If I hard code my stripe products into the line_items I can get a checkout session with multiple products. def create_stripe_checkout_session(request, product_name): domain_url = 'http://localhost:5000/' try: checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], shipping_rates=[''], shipping_address_collection={'allowed_countries': ['US', 'CA']}, metadata={'product_name': product_name, }, line_items=[{'price': PRODUCTS_STRIPE_PRICING_ID[product_name], 'quantity': 1, 'adjustable_quantity': {'enabled': True, 'minimum': 1, 'maximum': 10, }, }], mode='payment', success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled.html',) return JsonResponse({'id': checkout_session.id}) except Exception as e: print(e) raise SuspiciousOperation(e) Where I'm struggling is with my JavaScript fetch. My .html page has a bunch of product buttons with class 'buy-button' as well as unique button values and add/subtract to cart buttons. I'm able to keep track of how many and which products I need to create a checkout session for. I just can't figure out how to replace the JS productName variable with an object literal/dictionary or other data structure that I can pass … -
Django admin page redirecting to the same login page even after providing correct credentails
I'm working on a django project where i cant access the admin page when deployed to Digitalocean droplet with nginx/gunicorn , it is redirecting to the same login page again and again However when i run the server using python manage.py runserver on port 80 , it works fine -
ParseError On Django Restframework
I have created a Custom user Model for my project, using Django 3.2. To POST/PUT the details in the user I am using restframework. But while giving the data for "PUT" operation to change some change I am getting the error as JSON parse error - Expecting value: line 1 column 1 (char 0) def update_masteruser(request,pk): try: user = MasterUser.objects.get(pk=pk) except MasterUser.DoesNotExist: return JsonResponse({'message': 'The User does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == "PUT": user_data = JSONParser().parse(request) #problem seems to be on this line serializer = RegisterUserSerializer(user, data=user_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I searched the error cause, but couldnt find the reason on it. Why cant it parse the data from request? -
Error 404 serving media files in a Django app hosted on DigitalOcean
I am making a small Django app and I want to use files uploaded via Django admin panel in production This is from my settings.py file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '' MEDIA_ROOT = BASE_DIR I trust admin uploaded files and want to serve them easily(without Amazon S3 and similar services), so i tried to place the uploaded files with other static files image = models.ImageField(upload_to='static/images') After uploading an image via admin panel i run python manage.py collectstatic in the DigitalOcean console. Whenever i try to access the image i get Error 404, while all other static files(which are real static files, not uploaded via admin panel) load successfully I did the same thing locally and there is no problem, everything loads as expected(DEBUG=True is set both locally and on DigitalOcean). Is it some security measure that doesnt let uploaded files end up in static? How can i bypass it if i trust files uploaded via admin panel? -
Django, celery and kombu: how to allow pickle?
I want to use picker as the celery serializer. I'm getting a kombu error that pickle is not allowed. Celery documentation says (https://docs.celeryproject.org/projects/kombu/en/master/userguide/serialization.html#guide-serialization) By default Kombu will only load JSON messages, so if you want to use other serialization format you must explicitly enable them in your consumer by using the accept argument: But I have no idea how to implement that. I have celery[redis]==5.1.2 and in my project's settings.py I have tried CELERY_TASK_SERIALIZER = 'pickle' which leads to the error. (This setting is not documented here, is it old? https://docs.celeryproject.org/en/stable/userguide/configuration.html#task-settings) -
Facing Error While Pushing Code To Heroku
I have python Application in django and Pushing the code to Heroku using following command git push heroku master but at the end faces following error: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/ktietz/src/ci/alabaster_1611921544520/work' Can anyone help, Thanks in advance -
Django db field not displaying modified slug field value after serializing
I am trying get the user names instead of user id, in the created_by field of the Comment class. My model is below: class Comment(models.Model): thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) content = models.TextField() created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) Have used slugfield in the serializer. class CommentSerializer(serializers.ModelSerializer): created_by = serializers.SlugRelatedField( slug_field='email', queryset=User.objects.all()) class Meta: model = Comment fields = ("id", "thread_id", "content", "created_by", "created_at", "likes") Where as in the api below, the field created_by still has user id and not email. @action(detail=True, methods=["GET"]) def list_comments(self, request, pk): comments = Comment.objects.filter( thread_id = pk ) data = json.loads(serialize('json', comments)) print("**************data**************") print(data) return Response(data, status.HTTP_200_OK) The data printed looks like this : [{'model': 'blog.comment', 'pk': 20, 'fields': {'thread_id': 19, 'content': 'hi', 'created_by': 2, 'created_at': '2021-07-14T03:34:11.333Z', 'likes': 0}}] Is this because of serialize? How do I correctly get the value of the created_by as user email and not id ? -
Unable to load django variables in html through static javascript file
I have defined my javascript file inside static folder of my django project with path js/info.js and content as follows:- function info() { $('#outer_info').append('<div id="get_info"></div>'); console.log('info_btn clicked') document.getElementById('get_info').innerHTML = `<div class='modal fade' id='exampleModal1' tabindex='-1' aria-labelledby='exampleModal1Label' aria-hidden='true'> <div class='modal-dialog modal-dialog-centered modal-md'> <div class='modal-content' style='background-color:#47423e;'> <div class='modal-header'> <h3 class='modal-title text-white' id='exampleModal1Label'>xbguvolrtktest</h3> <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button> </div> <div class='modal-body'> <center><h3 class="text-white">Bucket Details</h3> <table class="table table-dark table-sm table-hover border-white"> <tbody> <tr> <td class="text-white">Items in Bucket:</td> <td class="text-white">{{ bucket_item_count }}</td> </tr> <tr> <td class="text-white">Bucket Size:</td> <td class="text-white">{{ bucket_size }}</td> </tr> <tr> <td class="text-white">Last Updated On:</td> <td id="last_updated" class="text-white">{{ last_updated_time }}</td> </tr> <tr> <td class="text-white">Directories:</td> <td class="text-white">{{ directory_count }}</td> </tr> <tr> <td class="text-white">Files:</td> <td class="text-white">{{ file_count }}</td> </tr> </tbody> </table> <br></center> </div> <div class='modal-footer'> <button type='button' class='btn btn-secondary' data-bs-dismiss='modal' style='background:#e2513c'>Close</button> </div> </div> </div> </div> <input type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal1" data-bs-whatever="@mdo" id="infoButton" hidden>` document.getElementById("infoButton").click(); } Here is how it is being called in index.html file:- <script src="{% static '/js/info.js' %}" type="text/javascript"></script> This is basically a Bootstrap Modal. The problem is that the value of the django variables is not getting rendered on html although it works fine when I include the entire script inside index.html directly. Here is how it looks:- What might be going … -
Django select count of same foreign keys within the same model
I have this model: class File(models.Model): id = models.CharField(max_length=21, null=False, blank=False, primary_key=True, unique=True) id_content = models.ForeignKey(Content, db_column="id_content", on_delete=models.CASCADE) I want to select the id and the count of other files with the same Foreign Key as this id. I literally have got no clue about where to define such query inside filter, extra etc. I have done this previously inside this MySQL query, but I'm looking for a Django Model solution: SELECT f1.`id` AS id, (SELECT COUNT(f2.`id_content`) FROM `file` AS f2 WHERE f2.`id_content` = f1.`id_content`) AS total FROM `file` AS f1; Thanks -
Use image URL in easy_thumbnail django
Currently I am using the following code in my django template which I use to display a picture and crop accordingly: <img src= "{% thumbnail obj.picture 375x550 box=obj.cropping crop detail %}" alt=""> instead I want to use the obj.picture.url instead of the picture object itself. Is there anyway to do this using django's easy_thumbnails. I don't want to use another way because I already have a cropping feature setup that I am using accross the app. -
django, gunicorn, grpc: "Failed to pick subchannel" if run django grpc client with gunicorn
I am a beginner in the Django framework. I wrote an application consist of 2 microservices. One as a Django Rest Server and the other as a Django GRPC Server. the rest request translated to GRPC requests in the first server and sent to the second for the process. ------>|-----------|------->|-----------| |rest server| |grpc server| | | | | <------|-----------|<-------|-----------| when I ran the first server with python manage.py runserver ip:port the application works properly. but when I ran the first server with gunicorn myapp.wsgi --workers=1 --bind=ip:port, a grpc request from the rest server randomly counter an error: {"created":"@1593330482.005402565","description":"Failed to pick subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":3981,"refer enced_errors":[{"created":"@1593330482.005396918","description":"failed to connect to all addresses","file":"src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc","file_l ine":394,"grpc_status":14}]} the interesting thing is the grpc request was received by grpc server and it sent back the response. wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() -
GET HTTP 405 Method Not Allowed
I am getting the following error when trying to access view using the following url: http://127.0.0.1:8000/api/hello-view/. I have posted code below incorporated views.py and urls.py created in my django-app. I will appreciate if review codes and advise where the errors are: enter code here Error message: HTTP 405 Method Not Allowed Allow: OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method "GET" not allowed." } enter code here views.py file content: from rest_framework.views import APIView from rest_framework.response import Response class HelloApiView(APIView): def get(self,request, format=None): """Returns a list of APIView features""" an_apiview = [ 'Uses HTTP methods as functions (get, post, patch, put, delete)', 'Is similar to a traditional Django View', 'Gives you the most control over your logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello!', 'an_apiview': an_apiview}) enter code here urls.py file content from django.urls import path from profiles_api import views urlpatterns = [ path('hello-view/', views.HelloApiView.as_view()), ] -
For a project with multiple user types across different apps, what is the correct AUTH_USER_MODEL to specify in the settings conf?
I have a Django 3.2.5 project in which I want to implement the different user types Artist and User (normal site user). I wouldn't want to share one User model and have all user types sharing redundant fields, e.g. a regular site user wouldn't have artist-specific information. The Django documentation advises that when starting a new project it is best to create a custom user rather than to inherit the built-in User. I can implement two models, Artist and User (both inheriting AbstractUser) - but what would the value of my AUTH_USER_MODEL config then be? -
Do sandbox CopyLeaks result requests send headers?
When CopyLeaks sends the completed webhook to my server, I then send an export request like the following (note that I'm specifying "headers") { "completionWebhook": "***REDACTED***/copyleaks/webhook/exported/56", "crawledVersion": { "endpoint": "***REDACTED***/copyleaks/webhook/crawled/56", "headers": [ [ "Authorization", "PRECI ***REDACTED***" ] ], "verb": "POST" }, "results": [ { "endpoint": "***REDACTED***/copyleaks/webhook/result/56/2a1b402420", "headers": [ [ "Authorization", "PRECI ***REDACTED***" ] ], "id": "2a1b402420", "verb": "POST" } ] } but I don't see that "Authorization" header when CopyLeaks submits the result to the indicated URL. The result requests are being received by my Django website. This is what Django shows for headers: {'UNIQUE_ID': 'YO5jaCH4wN9w5X3ozii3nQAAAAY', 'SSL_TLS_SNI': 'dev.earlychildhoodeducator.com', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REQUEST_METHOD': 'POST', 'QUERY_STRING': '', 'REQUEST_URI': '/copyleaks/webhook/crawled/56', 'SCRIPT_NAME': '', 'PATH_INFO': '/copyleaks/webhook/crawled/56', 'PATH_TRANSLATED': '***REDACTED***/wsgi.py/copyleaks/webhook/crawled/56', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_KEEP_ALIVE': '600', 'HTTP_ACCEPT_ENCODING': 'gzip', 'CONTENT_LENGTH': '179', 'HTTP_HOST': 'dev.earlychildhoodeducator.com', 'SERVER_SIGNATURE': '', 'SERVER_SOFTWARE': 'Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips mod_wsgi/4.6.2 Python/3.6', 'SERVER_NAME': 'dev.earlychildhoodeducator.com', 'SERVER_ADDR': '10.68.195.10', 'SERVER_PORT': '443', 'REMOTE_ADDR': '35.239.30.65', 'DOCUMENT_ROOT': '/var/data/websites/dev.earlychildhoodeducator.com/static', 'REQUEST_SCHEME': 'https', 'CONTEXT_PREFIX': '', 'CONTEXT_DOCUMENT_ROOT': '/var/data/websites/dev.earlychildhoodeducator.com/static', 'SERVER_ADMIN': 'tech@earlychildhoodeducator.com', 'SCRIPT_FILENAME': '/var/data/websites/dev.earlychildhoodeducator.com/main/wsgi.py', 'REMOTE_PORT': '39827', 'mod_wsgi.script_name': '', 'mod_wsgi.path_info': '/copyleaks/webhook/crawled/56', 'mod_wsgi.process_group': 'pacrimdev', 'mod_wsgi.application_group': 'dev.earlychildhoodeducator.com|', 'mod_wsgi.callable_object': 'application', 'mod_wsgi.request_handler': 'wsgi-script', 'mod_wsgi.handler_script': '', 'mod_wsgi.script_reloading': '1', 'mod_wsgi.listener_host': '', 'mod_wsgi.listener_port': '443', 'mod_wsgi.enable_sendfile': '0', 'mod_wsgi.ignore_activity': '0', 'mod_wsgi.request_start': '1626235752847504', 'mod_wsgi.request_id': 'YO5jaCH4wN9w5X3ozii3nQAAAAY', 'mod_wsgi.queue_start': '1626235752847648', 'mod_wsgi.daemon_connects': '1', 'mod_wsgi.daemon_restarts': '0', 'mod_wsgi.daemon_start': '1626235752847734', 'mod_wsgi.script_start': '1626235752847820', 'wsgi.version': (1, 0), 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.run_once': … -
TypeError: unsupported operand type(s) for *: 'DeferredAttribute' and 'DeferredAttribute' django
Good afternoon community, I am new to Django and in order to practice, I am building a financial website. The goal is that the user will insert data regarding company x, e.g. Apple, and the website will perform some metrics calculations to return to the user. I have two models so far: class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name class Market_Cap(Company): market_cap= Company.share_price * Company.outstanding_shares When I run python manage.py check I get the following error: Market_Cap market_cap= Company.share_price * Company.outstanding_shares TypeError: unsupported operand type(s) for *: 'DeferredAttribute' and 'DeferredAttribute' Any hints as to how I can solve this problem? Thanks a lot in advance. -
How do I display an image from an API in a Django
I am creating a website in Django. On the homepage I would like to display a different image on the every time the site's reloaded. I found an API with all the pictures I think I would ever need but I've never used an API before and I've found researching how to do this simple specific thing overwhelming. The docs didn't help me much either. I'm trying to use https://waifu.pics/docs. When you give a specific URL (ex. https://api.waifu.pics/sfw/dance ) you get a JSON with the actual Image URL you'd need to use. My first attempt: <a href="{% url 'index'%}"><img src="https://api.waifu.pics/sfw/dance" alt="Homepage IMG"> </a> I knew it would be more complicated than this but my first idea was to use the link in an ... that didn't work, because I need to get the specific URL every time. Any help would be appreciated, thanks. -
Why is django not finding any object matching the query, even though object is created
HEADSUP: I don't know if this is a duplicate. There are many with similar titles one, but they aren't answering my question. If it is a duplicate, however, please inform me. I have this model called Item: class Item(models.Model): title = models.CharField(max_length=120) date_created = models.DateTimeField(default=timezone.now) deadline = models.DateTimeField(default=timezone.now() + timedelta(5)) task = models.ForeignKey(Task, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) def __str__(self): return f'{self.title} for {self.task.title} - Item {self.id}' I have a delete view for Item: class DeleteItemView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Item template_name = 'function/delete_item.html' success_url = reverse('all-items') def test_func(self): item = get_object_or_404(Item, id=self.kwargs['pk2']) if item.task.author == self.request.user and not item.task.is_completed: return True return False def get_context_data(self, **kwargs): context = super(DeleteItemView, self).get_context_data(**kwargs) context['task'] = Task.objects.filter(id=self.kwargs['pk'])[0] return context Now, my problem is this. Whenever I try to go to this delete view, it results in an error, saying there is no item found matching the query (404). And it says Raised by: function.views.DeleteItemView . I am at my wits end, spending almost half a day trying to figure this out, but with no success. Any help or answers will be immensely and greatly appreciated. -
Ajax Like button is not working in infinite scroll javascript pagination
I am building a BlogApp and I build infinite scroll pagination using JavaScript, When user go down then page is loading and scrolling BUT When user likes a blogpost which came from infinite scroll then blogpost's like is showing directly JsonResponse message without ajax. AND when user like from top blogpost ( First Post ) which is already there without infinite scroll then like button is working fine. I have tried two libraries on infinite scroll but both are not working in ajax button. models.py class Blog(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) title = models.CharField(max_length=50) likes = models.ManyToManyField(User, related_name='blog_like', blank=True) views.py class BlogListView(ListView): model = Blog context_object_name = 'books' paginate_by = 5 template_name = 'blogs/blog-list.html' def post_like_dislike(request, blog_id): post = get_object_or_404(Blog, pk=blog_id) # Like if request.GET.get('submit') == 'like': if request.user not in post.likes.all(): post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) return redirect('mains:posts') blog-list.html <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <body> <div class="blog-list"> {% for book in blogs %} <div class="card mb-3"> <div class="card-body"> <h5 class="card-title">{{ book.title }}</h5> <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'post_like_dislike' book.id %}" data-pk="{{ book.id }}"> <span id="id_likes{{book.id}}"> {% if user in book.likes.all %} <p style="color:#065FD4;display: …