Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist at /appname/: deploying on heroku
I have deployed a Django app on heroku. When I visit the url for that app, I get a 'TemplateDoesNotExist at /appname/' error. However, when I run this app locally using heroku local, it runs perfectly. User@Users-MacBook-Air reponame % git status On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean User@User-MacBook-Air reponame % git push heroku master Everything up-to-date My working tree is clean and my local master branch corresponds to my heroku remote master branch. This means that the code I have locally is the code that is also present on the heroku servers. The exact Django error message I get is: TemplateDoesNotExist at /appname/ appname/Landing.html Request Method: GET Request URL: https://urlname.herokuapp.com/appname/ Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: appname/Landing.html Exception Location: /app/.heroku/python/lib/python3.8/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python38.zip', '/app/.heroku/python/lib/python3.8', '/app/.heroku/python/lib/python3.8/lib-dynload', '/app/.heroku/python/lib/python3.8/site-packages'] Server time: Thu, 15 Oct 2020 11:41:58 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/templates/appname/Landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/templates/appname/Landing.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/beergame/templates/appname/Landing.html (Source does not exist) The view code that renders the above page is as … -
Is it possible to access the user's filesystem and perform CRUD operations on his filesystem using django or node.js?
I want to access the filesystem of the client , and delete some files from his system. is it possible for me to make any website which can perform such task? if yes using what we can perform these? Django?Node.js? or anything else? if not can i perform the same using any other method? like API etc? thanks in advance. -
Django order by multiple related fields
I have a User and Credits model. Every User has a related Credits object. I want to rank/order a list of Users based on multiple fields in the Credits object: credits (amount) games_played_count (amount) last_game_credits (amount) Hence, if two players have an equal amount of credits the one with the highest games_played_count wins. If that is the same the one with the highest last_game_credits wins. Models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = NameField(max_length=25, unique=True) class Credits(models.Model): credits = models.IntegerField(default=1000) year = models.IntegerField(default=date.today().isocalendar()[0]) week = models.IntegerField(default=date.today().isocalendar()[1]) games_played_count = models.IntegerField(default=0) last_game_credits = models.IntegerField(null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="credits", on_delete=models.CASCADE) class Meta: unique_together = ('year', 'week', 'user') View: class RankingListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = RankingsSerializer def get_queryset(self): year = self.request.query_params.get('year', None) week = self.request.query_params.get('week', None) if week and year is not None: prefetchCredits = Prefetch('credits', queryset=Credits.objects.filter(year=year, week=week)) rankings = User.objects.prefetch_related(prefetchCredits) return rankings What I've tried: rankings = User.objects.prefetch_related(prefetchCredits).order_by('-credits__credits', 'credits__games_played_count', 'credits__last_game_credits ) This gives me duplicates. If I remove the duplicates by iterating through the list the ordering on the last 2 fields doesn't work. rankings = User.objects.prefetch_related(prefetchCredits).annotate(creds=Max('credits__credits')).annotate( gcount=Max('credits__games_played_count')).annotate( lgcount=Max('credits__last_game_credits')).order_by('-creds', '-bcount', '-lgcount) Does not give duplicates but ordering on the last 2 fields doesn't work. class Meta: ordering = ['-credits__credits', '-credits__games_played_count', … -
how to display grouped items in django templates?
I have a django template below: {% regroup budget.productitem_set.all by group_id as grouped_product_list %} {% for entry in grouped_product_list %} {% for item in entry.list %} <tbody> <tr> <td>{{ item.description }}</td> <td>{{ item.quantity }}</td> <td>{{ item.group_id }}</td> </tr> </tbody> {% endfor %} {% endfor %} What ends up happening: ID QUANTITY GROUP_ID test123 23 1 test123 24 1 What output I would like ID QUANTITY GROUP_ID test123 23 1 24 -
Show cutomize message in Django Admin on delete of a record
I am trying to change the default error message of django admin to my own message app that should display like a normal message system here is my model for the app class Role(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(null=True, unique=True, blank=False) def __str__(self): return self.name in on other model this model become the forighn key. here is the second model class LearningPath(models.Model): Path_Name = models.CharField(max_length=500) Role = models.ForeignKey(Role, on_delete=models.DO_NOTHING) after that, I have created some roles and then some Learning Paths. the issue is that I when I delete any of Role that is used inside any of Learning Path it shows me the below error what I want is to show the error message in a normal message app as the normal alert div appear. I have tried to write some code in admin.py but it's not working. here is admin.py code class RoleAdmin(admin.ModelAdmin): list_display = ('name',) prepopulated_fields = {'slug': ('name',)} list_per_page = 20 def delete_model(self, request, obj): try: obj.delete() except IntegrityError: messages.error(request, 'This object can not be deleted!') admin.site.register(Role, RoleAdmin) -
Update Quantity and Update Cart Django
Cart View before Checkout def cart_view(request): #for cart counter if 'product_ids' in request.COOKIES: product_ids = request.COOKIES['product_ids'] counter=product_ids.split('|') product_count_in_cart=len(set(counter)) else: product_count_in_cart=0 # fetching product details from db whose id is present in cookie products=None total=0 if 'product_ids' in request.COOKIES: product_ids = request.COOKIES['product_ids'] if product_ids != "": product_id_in_cart=product_ids.split('|') products=models.Product.objects.all().filter(id__in = product_id_in_cart) #for total price shown in cart for p in products: total=total+p.price return render(request,'ecom/cart.html',{'products':products,'total':total,'product_count_in_cart':product_count_in_cart}) Products Model class Product(models.Model): name=models.CharField(max_length=40) product_image= models.ImageField(upload_to='product_image/',null=True,blank=True) price = models.PositiveIntegerField() description=models.CharField(max_length=40) def __str__(self): return self.name I want that in cart page there will be a field which will take "Integer Input " and Update the Total Price Present Cart View Image How i Want I am new and trying and learning so please help me to sort this out Will i need any new model or views ? Thank You -
To convert code from DJANGO SQLite to MYSQL
Have a look at this code : w_in=appnav_dev_report.objects.filter(Q(de_manager=m),Q(date=day),Q(severity='1') | Q(severity='2') | Q(severity='3'),Q(type='incoming')) This code is currently in Django Sqlite format. I need to convert it into MYSQL format. So how to make changes ?? -
How more Foreign Key works in django
I would like to better understand how ForeignKey works in django, how can I refer field1 with barcode and field2 with job? class User(AuditModel): barcode = models.CharField(max_length=10, unique=True, default="not_specified", null=True, blank=True") name = models.CharField(max_length=100, unique=True, null=False, blank=False) surname = models.CharField(max_length=100, null=False, blank=False) job = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return str(self.barcode) class Test_table field1 = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name="fields1") field2 = models.ForeignKey(User, max_length=100, unique=True, blank=True, null=True, on_delete=models.CASCADE, related_name="fields2")``` Thanks -
Automatically Update Profile Picture in Django
I have written a command which reads a csv file and creates 50+ users at once. Also, I have downloaded a bunch of avatars that I plan to assign randomly to each user. This is where the problem occurs. I have written the code below which assigns a random image as the default image to each user. models.py def random_image(): directory = os.path.join(settings.BASE_DIR, 'media') files = os.listdir(directory) images = [file for file in files if os.path.isfile(os.path.join(directory, file))] rand = choice(images) return rand class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatars', default=random_image) def save(self, *args, **kwargs): # check model is new and avatar is empty if self.pk is None and self.avatar is not None: self.avatar = random_image super(UserProfile, self).save(*args, **kwargs) However, the code seems to run only when the user uploads a picture which is not what I desire. What I want is once the user is logged it, the model should check if it has an avatar and if not, to assign a random image. So, my questions are these: How can I implement this? Because the system keeps checking this after each log in, it seems to me that it is a little inefficient. To replace this strategy, … -
RelatedObjectDoesNotExist at /profiles/user-follow-feed/ User has no user
Well i am just trying to show feed back of the following users but got an error:RelatedObjectDoesNotExist at /profiles/user-follow-feed/ User has no user. I don't understand how can i fix it. Need help to fix it out. many thanks in advance. views.py class FolloweHomeView(View): def get(self, request, *args, **kwargs): user = request.user.userprofile is_following_user_ids = [x.user.id for x in user.follower.all()] qs = Post.objects.filter(username__id__in=is_following_user_ids).order_by("-create_date")[:3] return render(request, "profiles/follower_home_feed.html", {'object_list': qs}) models.py class ProfileManager(models.Manager): def toggle_follow(self, request_user, username_to_toggle): profile_ = UserProfile.objects.get(user__username__iexact=username_to_toggle) user = request_user is_following = False if user in profile_.follower.all(): profile_.follower.remove(user) else: profile_.follower.add(user) is_following = True return profile_, is_following class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/user-follow-feed/ 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", … -
How to use Django rq + wkhtmltopdf?
Asynchronous worker using wkhtmltopdf generate PDF from HTML template, how to do this? HTML template available Please write an example of such code and how to insert it into the ListView -
Wagtail: wrong filepath when I compile the project
I am trying to upgrade Wagtail from 1.13 to 2.0 and I get this error when trying to migrate: RuntimeError: Model class wagtail.wagtailcore.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. And log is: [...] File "C: \ Program Files \ Python36 \ lib \ site-packages \ wagtail \ wagtailcore \ blocks \ field_block.py", line 16, in <module> from wagtail.wagtailcore.rich_text import RichText File "C: \ Program Files \ Python36 \ lib \ site-packages \ wagtail \ wagtailcore \ rich_text.py", line 10, in <module> from wagtail.wagtailcore.models import Page File "C: \ Program Files \ Python36 \ lib \ site-packages \ wagtail \ wagtailcore \ models.py", line 54, in <module> class Site (models.Model): File "C: \ Program Files \ Python36 \ lib \ site-packages \ django \ db \ models \ base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class wagtail.wagtailcore.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have previously installed everything necessary for the update and I have passed the script to rename the changed fields. In the log you can see that the path that should point to the core actually points to the old version (wagtailcore) … -
I want to write this code using MySQL. It is now in sqlite
w_in=appnav_dev_report.objects.filter(Q(de_manager=m),Q(date=day),Q(severity='1') | Q(severity='2') | Q(severity='3'),Q(type='incoming')) -
Django custom forms Dynamic Raw Id
I have a table with a foreign key. My problem is that ther's a lot of registers, so I need do that: But all I've found was for the Admin Panel. Any idea for a custom form without admin? -
No Python at ...\AppData\Local\Programs\Python\Python38-32\python.exe
I keep getting the below error No Python at 'C:\Users\Arianda Basil\AppData\Local\Programs\Python\Python38-32\python.exe' I have reinstalled Python many times over and added it to PATH but no change. Here is the PowerShell view -
i want to acces static file js and css from my folder django not from aws
I am using django with aws now i have one problem all files come from aws even my js and css i want to use these file my folder right now i have these setting regarding my aws in my setting.py How can i do this? STATICFILES_DIRS = ['static'] STATIC_URL = '/static/' agents aws AWS_ACCESS_KEY_ID = '*********************' AWS_SECRET_ACCESS_KEY = '*********************' AWS_STORAGE_BUCKET_NAME = 'agents' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' MEDIAFILES_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' ---using in temp--- <link href="{% static 'css/my_style.css'%}" rel='stylesheet'> css i don't want this <link href="https://agents-docs-django.s3.amazonaws.com/static/css/my_style.css" rel='stylesheet'> i want this <link href="/static/css/my_style.css" rel='stylesheet'> -
Bootstrap cards are overlapping when I am using for loop in Django
I am facing issue in displaying Bootstrap cards. Cards are overlapping when I am using for loop in Django. Can anyone please help? Here is the code: enter image description here -
Django Celery getting pickling error on throwing custom exception
I'm using celery in a django application. In case of a failure I raise a custom exception, which is defined with this class: class CustomException(Exception): def __init__(self, err_input, err_info=''): self.err_key, self.err_msg, self.app_domain = err_input self.message = self.err_msg super(CustomException, self).__init__(self.message) self.err_info = err_info def __str__(self): return '[{}] {}'.format(str(self.err_key), str(self.err_msg)) def __repr__(self): return self.message the error_info is used for an internal logging purpose. If I throw the message I get in the related celery task: { "task_id": "0dfd5ef3-0df1-11eb-b74a-0242ac110002", "status": "FAILURE", "result": { "exc_type": "MaybeEncodingError", "exc_message": [ "'PicklingError(\"Can\\'t pickle &lt;class \\'module.CustomException\\'&gt;: it\\'s not the same object as module.CustomException\")'", "\"(1, &lt;ExceptionInfo: CustomException('Error message')&gt;, None)\"" ], "exc_module": "billiard.pool" }, "traceback": null, "children": [] } what am I misconfiguring in my exception class? -
Django button GET request with ajax
Its my button : <form action="{% url 'panel:lights' %}" method='GET'> {% csrf_token %} <button class="btn" type='submit' onclick=mybtn() >ON</button> </form> its my urls.py : app_name = 'panel' urlpatterns = [ path('panel', views.panel_views , name = 'panel'), path('light', views.light_views , name = 'lights'), its my views.py : def light_views(request): print ("finally worked") Device.objects.all() device = Device.objects.get(id=1) device.status = not device.status device.save() return redirect(request , 'panel/panel.html') and the error i get when i click button is : Reverse for '<WSGIRequest: GET '/panel/lightcsrfmiddlewaretoken=eIQ9rKiLaTvmOqMtXAoi9J1YcuOgEEtuaAlkV67hMk8iYZsXlEahyd7E62g5eXWu'>' not found. '<WSGIRequest: GET '/panel/light?csrfmiddlewaretoken=eIQ9rKiLaTvmOqMtXAoi9J1YcuOgEEtuaAlkV67hMk8iYZsXlEahyd7E62g5eXWu'>' is not a valid view function or pattern name. and the ajax code i used and it seems its wrong is : <script> function mybtn() { var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","{% url 'panel:light' %}", true); xhttp.send(); }; </script> -
JSON from Django render() to React.js
I'm writing a simple Django + React Application in which I want to pass some JSON from Django render() to React.js. I first render an HTML page with Django, providing the JSON. Although I'm unaware of the format, the data is coming through, as I can show it using Django's template language. However, in the React code, which is called by the HTML page, I get the JSON as a string, and only the first 10 chars. I'm wondering whether there is a way to get this through properly, instead of having to write an http post every time. My Django views script, which renders the html: @login_required(login_url="/login/") def index(request): data = { 'key': [0, 1, 2, 3], 'key2': 'abcd', } context = { 'data': json.dumps(data), 'navItem': 0, } return render(request, "index.html", context) My index.html: <!DOCTYPE html> <html lang="en"> <body> {{data}} <div class="reactitem" data-json={{data}}></div> <script src="http://127.0.0.1:8080/index.js" charset="utf-8"></script> </body> </html> And lastly my index.js (locally hosted): document.querySelectorAll('#reactitem').forEach((domContainer) => { console.log(domContainer.dataset.json); console.log(typeof(domContainer.dataset.json)); console.log(domContainer.dataset.json.length); }) When I load the page, I see the full data json on screen while getting the following output in the console: {"key": string 7 -
The build_absolute_uri function always generates url with the http protocol
The build_absolute_uri function of the request object generates a url with the http protocol, although the url with the https protocol is obviously. Is it possible to somehow force the generation of a security protocol? -
Plugin caching_sha2_password could not be loaded: /mariadb19/plugin/caching_sha2_password.so: cannot open shared object file
I am trying to dockerise my Django app. docker-compose.yml version: "3.8" services: db: image: mysql:8 command: --default-authentication-plugin=mysql_native_password # this is not working restart: always environment: MYSQL_ROOT_PASSWORD: rootmypass ports: - '3306:3306' cache: image: redis environment: REDIS_HOST: localhost REDIS_PORT: 6379 ports: - '6379:6379' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - cache When I run docker-compose -up, I get the following error. django.db.utils.OperationalError: (1156, 'Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory') Upon searching, I found the solution was to use command: --default-authentication-plugin=mysql_native_password or downgrade mysql. Tried the first command but it's not working. I don't want to downgrade as well. How do I get it to work? -
React-input-range dosen't displayed after build
I have seek bar component witch based on React-input-range <> <CurrentTimeWrapper> <CurrentTime/> </CurrentTimeWrapper> <SeekBarInput> <InputRange step={0.1} maxValue={duration} minValue={0} value={currentTime} onMouseDown={this._handleMouseDown} onMouseUp={this._handleMouseUp} onChange={this._handleChange} classNames={ DEFAULT_CLASS_NAMES } /> </SeekBarInput> </> After I build react app and add it in django code like: <script src="{% static "vsh25-biopro/static/js/2.ab2cb7d8.chunk.js" %}"></script> <script src="{% static "vsh25-biopro/static/js/main.27fe58ec.chunk.js" %}"></script> But when I check in Django, Seek bar dosen`t displayed. And I dosen't know any reason why it hapend. -
How to store and print array value from json object in postgresql?
Here i need to extract only skill and store in 'skill_s' variable for further processing. How can i achieve this? DO $do$ DECLARE skill_s Text[]; jsonObject json = // Json object '{ "Name": "bala Kala", "Education": "B.Tech", "Skills": ["enim", "aliquip", "qui"] }'; BEGIN SELECT jsonObject::TEXT[]->'Skills' into skill_s; raise info 'JSON value Name is %', skill_s; END $do$ I want to print the output enim, aliquip, qui -
Is there a way to have "parallel" for loop in Django template tags?
So I have two models : Question and Answer, like below: class Question(models.Model): number = models.IntegerField(primary_key=True) question = models.CharField(max_length = 100, blank=False, default="") class Answer(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE, null=True) number = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) answer = models.CharField(max_length = 100, blank = False, default="") And what I want to do is display all questions and each corresponding answers. Like this: Q1. This is the first question A1. This is this user's first answer. Q2. This is the second question A2. This is this user's second answer. And so on.. So I have my view like this: def questionsAndAnswers(request): thisUser = User.objects.get(authuser_id=request.user.id) answers = Answer.objects.filter(authuser_id=request.user.id) questions = Question.objects.filter(authuser_id=request.user.id) context = { 'thisUser' : thisUser, 'answers': answers, 'questions' : questions, } return render(request, 'main.html', context) AND NOW I'M STUCK. Apparently, I cannot have two nested for loops, like below (simplifed): ... {% for q in questions %} {% for a in answers %} <div>Question : {{q.question}}</div> <div>Answer : {{a.answer}}</div> {% endfor %} {% endfor %} So I was wondering if there's a way to have "parallel" for loops in the template. How do I do this? I very much appreciate your help in advance. :)