Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to arrange template for Django comments and corresponding replies
I have a made a Comment model and views and it works perfectly fine. But I am not able to arrange templates so that it shows reply to its corresponding comments or reply. It will be a great help if you educate me on how do I arrange them. Models.py class Comment(models.Model): serial = models.AutoField(primary_key=True) theme = models.ForeignKey(THEME, related_name='comments', on_delete = models.CASCADE) user = models.ForeignKey(UserModel, related_name='user', on_delete = models.CASCADE) date_added = models.DateTimeField(default=now) body = models.TextField() parent = models.ForeignKey('self',null=True, related_name='replies',on_delete = models.CASCADE) def __str__(self): return f"{(self.body)}({self.user})" Views.py def viewtheme(request, theme_name): theme = THEME.objects.get(theme_name=theme_name) context={} context['theme']=theme if request.POST: form=CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) # Assign the current post to the comment new_comment.theme = theme # Save the comment to the database new_comment.user = request.user if request.POST.get('serial') == '' or request.POST.get('serial') == None: new_comment.save() return redirect(f"/theme/{theme_name}") else: new_comment.parent = Comment.objects.get(serial=request.POST.get('serial')) new_comment.save() return redirect(f"/theme/{theme_name}") context['comments_form']=form else: form=CommentForm() context['comments_form']=form return render(request, 'themes/view_theme.html',context) Template That I tried but didn't worked <div class="card"> <div class="card-body"> <div class="card-title">Comments</div> <div class="card-text"> <form method="POST"> {% csrf_token %} {{comments_form.as_p}} <input type="hidden" name="seral" value=""> <br> <button type="submit">Add Comment</button> </form> <hr> <br> {% if theme.comments.all %} {% for comment in theme.comments.all %} {{ comment.body }} <form method="POST"> {% csrf_token %} {{comments_form.as_p}} <input … -
Memory leak in Django with Gunicorn and max-requests is already set
I have a Django application that is integrated with Gunicorn and Prometheus and Kubernetes. It's an application that queries ElasticSearch. my Gunicorn config is: exec gunicorn wsgi:application \ --worker-class gthread \ --bind 0.0.0.0:15236 \ --workers 40 \ --threads 4 \ --log-level=info \ --log-file=- \ --timeout 20 \ --reload My Problem Memory is gradually increasing. And when I add --max-requests 500 config for Gunicorn, my memory still increases and my Pod becomes Evicted! I also deleted all the URLs except for url('', include('django_prometheus.urls')) to ensure that the memory leak is not caused by my code. I also checked the Prometheus directory and It was only 1mb so it is not caused by Prometheus. and DEBUG is set to False. Questions What is it possibly causing the memory leak? And why is max-requests not helping at all and only worsening? Versions Django==3.1.1 gunicorn==20.0.4 django-prometheus==2.1.0 -
How to create a js portfolio filter (Isotope.js) with Django
I am building a portfolio website with Django and I want to filter porfolios based on a category on my home page, I am using the js portfolio filter pluggin (Isotope.js). I never thought this will be so difficult to achieve in Django and I did not see any resources on this on the Internet. my_custom_processor.py def index(request): port_category = PortfoilioCategory.objects.all() service = Services.objects.all() ''' Many more querysets ''' context = { 'port_category':port_category, 'service':service } return context base.html <ul> {% for port in port_category %} <li><a href="#porfolio_menu" data-filter="{{ port.id }}">{{ port.cat_name }}</a></li> {% endfor %} </ul> How do I create a view or a context_processor for the detail of my portfolio item using the divs below? How do I pass dynamic parameter to my context_processor? How else can I achieve this? <div class="col-xs-12 col-sm-4 appsDevelopment"> <div class="portfolio_single_content"> <img src="{% static 'img/portfolio/p1.jpg' %}" alt="title" /> <div> <a data-lightbox="example-set" href="{% static 'img/portfolio/p1.jpg' %}">Photo Frame</a> <span>Subtitle</span> </div> </div> </div> -
Invalid block tag error. Unable to figure out where have I missed ending block
I am getting the following error:- Invalid block tag on line 124: 'endif', expected 'endblock'. Did you forget to register or load this tag? I am trying to create a pagination system for my listings display. I am trying to figure out where have I missed the ending block. <div class="row"> <div class="col-md-12"> {% if listings.has_other_pages %} <ul class="pagination"> {% if listings.has_previous %} <li class="page-item"> <a href="?page={{listings.previous_page_number}}" class="page-link" >&laquo;</a > </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link">{{i}}</a> </li> {% else %} <li class="page-item"> <a href="?page={{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} </ul> {% endif %} </div> </div> -
Pyintsaller Execuatble RuntimeError: Script runserver not found
I used Pyinstaller to created a Django application Executable "testrun" on Linux. Then I used the command "dist/testrun/testrun runserver: localserver:8000" to test the executable. But the error message shows: "RuntimeError: Script runserver not foundspec file hiddenimport used for executable building Executable Runtime Error Message -
Access url (get_absolute_url) in Django Rest Framework inside a javascript
I have trouble in django rest framework where I filtered data using Ajax (completed) but the problem is that I can't access absolute url of a table row (td) to access the detail page (via pdf api) of that row. It is important to mention that it Work fine without Ajax, as I made a template without Ajax. Model class ApplyForm1(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) std_campus = models.ForeignKey(Campus, on_delete=models.CASCADE, blank=True) admission_class = models.ForeignKey(CampClass, on_delete=models.CASCADE, blank=True) std_fname = models.CharField(blank=True, max_length=20, null=True) std_lname = models.CharField(blank=True, max_length=20, null=True) std_pic = models.ImageField(upload_to='images/', blank=True) def __str__(self): return '{}'.format(self.std_campus) def std_full_name(self): return self.std_fname + " " + self.std_lname def get_absolute_url(self): return reverse('apply_form', kwargs={ 'id': self.id }) class Campus(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) id = models.AutoField(primary_key=True) campus_name = models.CharField(blank=True, max_length=30) user = models.ForeignKey(CampusUser, on_delete=models.CASCADE, blank=True, null=True) status = models.CharField(max_length=10, choices=STATUS, default='Disabled', null=True, blank=True) def __str__(self): return '{}'.format(self.campus_name) View def admissions(request): return render(request, 'admissions.html', {}) class AdmissionListing(ListAPIView): # set the pagination and serializer class pagination_class = StandardResultsSetPagination serializer_class = AdmissionSerializers def get_queryset(self): # filter the queryset based on the filters applied queryList = ApplyForm1.objects.all() campus = self.request.query_params.get('std_campus__campus_name', None) status = self.request.query_params.get('status', None) if campus: queryList = queryList.filter(std_campus__campus_name=campus) if status: queryList … -
Can not install django-heroku
I try pip install django-heroku and it gives me an error: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Thank you for helping me. -
Django to block certain regex in url
I have a Django-rest-framework and i want to block/return 404 for any URL using regex like ApiRoot/?any-word question mark at the beginning of it, i haven't specified any path in urls.py but Django still returning 200 with any word that comes after "?" question mark. example request url: HTTP GET /?any-word 200 Further more how do i get the request ip when URL like this used? -
Email Sends In Development But Not In Production
I am able to send these automated emails through Dajngo while in my production environment, though in development I get the error [Errno 101] Network is unreachable Exception Location: /opt/alt/python38/lib64/python3.8/socket.py in create_connection, line 796 My settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'email.email@email' EMAIL_HOST_PASSWORD = 'password' SERVER_EMAIL = EMAIL_HOST_USER I think the connection is being refused by Outlook, however it's accepted in my development environment (I used powershell to enable SMTP AUTH). Any help would be greatly appreaciated. Thank you. -
Django get_absolute_url() doesn't seem to work in comment section
I'm trying to get my users to the article page after comments, but something is missing. class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments" ,on_delete=models.CASCADE) name = models.CharField(max_length=30) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) class Meta: verbose_name = "comentario" verbose_name_plural = "comentarios" ordering = ['date_added'] def get_absolute_url(self): return reverse('article-detail', kwargs={'pk': self.pk}) urls.py path('article/<int:pk>/comment/', AddCommentView.as_view(), name='add_comment'), path('article/<int:pk>', ArticleDetailView.as_view(), name="article-detail"), path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), For the update_post the get_absolute_url() works. Thanks in advance. -
How to set default value of Django Fields from another Database table
I have here my codes models.py class Inventory(models.Model): name = models.CharField(max_length=100) class Products(models.Model): name = models.CharField(max_length=100) inventory_id = models.ForeignKey(Inventory, on_delete=models.CASCADE) Ideally, instead of always choosing the inventory_id manually, I want it to be default value like it will automatically be set as default value of inventory_id -
Tag variable to HTML class (or div) name in Django template
So I have this view.py from django.shortcuts import render from .models import Table def table_view(request): table_count = Table.objects.count() return render(request, 'table/table_view.html', {'table_count': table_count, 'table_list': range(table_count)}) and my template: {% extends "base.html" %} {% block title %}Dashboard{% endblock %} {% block content %} <h1>Table Management</h1> <div id="table_display"> {% for table in table_list %} <button class="button table1">Table {{table|add:"1"}}</button> {% endfor %} </div> {% endblock %} I want to tag the class name for the buttons with the value of variable table. For eg.: table1, table2, table3,etc. as the for loop iterate through the table_list. Could anyone advise how I go about doing this? Note that table_list starts from 0 and I would like for the name to start from 1. -
Django celery worker error on ec2 trying to start daemon process with systemd
I am trying to use celery as a daemon on my ec2 server and have so far been following this tutorial. Every time I try to start a celery worker daemon the log returns with these errors: systemd[1]: celery.service: Failed to load environment files: No such file or directory systemd[1]: celery.service: Failed to run 'start' task: No such file or directory systemd[1]: celery.service: Failed with result 'resources'. systemd[1]: Failed to start Celery Service. When I run the worker using celery -A profiles_project worker --loglevel=INFO celery runs as expected but shuts down when i log out of my server. Any help figuring out this error would be much appreciated as I am a complete beginner here. All relevant files are provided below: celery.conf # celery.conf CELERYD_NODES="w1" CELERY_BIN="/home/lynkup/usr/local/apps/profiles-rest-api/env/bin/celery" CELERY_APP="profiles_project" CELERYD_MULTI="multi" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_LOG_LEVEL="INFO" celery.service [Unit] Description=Celery Service After=network.target [Service] Type=forking User=lynkup Group=lynkup EnvironmentFile=/home/lynkup/usr/local/apps/profiles-rest-api/profiles_project/celery.conf WorkingDirectory=/home/lynkup/usr/local/apps/profiles-rest-api ExecStart=/bin/sh -c '${CELERY_BIN} -A ${CELERY_APP} multi start ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} -A ${CELERY_APP} multi restart ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target django settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'profiles_api', "push_notifications", ] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': … -
Microservices Architecture Using Django
We have a django-based web application which has a lot of features and deployed with uwsgi + nginx in a production-like environment. But our application is monolithic, so if something were to break all the features would be down. Is there any proper documentation/process to move to a microservices model ? Something to where we can have nginx point to certain views which would service as its own microservice. -
How to save tui image editor's editted image in django
I implemented TUI image editor in my Django Project so that I can manipulate images before uploading it to my project just like any other social media but I have faced two of the issues of which I can't find any specific answer anywhere: How can I upload this toast UI image editor's editted image on my django project? I can't change the text in the editor, it's take default sample text but I can't write some other text. Please If you'll tell me it'll be a huge help. I have attached my code below. index.html <html> <head> <meta charset="UTF-8"> <title>0. Design</title> <link type="text/css" href="https://uicdn.toast.com/tui-color-picker/v2.2.6/tui-color-picker.css" rel="stylesheet"> <link rel="stylesheet" href="https://uicdn.toast.com/tui-image-editor/latest/tui-image-editor.css"> <style> @import url(http://fonts.googleapis.com/css?family=Noto+Sans); html, body { height: 100%; margin: 0; } </style> </head> <body> <form action="uploadTemplate" method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="tui-image-editor-container"></div> <button class="btn btn-dark" type="submit" title="POST" id="submitPostMeme">Post</button> </form> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.0/fabric.js"></script> <script type="text/javascript" src="https://uicdn.toast.com/tui.code-snippet/v1.5.0/tui-code-snippet.min.js"></script> <script type="text/javascript" src="https://uicdn.toast.com/tui-color-picker/v2.2.6/tui-color-picker.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script> <script src="https://uicdn.toast.com/tui-image-editor/latest/tui-image-editor.js"></script> <!-- <script type="text/javascript" src="./js/theme/white-theme.js"></script> <script type="text/javascript" src="./js/theme/black-theme.js"></script> --> <script> // Image editor var imageEditor = new tui.ImageEditor('#tui-image-editor-container', { includeUI: { loadImage: { path: 'img/sampleImage2.png', name: 'SampleImage' }, // theme: blackTheme, // or whiteTheme initMenu: 'filter', menuBarPosition: 'bottom' }, cssMaxWidth: 700, cssMaxHeight: 500, usageStatistics: false }); window.onresize = … -
Turn Django Queryset into Filtered Dictionary
I am trying to work with the {% regroup %} template tag to display user made lists with items in them to look like this: LIST NAME Item Item Item Not this (which is the only way I can get it to render atm): List Name 1 Item 1 List Name 1 Item 2 List Name 1 Item 3 Based on my reading of the Django Docs I have to turn my queryset into a dictionary but I am having trouble achieving this. I also need to ensure my queryset if filtered based on the logged in user. I am getting errors depending on where I put the values() method, or it currently shows nothing at all... Here is my views.py @ensure_csrf_cookie def dashboard(request): return render(request, 'testingland/dashboard.html') class user_playlist(ListView): template_name = 'testingland/playlist.html' context_object_name = 'playlist' model = UserVenue def get_queryset(self): venue = self.request.GET.get('venue', None) list = self.request.GET.get('list', None) return UserVenue.objects.filter(list__user=self.request.user).values() Here is the models: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? def __str__(self): return self.list_name class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) And here is the template (I built it based on reading the Django Docs on regroup). <div class="user_playlists"> {% regroup … -
Django: How to render a specific HTML with context in an On Approve Ajax
In my Project after a Payment is made via PayPal I am trying to redirect it to an HTML page with certain context as per the following views: def payment_complete(request): body = json.loads(request.body) order = Order.objects.get( user=request.user, ordered=False, id=body['orderID']) payment = Payment( user=request.user, stripe_charge_id=body['payID'], amount=order.grand_total() ) payment.save() order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() messages.success(request, "Your Order was Successful ! ") return render(request, "order_completed.html", {'order': order}) <------------------------ I have tried adding but it took me the home while I am trying to go to an HTML that is created to show executed payment details // similar behavior as an HTTP redirect window.location.replace("/"); Also, I tried but it didn't work window.location.href = 'core:payment-complete'; Here is the full paypal on approve script onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(details); sendData(); function sendData() { fetch(url, { method: "POST", headers: { "Content-type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify({ orderID: orderID, payID: details.id }), }); } // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); // similar behavior as an HTTP redirect window.location.replace("/"); window.location.href = 'payment-complete'; }); } }).render('#paypal-button-container'); </script> -
Images Aren't Loading When Launching Website With Heroku. How Do I Fix This?
when I deploy *my heroku website everything loads up except my The Website Images you could see everything but it shows the images as errors I am not sure how to fix this I been stuck with this problem for almost 2 days if you know how to fix it please explain it to me so in the future I could go back and see this and fix my problem I literally have all the requirements for my website to be launched with heroku but I am not see the images at all my settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # remember to change to false ALLOWED_HOSTS = ['anim3-domain.herokuapp.com'] # 'https://anime-domain.herokuapp.com/' # Application … -
Iinsert or update on table "knox_authtoken" violates foreign key constraint "knox_authtoken_user_id_e5a5d899_fk_auth_user_id"
I'm building Crud API for my react and django project and I'm having some issues: django.db.utils.IntegrityError: insert or update on table "knox_authtoken" violates foreign key constraint "knox_authtoken_user_id_e5a5d899_fk_auth_user_id" DETAIL: Key (user_id)=(11) is not present in table "auth_user". So as I can see the user model is being created, but the AuthToken is not. How can I fix it? `AuthToken.objects.create(user)` NOTE - This line is raising the exception! My models.py: # Create your Winteka custom models here. class Users(AbstractBaseUser): public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) username = models.CharField(max_length=50, unique=True, null=False, blank=False) email = models.EmailField(max_length=100, unique=True, null=False, blank=False) profile_pic = models.ImageField(null=False, blank=False, default='def_profile_pic.png') password = models.CharField(max_length=128, null=False, blank=False) verified = models.BooleanField(null=False, blank=False, default=False) reports = models.ManyToManyField('main.UserReports', related_name='+') date_registered = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['public_id', 'email', 'profile_pic', 'password', 'verified', 'reports', 'date_registered'] My viewset.py: # Register Viewset class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) And my Serializer.py # Register Serializer class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = ('username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = Users( username=validated_data['username'], email=validated_data['email'], password=Users.create_password(None, validated_data['email']) ) user.save() return user I'm really … -
When i want to insert a new data into cartpaket table, i haved this error "Cannot assign "7": "CartPaket.toko_id" must be a "Toko" instance"
This is my Toko Table class Toko(models.Model): nama_toko = models.CharField(max_length=30) username = models.CharField(max_length=30) image_banner = models.ImageField(upload_to='toko') lokasi = models.CharField(max_length=30) deskripsi = models.CharField(max_length=30) status = models.CharField(max_length=30) boolean= models.BooleanField(default=0) def __str__(self): return self.username This is my Product Table class Produk(models.Model): nama_produk = models.CharField(max_length=30) gambar = models.ImageField(upload_to='produk') size = models.IntegerField(default=500) deskripsi = models.CharField(max_length=200) harga_resseler = models.IntegerField(default=0) harga_agen = models.IntegerField(default=0) harga_distributor = models.IntegerField(default=0) harga_retail = models.IntegerField(default=0) harga_hpp = models.IntegerField(default=0) **This is my CartPaket ** class CartPaket(models.Model): customer_name = models.CharField(max_length=30) harga = models.IntegerField() quantity = models.IntegerField(default=0) total_berat = models.IntegerField(default=200) subtotal = models.IntegerField(default=0) total = models.IntegerField(default=0) tanggal_pesan = models.DateTimeField(auto_now_add=True) kota_customer_id = models.IntegerField(null=True) kota_pelapak_id = models.IntegerField(null=True) toko_id = models.ForeignKey(Toko, verbose_name='toko', on_delete=models.CASCADE, default=1) produk_id = models.ForeignKey(Produk, verbose_name='produk', on_delete=models.CASCADE, default=1) def __str__(self): return self.customer_name This is my views.py if CartPaket.objects.filter(customer_name=get_user, produk_id=pro.id, toko_id=get_toko.id).exists(): cart = CartPaket.objects.get(produk_id=pro.id, customer_name=get_user, toko_id=get_toko.id) cart.quantity += jumlah cart.save() else: if jumlah != 0 or jumlah != '': barang_distributor = Barang.objects.get(produk_id=pro.id, toko_id=get_toko.id) cart = CartPaket(produk_id=pro.id, harga=barang_distributor.harga_jual, toko_id=get_toko.id, customer_name=request.user.username, quantity=jumlah, kota_customer_id=kota_customer_id, kota_pelapak_id=kota_pelapak_id) cart.total_berat = cart.quantity * cart.produk_id.size cart.subtotal = cart.harga * cart.quantity cart.save() This is post request information [1]: https://i.stack.imgur.com/OZhnU.png This is the error i haved [2]: https://i.stack.imgur.com/LYQja.png -
Django update a static csv file in background everyday at midnight
Hi I want to automatically update a static csv file in the background of my django web page every day at midnight, I tried setting a background task so that every day at midnight the file would update, and to test it I would change the schedule value to 1s just so I could see it happening faster but the task would never execute or at least I never saw anything printing in the google devtool nor in the comandline terminal, nor was there any change in modified date in the files properties my background task @background(schedule= abs(datetime.datetime.now() - datetime.datetime.now().replace(minute=0, second=0, hour=0))) def update(): print("in update") apiurl = 'https://api_im_downloading_from' jasonObject = requests.get(apiurl) parsed = json.loads(jasonObject.text) print("downloaded") file = open('boards/static/csv_files/file.csv', 'w+', newline='') df = pd.json_normalize(parsed) #store parsed jason in a panda data frame df.to_csv(r'boards/static/csv_files/file.csv', index=False) file.close() update() my settings.py file INSTALLED_APPS = [ 'boards.apps.BoardsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'background_task', ] when I don't use the @background and just call my method normally the server crashes, I also tried importing the schedule module and using schedule.every().day.at("0:0").do(update) #change time value to execute faster I also ran this in the commandline and nothing happened python manage.py process_tasks All I want is for … -
AttributeError at /profiles/using/14/ 'UserProfileDetailView' object has no attribute 'user'
I am trying to make follow toggle to work and I have put condition in templates and but in views I have having an issue. In templates {% if object.user in request.user.userprofile.follower.all %} this is returning true but in views if self.user in self.request.user.userprofile.follower.all(): this thing returning error 'UserProfileDetailView' object has no attribute 'user'. profiles/views.py class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): print(request.POST) user_to_toggle = request.POST.get('username') print(user_to_toggle) profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) user = request.user if user in profile_.follower.all(): profile_.follower.remove(user) else: profile_.follower.add(user) return redirect("/posts/list/") class UserProfileDetailView(DetailView): model = UserProfile template_name = "profiles/userprofile_detail.html" def get_context_data(self,*args, **kwargs): context = super(UserProfileDetailView,self).get_context_data(*args,**kwargs) is_following = False # print(user,'this is') # print(user.userprofile.follower.all()) if self.user in self.request.user.userprofile.follower.all(): is_following = True context["is_following"] = is_following return context profile.html {% extends 'base.html' %} {% block content %} <p style="text-align: center;"><img src="{{ object.user.userprofile.avatar.url }}" width = "50%"></p> {{ request.user.userprofile.follower.all }}<br> {{object.user.userprofile }} {% if object.user in request.user.userprofile.follower.all %} Following {% endif %} <p>{% include 'profiles/snippets/follow_toggle.html' with username=object.user is_following=is_following %}</p> <h2>{{ object.user.username }}</h2> /{{is_following}} {% endblock content %} -
django using object inside templates without using view
Im new to django; I'm using include inside a template that call another template like this {% include "cars_models.html" with user_id=request.user.id %} is there a way to use Cars.objects.get(user_id=request.user.id) or something like inside the cars_models template direct to get all cars are related to user_id without using views -
How to serialize a django model using serpy package
I'm trying to serialize the default User model using the serpy package but no success. Serializers class GroupSerializer(serpy.Serializer): id = serpy.IntField(required=True) name = serpy.StrField(required=True) class UserSerializer(serpy.Serializer): id = serpy.IntField(required=True) email = serpy.StrField(required=True) username = serpy.StrField(required=True) groups = GroupSerializer(many=True, attr="groups.all", call=True) I use model viewsets for both serializers; like so class UserViewset(...): queryset = get_user_model().objects.all() serializer_class = UserSerializer I followed this Github issue https://github.com/clarkduvall/serpy/issues/17 and now I get 'NoneType' object has no attribute 'id'. I then tried class UserSerializer (..): id = serpy.MethodField() def get_id(self, user): return user.id Yet same error! It seems the user object isn't properly gotten. The same error for the groups. I've tried dropping the required=True, but nothing. -
django custom command based on python script
I'm trying to create a custom command for django that can be run with python manage.py cert_transparency and i'm almost there but i'm having a little trouble. The purpose of this one is to create a 24/7 running command in the background which I just run in a docker container. I'm receiving this error message certificate_update: 0cert [00:00, ?cert/s]Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/src/scraper/management/commands/cert_transparency.py", line 184, in handle certstream.listen_for_events(callback, url=certstream_url) NameError: name 'callback' is not defined Basically what i'm trying to do is just import this script as a custom management command in django. cert_transparency.py: from django.core.management.base import BaseCommand, CommandError import re import math import certstream import tqdm import yaml import time import os from Levenshtein import distance from termcolor import colored, cprint from tld import get_tld from .confusables import unconfuse class Command(BaseCommand): help = 'Scrapes calidogs websocket for cert renewals and rates them.' def score_domain(self, domain): """Score `domain`. The highest score, the most probable `domain` is a phishing site. …