Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JQuery: Posting Files with FormData-Objects
So i am using a ModelForm for an updateview and want to append some files using a Javascript FormData-Object, submiting the whole form using JQuery. It seems, that the Image-Files dont get posted. views.py: class SowiUpdateView(UserPassesTestMixin, LoginRequiredMixin, UpdateView): def post(self, request, *args, **kwargs): print(request.POST) return super(SowiUpdateView, self).post(request, *args, **kwargs) The javascript: var formData = new FormData(document.getElementById("form_id")); for (var i = 0, len = filesToUpload.length; i < len; i++) { // filesToUpoad is a List containing a dict, with file i access the file formData.append("files", filesToUpload[i].file); } $.ajax({ headers: { "X-CSRFToken": getCookie("csrftoken") }, url: "{% url 'sowi-update' object.id %}", data: formData, contentType: false, processData: false, async: false, method: 'POST', type: 'POST', success: function (data) { // console.log(data); }, error: function (data) { console.log("ERROR - " + data.responseText); } }); Strangely, the serverside-post-data-output gives all the FormData-Data but the "files"-object. What's wrong? I Tried just appending a string instead of a file, and that worked. Thanks for your help!! -
Problems with creating session in the view
How to do that the same session but for each room, not for all of the rooms. In this case when this part working if user.has_perm('pass_perm', room) it creating this session request.session['joined'] = True but this works for all of the rooms views.py def auth_join(request, room, uuid): room = get_object_or_404(Room, invite_url=uuid) if request.session.get('joined', False): join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): request.session['joined'] = True join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) -
django-simple-history is storing changes twice
I tried django-simple-history and I discovered that every create or update is stored twice in the history model. I don't know which information is now useful for you to help me, but I use CBV's and model forms. I followed the instructions on how to install and setup and everything works fine. What I'm wondering is why there is a command line called clean_duplicate_history, which indeed removes all duplicates records. Thank you in advance for any help. -
why docker terminal freezes on runing the command docker-compose up
i was creating a simple hello world in django using docker but it got stuck here -
Pycharm not autocomplet file path (Cannot find declaration to go to / No suggestions)
I'm developing two django projects in parallels, apparently with the same settings that I use to do, but in one of them, when I try to refer a file, the autocomplete does not suggest anything. Print above. Here other project with autocomplete working Both projects have the same template path settings. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join((BASE_DIR), 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] Any suggestions what it might be? -
Comparing request.user.username to data from database [closed]
I want to compare current user to sender of msg in db. But it is always false {%for msg in data%} {%if msg.sender == requset.user.username %} <div class="own-msg"> <p class="sender">{{msg.sender}}</p> <p class="content">{{msg.content}}</p> <p class="time">{{msg.date_created}}</p> </div> {%else%} <div class="msg"> <p class="sender">{{msg.sender}}</p> <p class="content">{{msg.content}}</p> <p class="time">{{msg.date_created}}</p> </div> {%endif%} {%endfor%} -
How to set the landing page for user after login with django-allauth
I have the following in my project's urls.py: path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), In my project's setting.py: LOGIN_REDIRECT_URL='survey/' When I am on the login page of my application and click to submit. Instead of getting http://localhost:8000/survey/ and being redirected to the home page of my application, I am getting: http://localhost:8000/accounts/login/survey/ that gives this error: Using the URLconf defined in TestAllAuth.urls, Django tried these URL patterns, in this order: admin/ accounts/ signup/ [name='account_signup'] accounts/ login/ [name='account_login'] accounts/ logout/ [name='account_logout'] accounts/ password/change/ [name='account_change_password'] accounts/ password/set/ [name='account_set_password'] accounts/ inactive/ [name='account_inactive'] accounts/ email/ [name='account_email'] accounts/ confirm-email/ [name='account_email_verification_sent'] accounts/ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email'] accounts/ password/reset/ [name='account_reset_password'] accounts/ password/reset/done/ [name='account_reset_password_done'] accounts/ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key'] accounts/ password/reset/key/done/ [name='account_reset_password_from_key_done'] accounts/ social/ survey/ ontoSecConRule/ The current path, accounts/login/usecase/, didn't match any of these. As you can see the usecase/ path is in the error message, but I am not reaching. Where do I set the page (url) after a user has been authenticated? -
Fargate : Uwsgi died because of signal 9 , Django project
I run Django project using uwsgi and fargate container, and container kept drained. This is cloudwatch log. DAMN ! worker 1 (pid: 22) died, killed by signal 9 :( trying respawn ... Strange thing is, I already running containers with the same project, same code as testing server, and this problem never happened. The only thing that different is I did not set auto-scaling on testing, and I set auto-scaling on this server. I would like to know what is the source of sending kill signal. -
How to index columns created by django-modeltranslation to Elastic, using django-elasticsearch-dsl?
I've translated my Model fields with django-modeltranslation and implemented search using django-elasticsearch-dsl. Problem: django-modeltranslation creates translation fields in DB, and not in my Models, and search is working only for fields created by Model. As django-elasticsearch-dsl is checking Models to rebuild search index. When I try: python3 manage.py search_index --rebuild I get the error: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/apps.py", line 14, in ready self.module.autodiscover() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/__init__.py", line 11, in autodiscover autodiscover_modules('documents') File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/barbos/django-symbolsite/symbolgraph/search/documents.py", line 7, in <module> class SymbolDocument(Document): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/registries.py", line 65, in register_document field_instance = document.to_field(field_name, django_field) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/documents.py", line 142, in to_field "to an Elasticsearch field!".format(field_name) django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field name_ru to an Elasticsearch field! Oleh-MacSymbol-Pro:symbolgraph barbos$ python3 manage.py search_index --rebuild Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django_elasticsearch_dsl/documents.py", line 138, in to_field model_field.__class__](attr=field_name) … -
Django rest framework return first date in objects
I am writing an API with the django rest-framework library. Now I have the following view: class Event(models.Model): id = models.CharField(db_column='Id', max_length=36, primary_key=True) text = models.CharField(db_column='Text', max_length=4000) datacode = models.IntegerField(db_column='DataCode') datasource = models.IntegerField(db_column='DataSource') starttime = models.DateTimeField(db_column='StartTime') kind = models.IntegerField(db_column='Kind') eventcategoryid = models.CharField(db_column='EventCategoryId',max_length=36, blank=True, null=True) class Meta: managed = True db_table = 'Event' I need an endpoint that returns only the first date and the last date in the database. The expected json response is: { "firstDate": "2019-03-02 12:02:11", "lastDate": "2019-08-02 10:55:01" } Can someone help me how I can get both value from starttime. -
How do I configure my Django serializer to reuse a model if exists based on its unique constraint?
I'm using Django 2.0 and Python 3.7. I have the following models, one used as a ManyToMany by the other ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False, unique=True) objects = CoopTypeManager() ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have these serializers set up ... class CoopTypeField(serializers.PrimaryKeyRelatedField): queryset = CoopType.objects def to_internal_value(self, data): if type(data) == dict: cooptype, created = CoopType.objects.get_or_create(**data) # Replace the dict with the ID of the newly obtained object data = cooptype.pk return super().to_internal_value(data) ... class CoopTypeSerializer(serializers.ModelSerializer): class Meta: model = CoopType fields = ['id', 'name'] def create(self, validated_data): """ Create and return a new `CoopType` instance, given the validated data. """ return CoopType.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `CoopType` instance, given the validated data. """ instance.name = validated_data.get('name', instance.name) instance.save() return instance ... class CoopSerializer(serializers.ModelSerializer): types = CoopTypeSerializer(many=True) address = AddressTypeField() class Meta: model = Coop fields = ['id', 'name', 'types', 'address', 'phone', 'enabled', 'email', 'web_site'] extra_kwargs = { 'phone': { 'required': False, 'allow_blank': True } } def to_representation(self, instance): rep … -
Is it possible to change screen templates dynamically with Django framework in Python?
I am trying to build a Graphical User Interface with Django framework in Python. The goal is to have three or more intercheangeable screens: Product Menu, User Input and Payment. Is it possible to change the order of screen sequence at runtime? For example: Product Menu>Payment>User Input Payment>Product Menu>User Input User Input>Payment>Product Menu Looking at the documentation of Kivy (another framework), it offers the following functionality: Advanced Usage From 1.8.0, you can now switch dynamically to a new screen, change the transition options and remove the previous one by using switch_to(): sm = ScreenManager() screens = [Screen(name='Title {}'.format(i)) for i in range(4)] sm.switch_to(screens[0]) # later sm.switch_to(screens[1], direction='right') If not possible in Django, which framework allows to achieve this goal? -
Django can upload to S3 but not Get from S3
I have configured django to use s3 to hold media files. I can from the application upload files and they are stored on the s3, however if i try to view these media files i get this error. <Error> <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your key and signing method. </Message> I know GET requests are enabled as I can use Postman to get the images using the same credentials. So I'm not entirely sure whats wrong. STATIC_ROOT = os.path.join(BASE_DIR, '/staticfiles/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, '/image_library/') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = 'PLACEHOLDER' AWS_SECRET_ACCESS_KEY = 'PLACEHOLDER' AWS_STORAGE_BUCKET_NAME = 'childcaredevapp' AWS_DEFAULT_ACL = None AWS_S3_FILE_OVERWRITE = False AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = 'eu-central-1' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
How to allow anonymous post requests, but deny unauthorized get requests in django?
In C# you can easily attach [AllowAnonymous] to a request so that that specific method can be used. In django however I am a bit confused with Views, Serializers, ... Am I correct that a ViewSet allows you to see what a certain Serializer class contains? If so I would want that to be hidden ofcourse in the case of users. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) This is how I implemented it and it works just fine. So when I go to http://127.0.0.1:8000/api/users/ I get an error that I am not authenticated. Now the problem is with registering a new user. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data, AllowAny): user = User.objects.create_user(**validated_data) return user When I hit http://127.0.0.1:8000/api/users/ with a post request in my Angular app with newly registered userData, I obviously get an authentication error. How can I resolve that I or anyone with not enough rights, is not allowed to SEE the data of users, but however everyone is able to create (post) a new user? -
How to set an initial model field to inherent from previous views
I'm using Django to create an application that acts as a project management system. I have it set to where a user can create a project and then they can upload files that are grouped under that project. I use two models to achieve this, Projects and Drawings with Drawing using a foreign key field from Projects to create the relationship. My issue is that when users are viewing a specific project I would like the Drawing form to inherit the name of the project they were just looking at so that we don't get improperly uploaded files. I think I might be able to achieve this from the init method but not entirely sure how to grab the previous pk coming from the last view. path('project_drawings/<int:pk>/', views.ProjectDrawings, name='project_drawings'), path('project_drawingscreate/', views.ProjectDrawingsCreate.as_view(), name='project_drawingscreate'), class DrawingsForm(forms.ModelForm): def __init__(self, project ): class Meta(): model = Drawings fields = ('project', 'title', 'drawings', ) widgets = { 'project':forms.Select(attrs={'class':'form-control'}), 'title':forms.TextInput(attrs={'class':'form-control'}), } class ProjectDrawingsCreate(LoginRequiredMixin,generic.CreateView): form_class = DrawingsForm model = Drawings template_name = 'projects/project_drawingscreate.html' def form_valid(self, form, **kwargs): drawings = form.save(commit=False) drawings.user = self.request.user drawings.save() form.save_m2m() return redirect('projects:index') -
django how to set relation to some fields
i want to set relation in that case class SaleType(models.Model): price = models.CharField(max_length=50) contract = models.CharField(max_length=50) class SaleType2(models.Model): totalContract = models.CharField(max_length=50) requierd = models.CharField(max_length=50) def __str__(self): return str(self.price) class ForSale(models.Model): method = models.ForeignKey(Method, on_delete=models.CASCADE) def __str__(self): return str(self.method) that every method in ForSale have some fields from SaleType -
How to pass multiple authentication_classes in django rest framework?
I want to create an api which can be accessed using client_id and client_secret as well as access token. To access api using client_id and client_secret I have a custom authentication class like this:- class ClientAuthentication(authentication.BaseAuthentication): @staticmethod def get_client_credentials(request): try: client_id = request.headers.get('CLIENTID') client_secret = request.headers.get('CLIENTSECRET') except: raise AuthenticationFailed return { 'client_id': client_id, 'client_secret': client_secret } def authenticate(self, request): credentials = self.get_client_credentials(request) client_instance = Application.objects.filter( client_id=credentials['client_id'], client_secret=credentials['client_secret'], ).first() if not client_instance: raise AuthenticationFailed return client_instance, None def get_user_application(self, request): credentials = self.get_client_credentials(request) application_instance = Application.objects.filter( client_id=credentials['client_id'], client_secret=credentials['client_secret'], ).first() if not application_instance: raise AuthenticationFailed return application_instance, None And the other authentication class i want to use is default OAuth2Authentication I tried passing the authentication_classes for viewset as: authentication_classes = [ClientAuthentication | OAuth2Authentication] But it gives me an error. How can I achieve this? -
SESSION_EXPIRE_AT_BROWSER_CLOSE where we need to write in our project in django?
In django for expire a session after closing a browser where we need to type SESSION_EXPIRE_AT_BROWSER_CLOSE this in which file?? -
django rest_framework with React
I am trying to build an application with django as backend using REST API and front end with React. I have a model named User which contains attributes like firstname, lastname, email,password,description etc, now from front end I want to create a new user and save it to my Database, I can do this using axios and calling out put method, but before saving it to my Database I want to the profile to be verified by admin panel, like whenever user tries to signUp a new_request profile is triggered and the profile goes to admins, if they accept the profile the user is successfully added to the database, I am not getting how to do this stuff! -
How to display the old of the post in django using python?
Help me guys i am new to django and here too,, how can i display the old of the post in django so that the post time will be shown as posted 0 minute ago,, 3 weeks ago and so on to years?? -
Error during template rendering (NoReverseMatch) in Django 3.0.3
Error : Reverse for 'lesson-detail' with keyword arguments '{'course_slug': 'django-101', 'lesson-slug': 'first'}' not found. 1 pattern(s) tried: ['(?P < course_slug>[^/]+)/(?P< lesson_slug>[^/]+)$'] urls.py from django.urls import path from .views import CourseListView, CourseDetailView, LessonDetailView app_name = 'courses' urlpatterns = [ path('', CourseListView.as_view(), name='list'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail') ] course_detail.html <!DOCTYPE html> <html> <head> <title>Detail view</title> </head> <body> {{ object.title }} {% for lesson in object.lessons %} <a href="{{ lesson.get_absolute_url }}">{{ lesson.title }}</a> {% endfor %} </body> </html> -
im not able to makemigrations to my already built model after extending user model to it in django
im just stuck with error while making migrations to my django project. in my project which is already 50% dveloped i use owner model to represent owner of shop and then i used user model for login and for registration purpose. so i tried to use user model in my owner model so i could utilise both model effectively with additional fields. i tried to extend user model in owner model using onetoone field. after doing that i was not able to do migrations so i deleted all migrations files but after that it was start giving this error while doing migrations:- py manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", … -
Django-Insert Drop Down Value to postgresql
I'm very new to Django and I would like to Insert a drop down box value to database: Created two django-apps named 'Projects' and 'Clients'.After add the relevant client data ,I am trying to add the corresponding project through drop down ,the values comes from project app's corresponding table. But something went wrong , clients model Create your models here. class clients(models.Model): cname=models.CharField(max_length=20) cadd=models.TextField(max_length=50) cmob=models.BigIntegerField() cemail=models.EmailField(max_length=100) cproject=models.CharField(max_length=50,default=None) class Meta: db_table="client" project model class projects(models.Model): pname=models.CharField(max_length=100) pcode=models.CharField(max_length=100) loc=models.CharField(max_length=50) class Meta: db_table="projects" corresponding Views for add drop down value clients app def add(request): # show projects details from DB if projects.objects.count()>0: data=projects.objects.all() return render(request,'add.html',{'data':data}) else: return render(request,'add.html') def addpro(request): if request.method=="POST": temp.cproject=request.POST['sel'] temp.save() return redirect(addpro) else: return render(request,'add.html') html for dropdown list and selection <div class="container"> <form method="POST"> {% csrf_token %} <select name="sel"> <option selected disabled="true"> -- Select -- </option> {% for var in data %} <option >{{var.pname}}</option> {% endfor %} </select> <a class="btn btn-info" type="submit" href="{% url 'addpro'%}"><i class="fas fa-list-alt"></i>Add</a> </form> </div> -
HTTP Error 401: Unauthorized SendGrid django
I'm trying to do mail subscription on my django website I was following instructions online on how to achieve this. I went through it carefully but whenever I enter and email is say HTTP Error 401: Unauthorized. I went ovewr the instructions and couldn't find were i went wrong. Settings code FROM_EMAIL = 'newsletter@example.com' # replace with your address SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') Models code: class Subscriber(models.Model): email = models.EmailField(unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" class Newsletter(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subject = models.CharField(max_length=150) contents = models.FileField(upload_to='uploaded_newsletters/') def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): contents = self.contents.read().decode('utf-8') subscribers = Subscriber.objects.filter(confirmed=True) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) for sub in subscribers: message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject=self.subject, html_content=contents + ( '<br><a href="{}/delete/?email={}&conf_num={}">Unsubscribe</a>.').format( request.build_absolute_uri('/delete/'), sub.email, sub.conf_num)) sg.send(message) Views.py def random_digits(): return "%0.12d" % random.randint(0, 999999999999) @csrf_exempt def subscribe(request): if request.method == 'POST': sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for my email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), … -
Django adding placeholder text for PasswordChangeView?
A user can change their password on my change password page: <form class="password-change-form" method="POST"> {% csrf_token %} <div> {{ form }} </div> <input class="submit-button" type="submit" value="Change password"> </form> My urls.py: path( 'accounts/password_change/', auth_views.PasswordChangeView.as_view(template_name='account/password_change_form.html'), name='password_change' ), The problem PasswordChangeView uses PasswordChangeForm by default. I would like to add placeholder text to this form i.e. Old password placeholder text: 'Enter your old password'. How can I best do this?