Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'list' object has no attribute 'split' Django Haystack Solr
I'm working with django-haystack to use solr. However, I got "AttributeError: 'list' object has no attribute 'split'" when I search something at "127.0.0.1:8000/blog/search" how to solve this problem? terminal says that at blog/views.py "total_results = results.count()" error occured. blog/views.py from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.mail import send_mail from django.views.generic import ListView from django.db.models import Count from taggit.models import Tag from .models import Post, Comment from .forms import EmailPostForm, CommentForm, SearchForm from haystack.query import SearchQuerySet def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() print(results) # count total results total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) return render(request, 'blog/post/search.html', {'form': form}) blog/forms.py from django import forms from .models import Comment class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') class SearchForm(forms.Form): query = forms.CharField() blog/templates/blog/post/search.html {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} {% if "query" in request.GET %} <h1>Posts containing "{{ cd.query }}"</h1> <h3>Found {{ total_results }} result{{ total_results|pluralize}}</h3> {% for … -
Django Oscar Promotions not rendering promoted pages pages to home page
I read all the posts I could find online and tried all the possible solutions, earlier I was getting errors due to page_url not added to form meta class but after fixing that everything seems to be working fine, now the problem is that whenever I create a promotion and submit it to a URL let's say / which is home of I go back to site and refresh the home page I nothing shows up apart from the default home page. What am I getting wrong pls? What I also noticed is that when a promotion is submitted the layout is suppose to change to layout_2_col.html and it does not I have tried every single thing -
In Django, whitenoise do not show static files?
I am trying to show static files while debug=false.I am using whitenoise library but still website don't show the static files and media files. My settings.py file like this: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' -
How Can I sum the Result of a Django Date Range Result in Views
I want to add all the amount field during a date range query search. I have an Income Model with date and amount fields among others. And any time a user select between two dates, I want the amount fields of the query results added as total. Here is what I have tried: def SearchIncomeRange(request): listIncome = Income.objects.all() searchForm = IncomeSearchForm(request.POST or None) if request.method == 'POST': listIncome = Income.objects.filter( description__icontains=searchForm['description'].value(), date__range=[ searchForm['start_date'].value(), searchForm['end_date'].value() ] ) else: searchForm = IncomeSearchForm() context = { 'searchForm':searchForm, } return render(request, 'cashier/search_income_range.html', context) I am able to get the correct search result but getting the total I don't know how to use the SUM in the above query. So Someone should please help me out. Thanks -
How to deploy a Python script working under Django app?
I developed a Django app and created a script that runs through it. This script does everything I need just by running it with python3 manage.py runscript script_name I'd like now to deploy it outside of my local environment in order to run it automatically (without me manually launching it). First, I thought about deploying it on AWS Lambda but I have a hard time to figure out if that fit my needs and if I can run this sort of script out there. I have only few requirements, it needs to be on an UK server and have a database. Also this script is basically looping by itself once it's runned. Any idea or help with AWS for what I'm trying to achieve would be welcomed. Thank you. -
How to hide image from Django template?
I'm trying to make a blog website. On the all post page, it renders all the posts from the database. But not all post has its feature image. So, I'm trying to hide those image sections that don't have any featured images. Here is blog/model.py class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) author = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) slug = AutoSlugField(populate_from='title', unique=True, null=False, db_index=True) excerpt = models.CharField(max_length=60) featured_image = models.ImageField(upload_to="posts", null=True, blank=True, default="default.jpg") content = FroalaField() created = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) publish = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') Here is blog/view.py # display all blog posts def posts(request): all_posts = Article.published.all() context = {'all_posts': all_posts} return render(request, 'blog/posts.html', context) # Single post def single_post(request, slug): post = Article.objects.get(slug=slug) context = { 'post': post, } return render(request, 'blog/single-post.html', context) Here is blog/url.py urlpatterns = [ path('', views.posts, name="posts"), path('post/<slug:slug>/', views.single_post, name="single-post"), ] Here is post.html {% for post in all_posts %} <li class="bg-white px-4 py-6 shadow sm:p-6 sm:rounded-lg"> <article aria-labelledby="question-title-81614"> <a href="{{ post.get_absolute_url }}"> <!-- author details & option menus --> <div class="flex space-x-3"> <div class="flex-shrink-0"> <!-- author image --> <img class="h-10 w-10 rounded-full" src="{{ post.author.profile.avatar.url }}" alt="" /> </div> <!-- author name … -
Getting {"detail":"Method \"GET\" not allowed."} for user registration
I know this was asked a thousand times already but none of them solved my issue. I am trying to use Rest in my view. I get the error in title when I send a post request to the accounts/register/ url. models.py: from django.contrib.auth.models import AbstractUser from django.db import models from .validators import phone_validator class User(AbstractUser): class Gender(models.TextChoices): MALE = 'M', 'Male' FEMALE = 'F', 'Female' UNSET = 'MF', 'Unset' phone = models.CharField(max_length=15, validators=[phone_validator], blank=True) address = models.TextField(blank=True) gender = models.CharField(max_length=2, choices=Gender.choices, default=Gender.UNSET) age = models.PositiveSmallIntegerField(blank=True, null=True) description = models.TextField(blank=True) @property def is_benefactor(self): return hasattr(self, 'benefactor') @property def is_charity(self): return hasattr(self, 'charity') serializers.py: class Meta: model = User fields = [ "username", "password", "address", "gender", "phone", "age", "description", "first_name", "last_name", "email", ] def create(self, validated_data): user = User(**validated_data) user.set_password(validated_data['password']) user.save() return user urls.py (the one in the app. its included in the root urls.py with the 'accounts/' url) from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from .views import UserRegistration, LogoutAPIView urlpatterns = [ path('login/', obtain_auth_token), path('logout/', LogoutAPIView.as_view()), path('register/', UserRegistration.as_view()), ] views.py: from rest_framework import status from rest_framework.mixins import CreateModelMixin from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from rest_framework.views import APIView from .serializers import UserSerializer from .models import … -
How can I implement a location picker for user's searches?
I'm working on an internationalized website in Django where users need to specify their location and where users also serach things by location. I have several possible solutions: City autocomplete. Users just have to type a city and an autocomplete list will suggest complete triplets (city-state-country) to choose from. Using 3 levels dependent drop-down lists where the user first choose a country, then he picks a state and finally a city. Using a map picker where user have to click the location he want and the corresponding triplet (city-state-country) will complete. Solution 1 is very elegant. But it has several issues. The multilanguage nature of the website forces to translate any suggestion and it is not possible to translate partial inputs. A Mexican who is likely to type "Ciudad de México" with a tilded e, would not find it because the name of the city is "Mexico City" in the database. And users always risk to not find the appropriate suggestion or pick the wrong one. I would rather drop this solution even if I already have built it. Solution 2 would be very functional. But it is a little outdated and also it would complicate the user experience, expecially … -
when creating todoapp AttributeError: module 'typing' has no attribute 'NoReturn' when installing django
when entering virtual environment and trying to install django error occurs: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python36\lib\runpy.py", line 193, in _run_module_as_main "main", mod_spec) File "c:\users\user\appdata\local\programs\python\python36\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\user\Envs\test\Scripts\pip.exe_main.py", line 4, in File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\main.py", line 9, in from pip._internal.cli.autocompletion import autocomplete File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\autocompletion.py", line 10, in from pip._internal.cli.main_parser import create_main_parser File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\cmdoptions.py", line 23, in from pip._internal.cli.parser import ConfigOptionParser File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\cli\parser.py", line 12, in from pip._internal.configuration import Configuration, ConfigurationError File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\configuration.py", line 27, in from pip.internal.utils.misc import ensure_dir, enum File "C:\Users\user\Envs\test\lib\site-packages\pip_internal\utils\misc.py", line 38, in from pip.vendor.tenacity import retry, stop_after_delay, wait_fixed File "C:\Users\user\Envs\test\lib\site-packages\pip_vendor\tenacity_init.py", line 186, in class RetryError(Exception): File "C:\Users\user\Envs\test\lib\site-packages\pip_vendor\tenacity_init.py", line 193, in RetryError def reraise(self) -> t.NoReturn: AttributeError: module 'typing' has no attribute 'NoReturn' -
Cannot return MVT from Postgis 2.5
I have been trying to make the Postgis extension work with MVT data. I have been reading this article and I have done everything it says (I think) and it still does not work. Old setup Before attempting to support MVT data, we are using Mapnik with Django and we are returning PNG images. Current setup I'm building the following SQL query (using the code in the article) (bounds are dynamically calculated based on the z,x,y values) WITH bounds AS ( SELECT ST_Segmentize(ST_MakeEnvelope(0.0, -40075016.68557839, 20037508.3427892, -20037508.3427892, 3857), 5009377.0856973) AS geom, ST_Segmentize(ST_MakeEnvelope(0.0, -40075016.68557839, 20037508.3427892, -20037508.3427892, 3857), 5009377.0856973)::box2d AS b2d ), mvtgeom AS ( SELECT ST_AsMVTGeom(ST_Transform(t.geom, 3857), bounds.b2d) AS geom, original_address FROM records_addressvalue t, bounds WHERE ST_Intersects(t.geom, ST_Transform(bounds.geom, 3857)) ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom Once I have the query, I run it as follows: from django.db import connection cursor = connection.cursor() cursor.execute(sql) But the problem that it does not return anything! (yes, I have made sure that there points in that range, I have checked this with the old implementation, that it's working). The model I'm querying is this one: from django.contrib.gis.db import models class Address(models.Model): location = models.PointField(blank=True, null=True) # for vectors geom = models.PointField(srid=3857, blank=True, null=True) # for tile server … -
Accessing Images in media/ folder In Django
I'm currently learning about how images are stored in Django. To my understanding, Django stores all the images you upload in in a subdirectory of your site's media/ folder. My question is, let's say I create a website to upload images, where each image corresponds to a unique title (I will define this in my models.py file), like this: from django.db import models # Create your models here. class Post(models.Model): objects = models.Manager() title = models.CharField(max_length=100) cover = models.ImageField(upload_to='images/') def __str__(self): return self.title Then, given the unique title of an image, how can I find the image in the media/ folder that corresponds to it? Are there any websites/sections in the Django documentation that explain this? I've tried searching for some, but haven't been able to find any. Thanks in advance! -
Cannot assign "'1'": "LessonSummary.subject" must be a "Subject" instance
Cannot assign "'1'": "LessonSummary.subject" must be a "Subject" instance. File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\santosh\Desktop\desktop\New folder\quizApp\app\views.py", line 153, in LessonSumary Lesson = LessonSummary.objects.create( File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 451, in create obj = self.model(**kwargs) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 485, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\santosh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__ raise ValueError( ValueError: Cannot assign "'1'": "LessonSummary.subject" must be a "Subject" instance. [06/Sep/2021 20:24:07] "POST /createlesson HTTP/1.1" 500 85350 def LessonSumary(request): if request.method == "POST": title = request.POST["title"] content = request.POST["content"] subject = request.POST["subject"] Lesson = LessonSummary.objects.create( Title=title, content=content, subject=subject, user=request.user, ) Lesson.save() context = {"subjects": Subject.objects.all()} return render(request, "Main/lessonSummary.html", context) Models class Subject(models.Model): name = models.CharField(max_length=250, null=True, blank=True) def __str__(self): return self.name class LessonSummary(models.Model): Title = models.CharField(max_length=250) content = models.TextField() subject = models.ForeignKey( Subject, on_delete=models.CASCADE, null=True, blank=True ) user = models.ForeignKey(User, on_delete=models.CASCADE) -
how to render html code which is render from model in template as html
i am creating a blog project for leaarning django right now i am wondering is it possible to write html code in model.textfield and when fetching it in my template it render as html code whole code as paragraph let me exlain you with example i have model class Movie(models.Model): title = models.CharField(max_length=100, blank=False) urltitle = models.SlugField(max_length=100, blank=False, unique=True) info = models.TextField(blank=False,default=None) title_image = models.ImageField(upload_to='movies',blank=False, null=True) image_one = models.ImageField(upload_to='movies',blank=True, null=True) image_two = models.ImageField(upload_to='movies',blank=True, null=True) para_one = models.TextField(blank=True) written_by = models.CharField(max_length=50, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) created = models.DateTimeField(auto_now=True) as you can see in this model I have a text field name para one if I write code in that like Hello World and save it then my template while rendering it it render hello world with h1 heading instead of like this Hello World as paragraph i hope you got it or the or is there any way to do it or with any other field -
postgres showing authentication failed when given correct password
Ok, so I have installed Postgres Database with zeal, and during installation, i was prompted for a password which i entered, now when I try to start psql shell it gives me below mentioned error, but when i start Pgadmin it logs me in fine, No Clue here! Authentication error in CMD psql: error: FATAL: password authentication failed for user "atifs" Now i am trying to push my local Db to Heroku during this process i am asked for a password, and this error again, which password is it asking, because I clearly remember the password and i have given only one that too at the installation, i am close to being frustrated, need help, Thanks in advance Heroku error heroku pg:push postgres DATABASE_URL -a immense-anchorage-56196 » Warning: heroku update available from 7.53.0 to 7.59.0. heroku-cli: Pushing postgres ---> postgresql-opaque-17681 Password: pg_dump: error: connection to database "postgres" failed: FATAL: password authentication failed for user "atifs" pg_restore: error: could not read from input file: end of file ! pg_dump errored with 1 -
Django - How to use django-filters(module) with crispy-forms renderning
I'm new and still learning, I would appreciate your help on this matter. I created a listview, a grid, objects from my db and all. I now want to create a filter bar to select/seek for specific values in my object list by filtering them + have it in crispy. I downloaded both "pip install django-filter (2.4.0)" and django-crispy (forms). I already use crispy to customise forms(mostly Modelforms); I created a search bar that seems to work but the overall design isn't good and I have to make it in bootstrap. For this reason I try to bootstrapify the filter form with crispy, but it doesn't work and a)renders the standard django form; b)error. Doesn't seem to accept crispy. For this reason: Is it possible to do it? Or those modules are not compatible? If yes, what is the best practice to do so? If not, what should I do instead? **HTML** {% extends 'base/base1.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <h3>Log List</h3> <a class="btn btn-outline-info " href="{% url 'home' %}">Back to homepage</a> <hr> <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> ****{{ myFilter.form}}**** */tried also {{ myFilter.form|crispy}} {{ myFilter.form.variablefieldhere|as_crispy_field}}** <button class="btn … -
how to filter field values based on other field id of same model in Django
Here i want to filter the all the items of each group let us consider my model as class ItemsList(models.Model): invoice_number = models.IntegerField(blank=True, null=True) class ItemsInvoice(models.Model): items = models.ForeignKey(ItemsList) class StockItems(models.Model): item_invoice = models.ForeignKey(ItemsInvoice, blank=True, null=True) group_id = models.IntegerField(blank=True, null=True) For example let us consider my database values as: item_invoice | group_id 2206 | 1 2207 | 1 2208 | 2 2209 | 3 2210 | 4 2211 | 4 2212 | 4 2213 | 5 Now how can i write my filter statement based on group_id filter item_invoice and based on this item_invoice id's filter the items and based on these items ids filter invoice_number -
How to get google token for oauth2 django?
I'm trying to implement registration via the Django REST Framework Social OAuth2 did everything as in the documentation, but when I try to get an access_token, I get errors either {"error": "access_denied", "error_description": "Your credentials aren't allowed" }, if I manually specify the client_id and secret, but I don't have the google_token itself, tell me how to get it correctly and where? Here is the request itself for getting the token from the documentation: curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token -
how to setup supervisor file to read gunicorn socket
I have the following ubuntu folder structure using django test_app | |__ __ backend / | | wsgi.py | | __ __ settings.py | | |__ __ manage.py | |__ __ env / | |__ __ bin / | |__ __ gunicorn as i am trying to setup supervisor with django, nginx and gunicorn: cd /etc/supervisor/conf.d/ sudo touch gunicorn.conf sudo nano gunicorn.conf then the configuration [program:gunicorn] directory=/home/ubuntu/test_app command=/home/ubuntu/test_app/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/test_app/app.sock backend/wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn i saved and closed the file then sudo supervisorctl reread sudo supervisorctl update now when i check the status of supervisor sudo supervisorctl status i get the following error: guni:gunicorn BACKOFF Exited too quickly (process log may have details) then i checked the logs sudo cat /var/log/gunicorn/gunicorn.err.log File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'backend/wsgi' I am not sure what i am doing wrong here... the path seem correct to me Is there anything that i am missing? -
How to properly design my models for likes?
The requirement is simple. Logged in users can like post and the likes increases by 1. Here I think below models fulfill the requirement but I want the best database design possible. Or there might be other best options also. class Post(models.Model): title = models.CharField(max_length=255) likes = models.ManyToManyField(settings.AUTH_USER_MODEL) OR class Like(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User) -
Solving the view didn't return an HttpResponse object. It returned None instead
I am getting the error below Request Method: POST Request URL: http://127.0.0.1:8000/orders/place_order/ Django Version: 3.1 Exception Type: ValueError Exception Value: The view orders.views.place_order didn't return an HttpResponse object. It returned None instead. if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): print('we are here checking if the form is valid') data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax =tax data.ip = request.META.get('REMOTE_ADDR') data.save() return redirect('checkout') else: return redirect('checkout') This is a snippet of my views.py file -
how to manage messages for invalidate fields of model and invalidate recaptcha?
i have a form page in django project I want the reCaptcha-google validation error message to be different from the validation error fields of the model fields in webpage.html(template). How can I manage the error message in the view or form? translate by translate.google.com ! im sorry :) thank you views.py def home(request): comment_form = myform() if request.method == 'POST': comment_form = myform(data=request.POST) if comment_form.is_valid(): comment_form.save() messages.success(request, 'okkk') else: messages.error(request, 'error') newmyform = myform() context = { 'my': newmyform, } return render(request, 'home.html', context) forms.py from django import forms from captcha.fields import CaptchaField from .models import mymodel class myform(forms.Form): class Meta: captcha = CaptchaField() fields = ['name', ] model = mymodel -
What is the best way to handle uploaded images in Django Rest Framework on production server and how to do it?
I'm relatively new to DRF, and I'm facing a problem where I have to set up many (thousands) of profile images. I need to do it "properly", so I guess uploading raw photos to the server is not the best way to do it. What service/ approach should I use? -
Django forms inheritance doesn't read value from field
I have 2 similars forms so I decide to inherite one form from another and it looks like: class EditModuleForm(forms.Form): category_name = forms.CharField(label='Name', max_length=100) image = forms.ImageField(label='Icon', required=False) def clean_image(self): image = self.cleaned_data.get('image', None) if image: check_image_size(image) class NewCategoryForm(EditModuleForm): category_slug = forms.CharField(label="Slug", max_length=10) field_order = ['category_name', 'category_slug', 'image'] def clean_image(self): super(NewCategoryForm, self).clean_image() and during using NewCategoryForm image is not validated and value is None. Looks like this form can't get value from image field. Could somebody give me a hint what I'm doing wrong? -
Change name when saving multiple files in Django
I am trying to save multiple images at the same time: class Image(models.Model): image = models.ImageField() date = models.DateField(default=now) origin = models.ForeignKey(OriginModel) class ImageCreateView(CreateView): origin_model = None folder_name = 'temp' def form_valid(self, form): self.object = form.save(commit=False) origin_id = self.kwargs['pk'] origin = self.origin_model.objects.get(id=origin_id) date = self.object.date files = self.request.FILES.getlist('image') for f in files: image = f image.name = 'img/{0}/{1}/{2}'.format( self.folder_name, origin_id, f.name) self.model.objects.create(origin=origin, image=image, date=date) return redirect(self.get_redirect_url()) But when it saves the images, it saves them with original name f.name. I understand why it does that, but how do I pass the formatted name to the create method? -
Questions about JavaScript [closed]
I want to become a full stack web dev. I have completed HTML & CSS. Now I want to learn JS. I want to work backend with Python Django. So how much JS I need to learn for only front end? #newbie