Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django communication between users
Hi Django users? What's the best way for users to communicate with each other within the app. Similar to a chat platform where users can share files. -
getting error while saving a data into database in django using .save() method
I have created 2 models. from django.db import models from django.contrib.auth.models import User class categories(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class tasks(models.Model): title = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(categories, on_delete=models.CASCADE) def __str__(self): return self.title and have created the forms from these models. the view.py is from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login, logout, authenticate from .forms import CategoriesForm,TaskForm from .models import categories,tasks from django.utils import timezone from django.contrib.auth.decorators import login_required def home(request): return render(request, 'user/home.html') def signupuser(request): if request.method == 'GET': return render(request, 'user/signupuser.html', {'form':UserCreationForm()}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect('currentcategories') except IntegrityError: return render(request, 'user/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'user/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def loginuser(request): if request.method == 'GET': return render(request, 'user/loginuser.html', {'form':AuthenticationForm()}) else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request, 'user/loginuser.html', {'form':AuthenticationForm(), 'error':'Username and password did not match'}) else: login(request, user) return redirect('currentcategories') @login_required def logoutuser(request): if request.method == 'POST': logout(request) return redirect('home') @login_required def createcategories(request): if request.method … -
Sending out Email is not working at Google Cloud Run
My application that hosted at GCP Cloudrun. The Email cannot send out from there. It work perfectly at localhost. My email are hosted at G-suite. Anyone have encounter this issue? -
Is it possible to add a new data on Django Object in view?
My question is only to ask if this is possible. For example this QuerySet in view: item_list = ItemList.objects.all() Inside item_list, I want to add an HTML tag to be rendered to template. html_var = "<div> SOMETHING </div>" item_list = item_list + html_var or something Reason: I want to control what type of html tag based on the index of the item_list. My first option was to use modulus on loop counter but based on docs and other's comment, we can't get the remainder on the modulus operator. The return is a boolean. If you have other suggestion instead please let me know. Result that I want: If index/forloop.counter0 of item_list's modulus of 4 equals 1, <div class="upper-left"> If index/forloop.counter0 of item_list's modulus of 4 equals 2, <div class="lower-left"> If index/forloop.counter0 of item_list's modulus of 4 equals 3, <div class="upper-right"> If index/forloop.counter0 of item_list's modulus of 4 equals 0, <div class="lower-right"> -
Django: Model.objects.filter() returns an empty Queryset
I am using Django for the Backend in my webapplication. I have a some data in my database which I can query just fine with the objects.get() method. volumes = Volume.objects.get(volumeEngTitle="If there is a volume Title") This returns the following value in Postman: { "volumeNumber": 8.1 "chapterNumber": 12 "Translated": True } But I need to return multiple volumes that have the same title. This is why I tried to use filter() but the result of the Http.Get in Postman is always an empty set, e.g {}. filter() seems to never find any instance that matches the volumeEngTitle even though it exists. Here is the whole function to return the volume. from rest_framework.response import Response from .serializers import VolumeSerializer from ..volumeModel import Volume @api_view(['GET']) def getVolume(request): volumes = Volume.objects.filter(volumeEngTitle="If there is a volume Title") #This works like a charm but only for a single instance: #volumes = Volume.objects.get(volumeEngTitle="If there is a volume Title") serializer = VolumeSerializer(volumes) return Response(serializer.data) The result of this method is always {}. Even though it works fine with the get() method. I understand that get() is for a single return value and filter() gives me a queryset with mulitple values. But I can't figure out why filter … -
page language based on language field in user model
I'm starting with Django internationalization and I created a field in the user model and I want to change the language of the page based on the language of the user can i do this? -
NoReverseMatch at /admin/...(adding custom user with id as char field).. Unable to create user with a Custom User Model in Django Admin
I am working on a legacy database from .net application and in the users table the id field is of char type and is something like this-- 99124-b8f3-4d92-a0b1-763cc1f10f1b. So, I have taken char field on id. creating super user on shell is working fine and updating/changing existing user is working. How ever, when I try creating a user with User Creation form.. I get the below error. My code is as follows: Models.Py def generate_id(hash_length): hashtext = ''.join(random.choices(string.ascii_letters + string.digits, k=hash_length)) prefix='kcov' return f"{prefix}_{hashtext}" gender_choices= ((0, 'Female'), (1, 'Male')) class Aspnetusers(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True,db_column='Email') id = models.CharField(primary_key=True, max_length=128, db_column='Id', unique=True) first_name = models.CharField(db_column='Name', max_length=100, unique=False #### few more fields ### class Meta: managed = False db_table = 'AspNetUsers' verbose_name='User' verbose_name_plural='Users' def save(self,*args, **kwargs): if not self.id: prefix = 'KC{}'.format(datetime.datetime.now().strftime('%y%m%d')) prev_instances = self.__class__.objects.filter(id__contains=prefix) if prev_instances.exists(): last_instance_id = prev_instances.last().special_id[-4:] self.special_id = prefix+'{0:04d}'.format(int(last_instance_id)+1) else: self.special_id = prefix+'{0:04d}'.format(1) super(Aspnetusers, self).save(*args, **kwargs) def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self,app_label): return self.is_superuser def get_absolute_url(self): return reverse('Aspnetusers', kwargs={ 'id': self.id, }) def __str__(self): return str(self.email) def __str__(self): return str(self.email) def get_full_name(self): full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): return self.first_name Managers.py class UserManager(auth_models.BaseUserManager): def _create_user(self, email, password, **extra_fields): """ Creates and … -
Django filtering through encrypted fields doesn't work
I am using django-pgcrypto package to work with encripted data. In documentation says that is possible to filter on encrypted fields as you would normal fields via exact, gt, gte, lt, and lte lookups this package for encryption. Model: class Profiles(BaseModel): first_name = EncryptedCharField(max_length=255, null=True) last_name = EncryptedCharField(max_length=255, null=True) postal_code = models.CharField(max_length=32, null=True) skype = EncryptedCharField(max_length=255, null=True) email = EncryptedCharField(max_length=255, null=True) ... Example of query: email = Profiles.objects.filter(email__exact='example@email.com') Error: Traceback (most recent call last): File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function dearmor(text) does not exist LINE 1: ...irmed" FROM "profiles" WHERE convert_from(decrypt(dearmor("p... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/Projects/rab/rentautobus-site/uService2/traveler/views.py", line 206, in conversations print(email) File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/user/Projects/rab/rentautobus-site/uService3/env/lib/python3.7/site-packages/django/db/models/query.py", line 55, in … -
Django: manytomany relations not loaded even it exists
We run a Django server for an ecommerce web, where thousands of queries are made, and lastly we're getting many errors like: "FieldError: Cannot resolve keyword 'stockrecords' into field. Choices are: ..." I know that this error is thrown whenever we're trying to join a table through a field that doesn't exist in the model, but it really does exist. The definition of the model StockRecord is: class StockRecord(models.Model): product = models.ForeignKey( 'catalogue.Product', on_delete=models.CASCADE, related_name="stockrecords", verbose_name=_("Product")) num_in_stock = models.PositiveIntegerField( _("Number in stock"), blank=True, null=True) And the definition of the product does not include any reference to the stockrecords. And the errors is produced when calling: class ProductQuerySet(models.query.QuerySet): def with_stock(self): return self.filter(stockrecords__num_in_stock__gt=0) Where 'self' is a product. Thank you!! -
How to Preload only few images in Django
I am Building a BlogApp and I want my Image Page to load only few images after open the Image. What i am trying to do:- I am trying to Load only 9 images in the Server. I mean :- When user opens the Page then, load only few images that are in front of the page, and if user scrolls then load next few images. What is happening Now:- When i open the server now, It loads all the Images that are uploaded in the Page. What have i tried:- I also tried Preload function in HTML BUT it didn't worked for me. <img preload="auto"> <src="{{ image.file.url }}" width="200"> </img> I don't know what to do. Any help would be appreciated. Thank You in Advance. -
how to solve Django POST URL error of APPEND_SLASH
I'm trying get my form POST data onto next page but getting the error You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/robustSearch/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. my urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('search_titles', views.searchTitles, name='search_titles'), path('stats/', views.dataStats, name='stats'), path('robustSearch/', views.robustSearch, name='robustSearch'), ] And my views.py file def robustSearch(request): if request.method == 'POST': file = request.FILES['titles_file'] df = pd.read_csv(file) df.dropna(inplace=True) counting = df.counts() context={ 'counting': counting, } return render(request, 'result_titles.html', context) and my POST Form file is <form action="robustSearch" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-inline"> <input type="file" name="titles_file" class="form-control input-sm mr-2"> <button type="submit" class="btn btn-primary">Search</button> </div> </form> anyone can please point out where I'm doing wrong or how can I get this purpose fulfilled -
Django Postgres Interval
I have a following model class E(Model): start_date = DateField() duration = SmallPositiveIntegerField() # in days How can I write a query, that for a certain date finds rows, where start_date <= date <= start_date + duration? q.filter(start_date__lte=date, ????) How can I perform add timedelta inside postgres? -
How to use the pool connections set up with django-postgrespool2 when querying the database?
I have just set up django-postgrespool2 for creating a connection pool between my Django and PostgreSQL database. I followed the readme guide here on how to install and config it. It works now and I can run my project with django-postgrespool2. However, here comes my question. How do I verify that the pool connections are being used when I query the database? What code should be used when connecting to the database, is it any different or can I use the same code as before? My database settings in settings.py, I have set the database engine to django_postgrespool2: DATABASES = { 'default': { 'ENGINE': 'django_postgrespool2', 'NAME': env_config.get('DB_NAME'), 'OPTIONS': { 'options': '-c search_path=mbraindjango' }, 'USER': env_config.get('DB_USER'), 'PASSWORD': env_config.get('DB_PASSWORD'), 'HOST': env_config.get('DB_HOST'), 'PORT': env_config.get('DB_PORT') } } My settings for django-postgrespool2: DATABASE_POOL_CLASS = 'sqlalchemy.pool.QueuePool' DATABASE_POOL_ARGS = { 'max_overflow': 10, 'pool_size': 5, 'recycle': 300 } Code example of how I connect and query the database: def paginateData(self, paginationData, search): sqlSelect = "SELECT * FROM tablex " sqlWhere = self.buildCTPagianteSqlWhere(search) sqlOrderBy = "ORDER BY name " sqlPagination = "LIMIT %s OFFSET %s;" sql = sqlSelect + sqlWhere + sqlOrderBy + sqlPagination sqlParams = self.buildCTPaginateParams(paginationData, search) cursor = db.cursor("mydatabase", sql, sqlParams) dataResult = cursor.connect() return dataResult Does … -
show warning message in the html model before final submition of a django form
I have a Django form, I want to show a warning message to the end-user if the form has been edited i.e if the old data is changed. how can I do that? currently, I am able to figure out what are the fields which have been changed with the help of the form.changed_data attribute of Django form. user_changed_data = schedule_form.changed_data if user_changed_data: message.warning(request, "are you sure you want to edit this form?") return HttpResponseRedirect(reverse(EditView.urlname, args=[arg1, arg2])) how can I show the warning message on the HTML modal and if the user presses yes do the final submission of the form? -
Open source cryptography based software licence creation in python
I'm working on a server-side (Django) implementation for issuing licenses to on-premise nodes as a response to renew license API call. These licenses will have a short expiry forcing end-user to provide internet to on-premises nodes in order to continue operations. I'm looking for a mechanism to create license certificates with short expiry (7 days) on an authenticated API call. Renewed certificate will allow Python web app running on-premises Linux OS to operate seven more days. This will force the end-user to provide internet access so that the server can collect compiled data from nodes. A crypto algorithm will create a private key from the node’s UUID (dmidecode). The server will have private keys for all registered nodes to sign license certificates with seven days expiry. Python web app will verify certificate expiry using the system’s UUID at each startup. A simple way to do this would be to use JWT for certificates creation and UUID as secrete keys but I want to know if there are any open-source lib specialized for this case or is there any other better way to implement this. Note: Linux Node is shipped to the end-user preconfigured with an encrypted drive so users do … -
Nginx render speed too slow
I'm working with django + uwsgi + nginx Below are my main settings and request log with uwsgi and nginx 1 uwsgi.ini [uwsgi] pythonpath=/xxx static-map=/static=/xxx/static chdir=/xxx env=DJANGO_SETTINGS_MODULE=conf.settings module=xxx.wsgi master=True pidfile=logs/xxx.pid vacuum=True max-requests=100000 enable-threads=true processes=16 threads=32 listen=1024 log-slow=3000 daemonize=logs/wsgi.log stats=/tmp/xxx/socket/stats.socket http=0.0.0.0:6187 buffer-size=220000000 socket-timeout=1500 harakiri=1500 http-timeout=1500 reqeust log [pid: 10550|app: 0|req: 549/6061] 103.218.240.105 () {50 vars in 1037 bytes} [Mon Mar 8 15:24:30 2021] GET /api/v2/analysis/xxxx => generated 3890508 bytes in 397 msecs (HTTP/1.1 200) 5 headers in 222 bytes (1 switches on core 16) 2 nginx.conf worker_processes 12; events { use epoll; worker_connections 65535; } http { include mime.types; include log_format.conf; include upstream.conf; default_type application/octet-stream; sendfile on; tcp_nopush on; keepalive_timeout 1800; server_tokens off; client_max_body_size 100m; gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_comp_level 5; gzip_types text/plain application/json application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary off; include "site-enabled/*.conf"; } upstream.conf upstream bv_crm_server_proxy_line { server proxy.xxxx.cn:6187 weight=100 fail_timeout=0; keepalive 500; } log_format.conf log_format upstream '$remote_addr - $host [$time_local] "$request" ' '$status $body_bytes_sent $request_time $upstream_response_time ' '"$http_user_agent" "$http_x_forwarded_for" '; site-enabled.xxx.conf server { listen 7020; server_name xxxx.xx.cn; client_max_body_size 100M; access_log logs/xxx.log upstream; root /home/smb/web/xxx/dist; client_header_buffer_size 16k; large_client_header_buffers 4 16k; location ^~ /api/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header … -
Django Inheritance project
Sir/Madam, I'm trying here to inherit a project in Django. I wrote here 1 single CommonData and 3 children classes. Trying to inherit 2 common data fields 'name' and 'location'. I code in the admin.py file also. I think everything I wrote is correct. But, I got the following error while making migrations. I don't know where I done a mistake? please give me a hint to fix it. Thank you. ERRORS: <class 'abapp.admin.CustomerAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'CustomerAdmin', or an attribute or method on 'abapp.Customer'. <class 'abapp.admin.CustomerAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'location', which is not a callable, an attribute of 'CustomerAdmin', or an attribute or method on 'abapp.Customer'. <class 'abapp.admin.EmployeeAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'EmployeeAdmin', or an attribute or method on 'abapp.Employee'. <class 'abapp.admin.EmployeeAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'location', which is not a callable, an attribute of 'EmployeeAdmin', or an attribute or method on 'abapp.Employee'. <class 'abapp.admin.StudentAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'StudentAdmin', or an attribute or method … -
Date format inconsistency in Django Model
I have a model similar to class MyModel(models.Model): statusChangeDateTime = models.DateTimeField(db_column='status_change_date_time', null=False, default=timezone.now) startTime = models.DateTimeField(db_column='start_time', blank=False, default=timezone.now) Interestingly there are some inconsistencies in the format, I just could not find why that might happen.. The difference is like "startTime": "2020-12-25T04:50:26Z" and "startTime": "2021-03-08T01:50:19.173085Z" The same thing is happening with the other field as well. How can I fixed the format so that all of them have the same format all the time. I am using MySQL as my database. Thanks in Advance. -
How can I start the creation of a Django foreign key model instance from the parent form?
I created the following two Django models: class Partner(models.Model): name = models.CharField( max_length = 100, null = False ) zip_code = models.CharField( max_length = 10, null = False ) class Meta: verbose_name_plural = "Partners" def __str__(self): return self.name class Screen(models.Model): name = models.CharField( max_length = 100, null = False ) position = models.CharField( max_length = 100, help_text = "Google Pluscode", null = False ) partner = models.ForeignKey( Partner, on_delete = models.PROTECT, null = False ) class Meta: verbose_name_plural = "Screens" def __str__(self): return self.name When I add a new instance of a screen, I would like to be able to click on a button inside the form and add a new instance of a partner (if it does not exist yet). After the creation of the foreign key instance, it should return to the original form. It is the same mechanism as in the the admin site when you add a new instance of a model (see image below) but I don't know how to implement it. Admin site model creation I have already looked up inline forms but this is not really the mechanism I want to use. I want to have a new HTML-Page or a modal for … -
how to create a post api in django if sample post request and response is already given
How to create a post rest api in django if sample request and sample response is given? Can't understand from where to begin. -
Django not showing dynamic list content
I am making a website where I show off the specs of each product using flip cards and I have django is as the backend. I was trying to make the specs dynamic using jinja format but everytime I try to put my multiple objects in list it messes the code up. views.py before def prodospecs(request): product1 = product() product1.name = 'iPhone 12 Pro 5G' product1.screen = '6.1" Super Amoled Display 60hz' product1.chipset = 'A14' product1.camera = 'Triple Camera Setup (UltraWide, Telephoto, Wide)' product1.special = 'New Design' product1.price = 999 product2 = product() product2.name = 'S21 Ultra 5G' product2.screen = '6.8" Amoled Display 120hz' product2.chipset = 'Snapdragon 888, Exynos 2100' product2.camera = 'Quad Camera Setup (UltraWide, 2 Telephoto, Wide)' product2.special = 'New Camera Design and S-Pen Support' product2.price = 1199 product3 = product() product3.name = 'Asus Zenbook Duo' product3.screen = '14 inch 16:9' product3.chipset = 'i5 or i7' product3.camera = '720p Webcam' product3.special = 'Two Displays' product3.price = 999 return render(request, 'prodospecs.html', {'product1' : product1,'product2' : product2, 'product3' : product3 }) And this one works and shows all the information necessary views.py after def prodospecs(request): product1 = product() product1.name = 'iPhone 12 Pro 5G' product1.screen = '6.1" Super Amoled Display … -
How do I show specific field in foreign key model, in Django+React app?
so I have a Django+React app, and having trouble with something. Obviously, I've created REST API with Django and fetching it with React. Let me show you the code first. models.py (Django) class Category(models.Model): category_name = models.CharField(max_length = 20) class Content(models.Model): category = models.ManyToManyField(Category) key_line = models.CharField(max_length = 100, null=True) body = models.TextField(blank=True, null=True) views.py (Django) @api_view(['GET']) def book_list(request): books = Content.objects.all() serialized = ContentsSerializer(books, many=True) return Response(serialized.data) React component class Books extends Component { constructor(props){ super(props); this.state = { } } componentDidMount() { this._getBookList(); } _renderBookList = () => { const books = this.state.bookList_object.map((this_book, index) => { return <BakeList key_line={this_book.key_line} body={this_book.body} category={this_book.category} /> }) return books } _getBookList = async () => { const book = await this._callApiBookList(); this.setState({ bookList_object : book }) } _callApiBookList = () => { return fetch("https://api.book.shop/api/books/") .then((response) => response.json()) .catch((err) => console.log(err)) } render() { return( <div>this._renderBookList()</div> ) } BookList.js class CakeList extends Component { constructor(props) { super(props); this.state = { page : 'home' } } render() { return ( <div>{this.props.key_line}</div> <div>{this.props.body}</div> <div>{this.props.category}</div> ) } Now the problem is in the {this.props.category} line in BookList.js component. What I want to get in the screen is category_name, but what I get is id. How do … -
django - No return after call from another serializer
users/models.py class GolferPhotoViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet,): queryset = GolferPhoto.objects.all() serializer_class = GolferPhotoSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, GolferPhotoPermission) def get_queryset(self): data = self.kwargs if data.get("golfer_profile_pk"): if data.get("pk"): if self.request.query_params.get("photo_nickname"): image_value = self.request.query_params.get("photo_nickname") user = self.request.user.id user_value = "GOLFER" + str(user) return FileInfo.objects.get( reference_value=user_value, image_nickname=image_value ) obj = GolferPhoto.objects.get(id=self.kwargs["pk"]) self.check_object_permissions(self.request, obj) return self.queryset.filter(pk=self.kwargs["pk"]) ... http://127.0.0.1:8000/golfer-profile/1/golfer-photos/3?photo_nickname=MAIN I'd like to return one object from a model called [Fileinfo], but it says [{"detail":"Not Found"} in postman. instance = FileInfo.objects.get( reference_value=user_value, image_nickname=image_value ) serializer = FileInfoSerializer(instance) return Response(serializer.data) Even if I put it in the serializer, it doesn't work out the way I want it to, what should I do? -
How to properly show image stored from a file server to a django HTML template?
I have trouble displaying images stored in a file server to the django template. File server link is \11234.123.123.123\dashboard.jpg (just a sample). It seems like the img src url is being added by the django localhost url prefix to the file server path as follows: http://127.0.0.1:8000/dashboard/\\11234.123.123.123\dashboard.jpg In django template, the img tag is written as: <img class="imgView" src="{{dashboard_image}}" alt="Dashboard画面.jpg"></img> My views.py just sends the image file server URL as text (with value of \11234.123.123.123\dashboard.jpg) to be displayed as image in the HTML page as the django template. But, the image does not show properly as follows. Please help, thank you! -
How can I retrieve form data out of request.POST in Django
I want to get a form data sent through request.POST. The data is in a form of dictionaries inside a list. Here is the html form and ajax request: <form class="passwordUpdateForm" novalidate="" name="passwordUpdate" action="" method="" id="passwordUpdateForm"> {% csrf_token %} <div class="md-form md-outline mb-3"> <label data-error="wrong" data-success="right" for="oldPass">current password </label> <input type="password" id="oldPass" class="form-control" name="oldPassword" placeholder="*********" value=""> </div> <div class="md-form md-outline mb-3"> <label data-error="wrong" data-success="right" for="newPass">new password </label> <input type="password" id="newPass" class="form-control" name="newPassword" placeholder="*********" value=""> </div> <div class="md-form md-outline mb-5"> <label data-error="wrong" data-success="right" for="newPassConfirm">confirm new password </label> <input type="password" id="newPassConfirm" class="form-control" name="newPasswordConfirm" placeholder="*********" value=""> </div> <button type="submit" class="btn btn-primary mb-4"> change password </button> </form> <!-- to change user password --> <script type="text/javascript"> $('#passwordUpdateForm').on('submit', function(event) { event.preventDefault(); // to get form data var formData = $(this).serializeArray(); var formData = JSON.stringify(formData); alert(formData); // submit ajax request $.ajax({ type: "POST", url: "{% url 'passwordReset' %}", dataType: "json", contentType: false, processData: false, data: { 'form_data': formData, csrfmiddlewaretoken: '{{csrf_token}}', }, success: function(data) { data = JSON.parse(data); var message = $('#flashMessage').html(''); message.append('<div class="alert alert-warning alert-dismissible fade show" role="alert">'+'<strong>'+'sorry {{first_name}} </strong>'+ data +'<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+'<span aria-hidden="true">&times;</span>'+'</button></div>'); } }); }); </script> The backend view function is as follow: def passwordReset(request): # process form data if request.method == …