Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. … -
OperationalError at ... no such column: funcionarios_funcionario.user_id
I am a newbie in Django and I am facing a problem. I am getting this message in the console: django.db.utils.IntegrityError: The row in table 'funcionarios_funcionario' wi th primary key '1' has an invalid foreign key: funcionarios_funcionario.empres a_id contains a value '1' that does not have a corresponding value in empresa_ empresa.id. and when I run the app, I got this message OperationalError at /admin/documentos/documento/add/ no such column: funcionarios_funcionario.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/documentos/documento/add/ Django Version: 3.1.2 Exception Type: OperationalError Exception Value: no such column: funcionarios_funcionario.user_id the class documentos from django.db import models from apps.funcionarios.models import funcionario # Create your models here. class Documento(models.Model): descricao = models.CharField(max_length=100) pertence = models.ForeignKey(funcionario, on_delete=models.PROTECT) def __str__(self): return self.descricao the class funcionarios from django.db import models from django.contrib.auth.models import User from apps.departamentos.models import Departamento from apps.empresa.models import Empresa class funcionario(models.Model): nome = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.PROTECT) departamentos = models.ManyToManyField(Departamento) empresa = models.ForeignKey(Empresa, on_delete=models.PROTECT) def __str__(self): return self.nome How I can solve this? Thank you very much! -
wsgiref exception 'NoneType' object has no attribute 'split' when opening a file from media folder
When I open a file from media folder, I keep getting this exception from wsgiref 'NoneType' object has no attribute 'split' urls.py path('media/<file_id>/', views.media), views.py def media(request, file_id): file = get_object_or_404(File, id=file_id) file = file.file return FileResponse(file, as_attachment=False, filename=file.name) models.py class File(models.Model): id = models.AutoField(primary_key=True) file = models.FileField(null=False, blank=False, upload_to='media') belongs_to = models.ForeignKey('Content', null=False, blank=False, on_delete=models.CASCADE) date = models.DateTimeField(null=False, blank=False, auto_now_add=True) @property def filename(self): return os.path.basename(self.file.name) I also noticed that it only shows for mp4 and mp3 mp4 : The error keeps showing in an infinite loop mp3 : The error shows one time only Does anyone have an explanation to this ? Any help would be appreciated. -
Django get pk inside of decorator
Imagine the following pseudo code at decorators.py where you need the actual pk of the object where this decorator get placed onto: def count_view(function): def wrap(request, *args, **kwargs): pk = ('??? Missing ???') user = get_user_model().objects.get(pk=request.user.pk) hit_objects = Hit.objects.filter(viewer=user, content_object=pk) if hit_objects: return function(request, *args, **kwargs) else: new_hit = Hit.objects.create(viewer=user, content_object=pk) new_hit.save() return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap How can I access the objects pk I'm placing this decorator on? e.g. @count_view def PostDetail(request, pk): post = get_object_or_404(Post, pk=pk) ... -
DoesNotExist at /profiles/user-profile/ UserProfile matching query does not exist
I am trying to add a follow toggle but In my views I am getting error in matching query set. The userprofile exist in database than still I dont why is it happening. I hope you guess can figure out my mistake and tell me how can I fix it. I am learning django if you help me than that means a lot. I shall be thankful to you. if more code required for help than let me know i will share that. 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/") trace back Environment: Request Method: POST Request URL: http://127.0.0.1:8000/profiles/user-profile/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, … -
When I am defining the URL patterns in django version 2.1.4 , I am getting an error. please show me a path
enter code hereError on running the project from CMD: enter code herepath('about/',views.about), enter code hereAttributeError: module 'testapp.views' has no attribute 'about' enter code hereURLs.py: enter code herefrom django.contrib import admin enter code herefrom django.urls import path enter code herefrom testapp import views enter code hereurlpatterns = [ enter code herepath('about/',views.about),] enter code hereview.py enter code herefrom django.shortcuts import render enter code herefrom django.http import HttpResponse enter code heredef about(request): enter code heres=" This is an about page" enter code herereturn HttpResponse(s) -
Calling view name that belongs to a different app
I am trying to a similar task as in this thread here : calling a view when a button is clicked. However, the view name that the button is calling belongs to a different app. <button class="button table_mgt" > <a href="{% url 'table_view' %}">Table Mgt</a> </button> This button sits in a template called dashboard.html which belongs to an app called account. But the view named table_view belongs to another app called table. Both apps belong to the same root. What do I need to set up for the above code to work? -
Testing CSRF protecting views in Django Rest Framework
I was hitting a wall when it comes to testing my APIViews that require authentication. I wanted to test that both CSRF and authentications + permissions were enforced as expected. Some information of my setup: My view is a Django Rest Framework rest_framework.views.APIView which implements the post function. Default authentication classes are SessionAuthentication Default permission classes are IsAuthenticated Test cases use the APIClient to issue requests When initializing the APIClient with enforce_csrf_checks=True I still can't seem to get the response I'm expecting when it comes to views that require authentication (using the IsAuthenticated permission class). For non-authenticated views, I can test CSRF protection, no problem. The view in question: @method_decorator(csrf_protect) def post(self, request, format=None): """ Create a new user. """ serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The test code: client = APIClient() response = client.post(url, data) # Success! client = APIClient(enforce_csrf_checks=True) response = client.post(url, data) # 403 FORBIDDEN For authenticated views, things get weird (this view uses the IsAuthenticated permission: def get(self, request, format=None): """ Get request user. """ user = User.objects.get(pk=request.user.id) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) The test code: self.client = APIClient(enforce_csrf_checks=True) self.client.login(email='t@t.se', password='pw') self.client.get(url) # Succeeds, even though it should not. … -
Celery doesn't work with Django on Heroku. Getting `Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused` error
I can't seem to get Celery to work with Django using Heroku. I've tried many different combinations of fixes over the past two days and can't seem to get it done. The error that I'm getting is this [2020-10-10 22:29:25,246: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. I use a heroku add-on called Redis Cloud for redis, (hence the celery settings using REDISCLOUD_URL as an environment variable. I'm basically at a complete loss on what to do at this point as I've looked at many tutorials, stackoverflow questions, etc. Thank you. Here is my complete set up. . ├── LICENSE ├── Pipfile ├── Pipfile.lock ├── Procfile ├── README.md ├── manage.py ├── runtime.txt ├── static │ └── README.md └── wowzers ├── __init__.py ├── celery.py ├── settings.py ├── urls.py └── wsgi.py __init__.py file in wowzers/ from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ("celery_app",) celery.py file in wowzers/ from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wowzers.settings") app … -
DJANGO ORM vs JUPYTERLAB.. can you do the same in ORM vs JupyterLab?
i want to analyse in Pandas/Numpy/MatPlotLib my sales in a project/site. can i do the same analysis in ORM vs JupyterLab? (im using SQLite3) which do you prefer? if not, how do i use the SQLITE DB from that project, in a JupyterLab project??? -
How can I program a dynamic sitemap in django, mine not working
The static part works fine but the dynamic posts of my blog app are not generated from django.contrib.sitemaps import Sitemap from django.urls import reverse from .models import Post class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.9 def items(self): return Post.objects.all() I'm not able to get a dynamic sitemap with my blog and my Post class in models: class Post(models.Model): title=models.CharField(max_length=100) header_image = models.ImageField(null=True , blank=True, upload_to="images/") title_tag=models.CharField(max_length=100) author= models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(extra_plugins= ['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')]) #body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=50, default='uncategorized') snippet = models.CharField(max_length=200) likes = models.ManyToManyField(User, blank=True, related_name='blog_posts') def total_likes(self): return self.likes.count() class Meta: verbose_name = "Entrada" verbose_name_plural = "Entradas" ordering = ['-post_date'] def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') If any one can help me I would be very grateful. urls.py: from django.contrib.sitemaps.views import sitemap from theblog.sitemaps import PostSitemap, StaticSitemap sitemaps = {'static': StaticSitemap, 'blog': PostSitemap}