Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Issue: cannot execute binary file: Exec format error
/home/linuxbrew/.linuxbrew/bin/heroku: line 45: /home/linuxbrew/.linuxbrew/opt/heroku-node/share/node: cannot execute binary file: Exec format error i was trying to login with Heroku, but it returned this error. My app is a basic and barebones django app with no frameworks or even static files loaded in. My virtualenv is working fine, and my server has run correctly. This problem persists everywhere in my system also. -
Using django-smart-selects, Empty ChainedForeignKey In Admin When Editing
I'm using django-smart-selects in django project. I'm using ChainedForeignKey in 'Country'. when adding new record, it works fine: selected 'Continent' then Chained 'Country' appeared. BUT while editing this record, 'Country' shows empty value. Any idea for this? -
How to create a query function that will set a dynamic variable foreach selected column PART 2
So in the last question How to create a query function that will set a dynamic variable foreach selected column with the help of community, finally i can get to make a query function that can set variable dynamically foreach selected column, but there is new problem where when i try to select all , for example select * from auth_user , it will list the "*" element , not all the columns in auth_users, how can i do this? views.py def list_all_data(request): import cx_Oracle data_names = request.GET.get('name').split(',') #resulting getting the "*" value table_name = request.GET.get('table',1) column_name = request.GET.get('column',1) data_name_name = ','.join(data_names) #print(data_name_name) operator = request.GET.get('operator',1) #print(operator) condition = request.GET.get('condition',1) #print(condition) #print(column_name) dsn_tns = cx_Oracle.makedsn('10.20.214.198', '1527', sid='dicb') conn = cx_Oracle.connect(user=r'icb', password='devicb', dsn=dsn_tns) c = conn.cursor() c.execute("select "+data_name_name+" from "+table_name) #select * from table_name print(c) c.rowfactory = makeDictFactory(c) columnalldata = [] for row in c: columnalldata.append([row[data_name] for data_name in data_names]) #the problem is here it will list * in data_names , not all the column selected #print(columnalldata) context = { 'obj4' : columnalldata, 'columnnames' : data_names # 'column_name' : columnallname } return render(request,'query_result.html',context) -
How do I get Django to load my favicon from my React build directory?
I am using Django and React to create a web application. When it comes to my React Development server, my favicon.ico loads like it should, but when I build my files, my Django development server doesn't find and render my favicon, and I have no idea why. I've tried renaming my favicon and changing the file type to .png. When I put my favicon into my static directory, and change the file name from favicon to some thing like "icon.ico", then it loads properly. But, I can't have my favicon in my static directory because CRA won't copy it into that directory when it builds. It's probably something small and simple so I'll show y'all all of the related files. Thanks for any insight! The import in my build/index.html: <link rel="shortcut icon" type="image/x-icon" href="./favicon.ico"/> urls.py from django.contrib import admin from django.urls import include, path, re_path from django.conf.urls import include, url from backend import views from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('backend.urls')), path(r'^api/<int:pk>$', include('backend.urls')), path(r'^api/<int:pk>$/', include('backend.urls')), url(r'^.*$', views.index), ] my settings.py static settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(FRONTEND, 'build/static/'), ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) Also, let me know if the problem could be in … -
Is wagtail cms keeping the list filters like django admin?
In django admin, I seach something in instances list page, the filters will be kept to next page by _changelist_filters, and is uesed to do the previous filter after saving, then I can edit the other instances that match the conditions. Can wagtail cms do the same thing? After I saving an instance, there is only an notify about the instance saved successfully, but the filters are missing. -
Website returns 500 error when Debug is switched to False in Django Heroku application
I have a Django app hosted on Heroku. Everything works perfectly when the debug is set to true however when I set the debug to false it returns a 500 error. I'm very sure this has something to do with how I'm rendering my static files. My app can't seem to find my static files when in production. urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('', include('moderator.urls')), path('accounts/', include('allauth.urls')),] handler404 = main_views.error_404 handler500 = main_views.error_500 if settings.DEBUG: urlpatterns +=static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's everything in my application that regarding static file storeage(I also set up amazon s3 to handle user uploads): STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_BUCKET', '') AWS_QUERYSTRING_AUTH = False AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com' AWS_DEFAULT_ACL = None #static media settings STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' MEDIA_URL = STATIC_URL + 'media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = 'staticfiles' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Any help would … -
django rest framework parser returns before all statements are executed
I am using django and django-rest-framework at the latest versions available on the stable channel on pipy - though, the issue is reproducible on older codebases (django version 2.x) as well. The issue is when I try to define a custom parser (as per here) and an example that illustrates the issue is shown below: class JSONCustomParser(JSONParser): def parse(self, stream, media_type=None, parser_context=None): data = super(JSONCustomParser, self). \ parse(stream, media_type, parser_context) try: # these are executed normally a = 1 b = 2 # problematic bits: un-comment either of these and execution ends early. # data = json.load(stream.read()) # data = json.load("{}") # data = JSONParser().parse(stream) # auth_name = str(parser_context['request'].auth.application) # sample commands not executed if they are *after* the above and either if them is # un-commented a = a + a b = a + 2 except ValueError: log.error("Value error") else: return data I assume the two stream consume operations force a return, although not too sure since the stream is consumed by JSONParser anyway in the super call... However, I am not certain why the others pose an issue... -
Django request list of objects
I am trying that when the user logs in, run a function that gets the number of objects (Count) from the Rating and puts them separately in Purchased.quantity_rated, according to their collection. All books have a purchase collection, although models Rating and Purchase are not directly linked with a ForeignKey. I am beginner with django and have no idea how to do that. rating/models.py class Rating(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) book = models.ForeignKey(Book, on_delete=models.CASCADE, null=False) rating = models.IntergerField(default=0) book/models.py class Books(models.Model): collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING, blank=True, null=True) book = models.CharField(max_length=250, blank=True, null=True) collection/models.py class Collection(models.Model): title = models.CharField(max_length=50) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) purchased_collections/models.py class Purchased(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING) date = models.DateTimeField(default=datetime.now) quantity_rated = models.IntegerField(default=0) -
Scrapy Mongodb duplicate key error E11000 pymongo.errors.DuplicateKeyError: E11000
I m a newbie to python, django, scrapy and mongodb What i am trying to do? Trying to persist data from scrapy to a mongodb collection created via django. So scrapy can read the data from this collection and display on a page. What have i done so far? Model in django class Project(models.Model): title = models.CharField(max_length=100) desc = models.CharField(max_length=100) urls = models.CharField(max_length=100) upon migration of the project following 0001_initial.py was generated, meaning django auto generated the field 'id' # Generated by Django 2.2.8 on 2019-12-27 03:09 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('desc', models.CharField(max_length=100)), ('urls', models.CharField(max_length=100)), # ('image', models.FilePathField(path='/img')), ], ), ] Following is my spider, pipeline.py file class ProjectspiderPipeline(object): def __init__(self): self.conn = pymongo.MongoClient('localhost', 27017) db = self.conn['djangodb'] #self.collection = db['spiderCollection'] self.collection = db['projects_project'] def process_item(self, item, spider): self.collection.insert(dict(item)) return item This is my items.py import scrapy class ProjectspiderItem(scrapy.Item): _id = scrapy.Field() title = scrapy.Field() desc = scrapy.Field() url = scrapy.Field() Now when i try to run it my spider with self.collection = db['spiderCollection'] in my pipelines. It runs successful. However when i change the collection to … -
How to use SetPasswordForm in a FormView
I am using Django's own SetPasswordForm() form class so I can allow a user to reset a password without providing their old one. My view is below: class UserSetPassword(FormView): template_name = 'accounts/users/user_set_password.html' form_class = SetPasswordForm success_url = reverse_lazy('user_list') def form_valid(self, form): form.save() messages.success(self.request, 'Initial password set') return super(UserSetPassword, self).form_valid(form) However this results in the error: TypeError at /users/set_password/ __init__() missing 1 required positional argument: 'user' Where am I going wrong? -
AngularJS and Django: :8000/uploaded_file:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I am trying to pass a file from my front-end (AngularJS) to my back-end(Django). It was working well yesterday, but however, when I logged in today, I will have this error that says: :8000/uploaded_file:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error). Multiple attempts I've got different Internal server error. Error 1: Error 2: .html: <body ng-app="myApp" ng-controller="appCtrl"> <input type="file" id="file" name="files" accept="text/*" data-url="file" class="inputfile_upload" select-ng-files ng-model="uploadedFile"/> <label for="file"> <span id="chooseFile"></span>Upload a file!</label> <button id="submitBtn" type="submit" ng-click="upload()">Upload</button> </body> directive.js: app.directive("selectNgFiles", function($parse) { return { require: "ngModel", link: function postLink(scope,elem,attrs,ngModel) { elem.on("change", function(e) { var files = elem[0].files; ngModel.$setViewValue(files); }) } } }); controller.js: var app = angular.module('myApp', []) app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){ $scope.upload = function() { var file = $scope.uploadedFile; console.log('file is ' ); console.dir(file); var uploadUrl = "/uploaded_file"; fileUploadService.uploadFileToUrl(file, uploadUrl); $http({ method:'POST', url: '/uploaded_file' }).then(function successCallback(response) { console.log("success"); }, function errorCallback(response){ console.log("failed"); }) }; } service.js: app.factory('fileUploadService', function ($rootScope, $http) { var service = {}; service.uploadFileToUrl = function upload(file, uploadUrl){ var fd = new FormData(); fd.append('file', file); $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': 'multipart/form-data'} }).then(function successCallback(response){ console.log("Files added"); }, function errorCallback(response){ console.log("Files not successfully added"); }) } return service; … -
Add a button on the default Django Admin login page
I want to add one more button on the default admin/login page. The button will allow users to send a request to become an administrator. Is there any way I could do this? -
I need to send JS file using Django view
I need to send JS file using Django view. Script that is used to get the js file from server: <script src="http://127.0.0.1:8000/give_me_js_file" parameter="1q2w3e"></script> //for example Is there any way to output JS file to any website from django? -
Django shell_plus disconnection from the server
When using the django command python manage.py shell_plus, I frequently get the following error when I send a new command after a few minutes of inactivity. OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. I have never seen this with the regular shell command. What is the cause of this error and can I restart the connection without exiting the python shell? -
Pysftp raises an Exception when running unit tests in Django
I'm developing a webapp with django that involves using pysftp for getting files from a SFTP server. The thing is that when I'm running the unit tests, I get this output at the end: Ran 3 tests in 0.264s OK Destroying test database for alias 'default'... Exception ignored in: <bound method Connection.__del__ of <pysftp.Connection object at 0x7f7bf7adeb00>> Traceback (most recent call last): File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/pysftp/__init__.py", line 1013, in __del__ File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/pysftp/__init__.py", line 785, in close File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/paramiko/sftp_client.py", line 194, in close File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/paramiko/sftp_client.py", line 185, in _log File "/home/madtyn/venvs/corelli/lib/python3.6/site-packages/paramiko/sftp.py", line 158, in _log File "/usr/lib/python3.6/logging/__init__.py", line 1374, in log File "/usr/lib/python3.6/logging/__init__.py", line 1443, in _log File "/usr/lib/python3.6/logging/__init__.py", line 1413, in makeRecord TypeError: 'NoneType' object is not callable The console for Django server does not show anything and when debugging it looks like the test units are doing fine. I don't know which code could be causing this or even if I should be worried. I can't find a similar question/answer in this context, so I decided to ask here. -
Django - Get queryset listing object attribute grouped by a different attribute
Let's say I have this model: class MyModel(models.Model): state = models.CharField(max_length=2) SKU = models.PositiveIntegerField() and these values: MyModel.objects.create(state='CA', SKU=1) MyModel.objects.create(state='CA', SKU=2) MyModel.objects.create(state='NY', SKU=3) My goal is to create a dictionary which maps state to a list of SKUs for these objects. I attempted to do that like so: my_objs = MyModel.objects.values('state', 'SKU') # to prevent creation of python object on loop -- my real model has many more fields that I don't need to query state_to_skus = dict() for my_obj_dict in my_objs: state_to_skus.setdefault(my_obj_dict['state']).append(my_obj_dict['SKU']) Which yields me: {'CA': [1, 2], 'NY': [3]} Which is exactly what I want, however, it does not scale how I would like it to when querying with almost 1 million entries. Is there a more efficient way to create this dict as a QuerySet to be something like this? <QuerySet [{'state': 'CA', 'SKUs': [1,2]}, {'state': 'NY', 'SKUs': [3]}]> I've also reviewed this question: Django - How to get a list of queryset grouped by attribute value However, neither of those two answers are what I need; they still scale to the same complexity. Thanks! -
Issue creating instance of Django model when model uses datetime?
I am currently making a project in Django that has two models: Cards and Articles. Both cards and articles have a manager that should allow me to quickly instantiate instances of the class. For cards I have the following: class CardsManager(models.Manager): def create_card(self, card_name, geography, player, typestatus, _weighted_strength = 0): card = self.update_or_create(card_name=card_name, geography=geography, player=player, typestatus=typestatus) return card This manager works smoothly and I have no issue uploading cards. However, my article manager is a different story. This is my article manager. class ArticleManager(models.Manager): def create_article(self, title, body, cardvar, source, datetime, readthrough, author): article_item = self.update_or_create(title=title, body=body, card=cardvar, source=source, entry_date_time=datetime, read_through=readthrough, cardvar__card_name=cardvar, author=author) return article_item When I try to upload an article however, say in the following fashion: article_entry = Article.objects.create_article('title', 'empty body', 'test_card_var', 'The_Source', '2019-12-30 02:03:04', 0, 'author') I get the following error in my Powrshell when I simply attempt 'python manage.py runserver': LookupError: No Installed app with label 'admin'. When I attempt to run 'python manage.py makemigrations' I get another long error message whose last line is 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.' I think the issue may have to do with something related to either 1) entry_date_time being a datetime object and passing a string (though I honestly … -
Release phase with container registry on heroku runs container
I created simple project in Django with docker. According to heroku's documentation about release phase with container registry (https://devcenter.heroku.com/articles/container-registry-and-runtime#release-phase) I created a new app with postgres addon. To deploy app with docker I executed following commands: heroku container:push web heroku container:push release heroku container:release web release But after last command my terminal is blocked and it looks like release phase actually run a container. Releasing images web,release to teleagh... done Running release command... [2019-12-30 21:22:00 +0000] [17] [INFO] Starting gunicorn 19.9.0 [2019-12-30 21:22:00 +0000] [17] [INFO] Listening at: http://0.0.0.0:5519 (17) [2019-12-30 21:22:00 +0000] [17] [INFO] Using worker: sync [2019-12-30 21:22:00 +0000] [27] [INFO] Booting worker with pid: 27 My goal is tu run django migrations before release. I would really apreciate any help. Procfile: release: python manage.py migrate Dockerfile: FROM python:3.7-slim ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PORT=8000 WORKDIR /app ADD requirements.txt . RUN pip install -r requirements.txt RUN apt-get update && apt-get install -y curl ADD . ./ RUN python manage.py collectstatic --noinput CMD gunicorn --bind 0.0.0.0:$PORT teleagh.wsgi -
social_django is creating two user instances
I have a project setup with django REST and react, with auth0 for user authorization. I have set it all up using the tutorial auth0 provides on their site (https://auth0.com/docs/quickstart/webapp/django#logout). Almost everything is working fine, however when a user is registered, their login information is stored twice: one in a database table called auth_user and again in a table called social_auth_usersocialauth. auth_user is created by my auth0backend.py file, but I cannot find where the other table is being created. Is someone able to help me find what is likely creating this second table? settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phone_field', 'rest_framework', 'social_django', 'corsheaders', 'backend', 'frontend' ] # Auth0 (Start) ----------------------------------------------- SOCIAL_AUTH_TRAILING_SLASH = False # Remove trailing slash from routes SOCIAL_AUTH_AUTH0_DOMAIN = '***' SOCIAL_AUTH_AUTH0_KEY = '***' SOCIAL_AUTH_AUTH0_SECRET = '***' SOCIAL_AUTH_AUTH0_SCOPE = [ 'openid', 'profile', 'email' ] AUTHENTICATION_BACKENDS = { 'backend.auth0backend.Auth0', # 'django.contrib.auth.backends.ModelBackend' } LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = 'http://localhost:8000' CORS_ORIGIN_ALLOW_ALL = True # Auth0 (End) ------------------------------------------------- MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] auth0backend.py from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' … -
Django project has a 'lib' folder with all of the dependence but when i run project, it gives an import error
I have been struggling with this for a while. I am trying to run an old Django 1.2 project but i keep getting an error saying "ImportError: No module named appengine.ext". I know that the module is inside the folder called 'lib' but how do i tell python to search there. I have tried to set $PYTHONPATH to the folder but it still is not working. I am using python 2.7 -
Django e-300 error after commenting and uncommenting models
I have some models I created them, ran migrations, so they we added to db. Then I decided I don't need them and commented out. Ran migrations again. Now I need them and when I uncomment and run migrations I get errors reservations.Day.room: (fields.E300) Field defines a relation with model 'Room', which is either not installed, or is abstract. reservations.Reservation.wubook_rooms: (fields.E300) Field defines a relation with model 'WubookRoom', which is either not installed, or is abstract. reservations.Room_wubook_id: (fields.E336) The model is used as an intermediate model by 'reservations.Room.wubook_id', but it does not have a foreign key to 'Room' or 'WubookRoom'. How to fix it ? -
Django admin - autocomplete select doesn't emit "change" event
I have a model, Color, with a foreign key mill that I'd like to autocomplete. Furthermore, I'd like to detect when the mill select box changes and do something with that in Javascript. However, I can't seem to trigger any JS off the select box being changed. I set up my admin like so: # admin.py class MillAdmin(admin.ModelAdmin): search_fields = ['name'] class ColorAdmin(admin.ModelAdmin): class Media: js = ['js/jquery/jquery.min.js', 'js/admin/some-function.js',] autocomplete_fields = ['mill'] And I write some Javascript: // some-function.js console.log('loaded script'); document.addEventListener('change', (function(e) { console.log('detected change event somewhere') })) console.log('event listener added') In my browser console, when I visit the Color page, I see: loaded script event listener added But when I select a mill, nothing more is logged. Further notes: The autocomplete itself is working just fine -- I am able to choose the mill I want, save, etc. Furthermore, if I remove autocomplete_fields = ['mill'] from my admin, I see that the vanilla select box does trigger the change event as expected: loaded script event listener added detected change event somewhere I dug around in the source code long enough to find that Django is using Select2, which promises to emit the change event just as if it … -
return a queryset just for the row in the database to loop through
I have 2 lists of equal size elements that I want to join and then output to my Django template. But I'm having trouble identifying the row so just that row is printed. I am trying to zip the two lists and then create a new list that will loop through onto the template page. When I use the variable on the template like the code below It works fine but I want to be able to loop through the list. I know this is incorrect as not all the elements are printed to the template but it creates the desired result. <p> {{ news.esp_article.0 }}</p> <p> {{ news.eng_article.0 }}</p> <hr> <p> {{ news.esp_article.1 }}</p> <p> {{ news.eng_article.1 }}</p> <hr> <p> {{ news.esp_article.2 }}</p> <p> {{ news.eng_article.2 }}</p> <hr> <p> {{ news.esp_article.3 }}</p> <p> {{ news.eng_article.3 }}</p> <hr> <p> {{ news.esp_article.4 }}</p> <p> {{ news.eng_article.4 }}</p> To try to solve it here is my views.py And I'm almost certain my problem is my queryset result. class ArticleViewPage(DetailView): model = Newspapers template_name = 'rtves/article.html' context_object_name = 'news' eng_articles = Newspapers.objects.values_list('eng_article') esp_article = Newspapers.objects.values_list('esp_article') zip_scripts = list(zip(eng_article, esp_article)) context.update( zip_scripts = zip_scripts ) Then I get the full raw data of every … -
Why does my image does not show up on my Template
My Goal is that the user can upload a new Manga Cover Image and the title of the Manga. I would like to show the image on the Template but it says in my command line. Not Found: /media/onepiece.jpg In my Postgressql it is added. The only thing I see is a File with a white cloud and a green hill. I also installed Pillow. My media folder contains the subfolder images and it is empty. I am really confused because the error message is looking up in the media folder but not 1 level deeper to images. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' App models.py class Manga(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) img = models.ImageField(upload_to='images', blank=True) title = models.TextField(default=None, null=True) views.py def manga_post(request): manga_img = request.POST.get('manga_img') manga_title = request.POST.get('manga_title') manga_conf= Manga.objects.get(user_id=request.user.id) manga_conf.img = manga_img manga_conf.title = manga_title manga_settings.save() return redirect('settings_manga') template (Where the post hapening) <div class="container"> <form action="{% url 'post_manga' %}" method="POST" class="form-horizontal"> {% csrf_token %} <div class="row"> <div class="col-md-6"> {% if manga.img %} <img src="{{ manga.img.url }}" alt="Add Manga Picture"> {% else %} <img src="https://image.flaticon.com/icons/png/512/43/43254.png" alt="" class="manga-img"> {% endif %} </div> <div class="col-md-6"> <div class="input-group mb-3"> <div class="custom-file"> <input type="file" class="custom-file-input" id="manga-image-input" name="manga_img"> <label class="custom-file-label" … -
need browser back button to refresh some content without refreshing the whole page like gmail
I have a Django project where I show a list of post titles in a forumhome page. Here is a typical action of a user. user clicks title of post A. user was directed to post A detail page user clicks browser back button, and go back to forumhome page with a list of posts. (!important) I want to show the user that certain posts were already read in the forumhome page. user repeat (1-4) Currently, I was able to do the above by forcing browser to refresh the page when back button is clicked: 1) track post view 2) in forumhome page, check if a specific post was viewed by the user 3) (!important) when the user clicks browser back button, I force the browser to refresh the page. I use Leonid Vasilev's answer from this post, copy-pasted below: window.addEventListener( "pageshow", function ( event ) { var historyTraversal = event.persisted || ( typeof window.performance != "undefined" && window.performance.navigation.type === 2 ); if ( historyTraversal ) { // Handle page restore. window.location.reload(); } }); What I want is rather than refreshing the whole page, only change the specific post(or posts) link to show that the post has been read by …