Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form is submitted but not saving value in database
When I submitted this form, instead of saving the value it takes and save it to the database, it submitted the form but the value is none when I check admin page, the form is submitted and redirected me to home page, but the value that a form takes is none when I check my admin: Model: class Column(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) name = models.CharField(max_length=100) select_type = models.ForeignKey(Type, on_delete= models.CASCADE) views: class CreateColumn(CreateView): model = Column template_name = 'column_create.html' form_class = ColumnForm success_url = 'home' def get_context_data(self, **kwargs): context = super(CreateColumn, self).get_context_data(**kwargs) context['formset'] = ColumnFormSet(queryset=Column.objects.none()) return context def form_valid(self, form): form.instance.user = self.request.user return super(CreateColumn, self).form_valid(form) Form: class ColumnForm(forms.ModelForm): class Meta: model = Column fields = ['name', select_type'] ColumnFormSet = modelformset_factory(Column, fields=('name' 'select_type'), extra=30) template: <form method='post'> {% csrf_token %} {{ formset.management_form}} {% for form in formset %} {{form.as_p}} {% endfor %} <button type='submit'>Save<button/> <form/> -
Create Django custom 404 error template page affects navigation bar
I am creating a custom 404 error page but it affects my navigation bar. Before creating a custom 404 error page: After creating a custom 404 error page: main's urls.py handler404 = "audioJournaling.views.error_404" setting.py DEBUG = False ALLOWED_HOSTS = ['*'] views.py def error_404(request, exception): return render(request, '404.html') 404.html <h1>404 Page Not Found</h1> <p>My Custom 404 Page Not Found!</p> The first code I have followed is https://levelup.gitconnected.com/django-customize-404-error-page-72c6b6277317 And the second is https://studygyaan.com/django/django-custom-404-error-template-page The only difference between the two code is the views.py. The first code example place the code in main's views.py. The second code example place the code in app's views.py. However, both of them shows the same problem. -
admin.display with mark_safe
Is there any chance I can put HTML in the <th> of change_list.html, other than going down the ugly road of overriding the admin_list template tags? I want to style the text in the table head a little bit for viewing pleasure but it is quite tricky to access the table header in django. I have something in mind like: @admin.display(description = mark_safe("<b class='bg-danger'>status</b>")) def get_status(self, obj): return obj.status -
django display nested loop foreignkey in template
I have 3 models Course course_name = models.CharField(max_length = 200, unique=True) Module module_name = models.CharField(max_length = 200, unique=True) course = models.ForeignKey(Course, on_delete=models.PROTECT) Sesion sesion_name = models.CharField(max_length = 200, unique=True) course = models.ForeignKey(Module, on_delete=models.PROTECT) Lesson lesson_name = models.CharField(max_length = 200, unique=True) sesion = models.ForeignKey(Sesion, on_delete=models.PROTECT) I need show in ul, ol html Course name Module 1 Sesion 1 Lesson 1 Lesson 2 Sesion 2 Lesson 1 Lesson 1 Module 2 Sesion 1 Lesson 1 How I can display this queryset? I try prefetch... and dict = [zip(mod, ses, tem)] but i Dont understand how display or how set the queryset -
Getting ModuleNotFoundError while running the Django app with embedded python distro but its working fine with python installer version in Windows
I am trying to run a Django app in windows. Case A: (with python Windows embeddable package) Downloaded python Windows embeddable package (64-bit) installed Django by executing python -m pip install Django created a Django app by running django-admin startproject testDjango1 executing in command line: python manage.py runserver getting error: D:\program_files\python\testDjango1>python manage.py runserver Traceback (most recent call last): File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "D:\program_files\python-3.10.10-embed-amd64\Lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'testDjango1' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\program_files\python\testDjango1\manage.py", line 22, in … -
Hide specific URI in URL using htaccess
The hosted site is located in a subdirectory and can only be accessed through the URI /public/, i.e., https://test.myapp.com/myapp1/public. However, I want to make the site accessible directly through the URI https://test.myapp.com/myapp1/. This is Symfony 5.4 PHP project. -
Django Rest Framework nested serializer returns empty list
I have two models which are related by one to many relationship. I want to use the first model called Return to post data and another one called Assessment to retrieve data. My models are as follows:- from django.db import models class Return(models.Model): room_type = models.CharField(max_length=50) number_of_rooms = models.PositiveSmallIntegerField() price_per_night = models.DecimalField(max_digits=10, decimal_places=2) actual_turnover = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateField(auto_now=True) class Meta: verbose_name = 'Return' verbose_name_plural = 'Returns' def __str__(self): return f'{self.room_type}' # A function that return number of days in a month def days_in_month(self): # Get the year and month from the date field year = self.created_at.year month = self.created_at.month # Use calendar.monthrange() to get the number of days in the month num_days = monthrange(year, month)[1] return num_days @property def potential_turnover(self) -> float: return float(self.days_in_month()) * float(self.number_of_rooms) * float(self.price_per_night) @property def total_number_of_rooms(self) -> float: total = 0 for obj in Return.objects.all(): total += obj.number_of_rooms return total @property def total_potential_turnover(self) -> float: total = 0 for obj in Return.objects.all(): total += obj.potential_turnover return total @property def gross_amount(self) -> float: total = 0 for obj in Return.objects.all(): total += obj.actual_turnover return total class Assessment(models.Model): return = models.ForeignKey(Return, related_name = "returns", on_delete=models.CASCADE) created_at = models.DateField(auto_now=True) class Meta: verbose_name = 'Assessment' verbose_name_plural = … -
How do I pass in a variable inside a HTML link which will then pre populate different parts of a fields in my Django model form
Please bare with me as this is my first post on here and I may have made some formatting erros in the way the question is presented and someone might have already answered my question. But I just can't find the answer. Thank you very much for your help in advance. So I have a Django project that shows a weekly calender with items that people will be working on. Next to each day on the calender there is a button to add items on to the list but i want to make that button dynamic so it only takes in the current date that it is being showed next to and only takes the user that it is being showed under. Then i want that link to prepopulate two fields of a scheduleCreationForm. Please see below the view of the html page and the code for the html page view of html page # html file <section class="section"> <div class="row"> {% for profile in profiles %} <div class="col-6 col-md-12 col-lg-6"> <div class="card"> <div class="card-content"> <div class="card-body"> <h4 class="card-title">{{profile.name}}</h4> {% for date in ldates %} <div class="d-flex justify-content-between"> <p>{{date}}</p> <a href="#" ><i class="bi bi-plus-circle"></i></a> </div> <hr style="margin-top: 0px; margin-bottom: 0px; … -
How to make a form which adds data to a through table in django
I have two models, Place and Species, with a many-to-many relationship, which are joined by a through table called Sighting which has some extra fields: class Place(models.Model): coordinates = models.TextField() class Sighting(models.Model): place = models.ForeignKey(Place, on_delete=models.PROTECT) species = models.ForeignKey(Species, on_delete=models.CASCADE) uploaded_by = models.ForeignKey(User, on_delete=models.PROTECT) description = models.TextField(blank=True, null=True) class Species(models.Model): name = models.TextField() places = models.ManyToManyField(Places, through=Sighting) here is the view for creating instances of the Species model, which adds the uploaded_by attribute automatically to the Sighting through table: class SpeciesCreateView(CreateView): model = Species form_class = SpeciesCreateForm template_name = "species_form.html" def get_success_url(self): messages.success(self.request, "Species Created Successfully") return reverse("add_species") def form_valid(self, form): self.object = form.save(commit=False) self.object.save() for place in form.cleaned_data["places"]: sighting = Sighting() sighting.uploaded_by = self.request.user sighting.place = place sighting.species = self.object sighting.save() response = super().form_valid(form) return response here is the form for that CreateView, where a user can select multiple places to link to the species: class SpeciesCreateForm(forms.ModelForm): class Meta: model = models.Species fields = [ "name", "places", ] name = forms.CharField() places = forms.ModelMultipleChoiceField( queryset=models.Species.objects.all(), help_text="Places this species has been sighted", ) and for good measure the form template: {% extends "base.html" %} {% block content %} <h1>Upload Species</h1> <div> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {% include … -
how to create a custom user registration form without using django's forms
I work on a project of which I do the back-end, another developer works the front-end. he created a registration page with html forms, it gives me a hard time because I have never used html forms I only use django forms. so I can't save the forms he created in the database. help me please I tried the django forms method but it doesn't work. views files from django.shortcuts import render, redirect from user.forms import * # Pour importer tous les elements du fichiers forms.py # on import View pour utiliser la vue basée des classes. from django.views.generic import View from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.conf import settings from command.models import Command,CommandProduct from main.utils import get_command_data from main.models import Cart from user.forms import * class Loginpage(View): template_name = 'user/loginpage.html' form_class = 'LoginForm' def get(self, request): form = self.form_class() message = '' print('-----------LOgiN GET-----------') return render(request, self.template_name, {'form': form, 'message': message}) def post(self, request): form = self.form_class(request.POST) print('-----------LOgiN-----------') print(form) if form.is_valid(): user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user is not None: login(request, user) return redirect('main/home') else: message = 'Identifiants invalides' return render(request, self.template_name, {'form': form, 'message': message}) def connect(request): form = LoginForm() error = '' … -
How to create filter form page with Django filters with object count per category shown in the option labels
I am new to Django and trying to create a page that shows a list of products with couple of filters. The page works fine using standard method and shows filter and update the page as selected. What I want to do is to add a count of products available based on the seelcted filters in; in this case just for category. models.py class Category(index.Indexed, models.Model): name = models.CharField(max_length=1024) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" class Product(models.Model): title = models.CharField(max_length=1024, verbose_name="Product title") last_modified = models.DateTimeField(null=True, blank=True) category = models.ForeignKey("Category", on_delete=models.SET_NULL, null=True, blank=True) filters.py class ProductFilter(django_filters.FilterSet): category = django_filters.ModelChoiceFilter( queryset=Category.objects.annotate(num_product=Count("product")) ) last_modified = django_filters.DateRangeFilter(label="Date_Range") class Meta: model = Product fields = ["category", "last_modified"] views.py def product_explorer_view(request): products = Product.objects.all() product_filter = ProductFilter(request.GET, queryset=products) products = product_filter.qs context = { "products": products, "product_filter": product_filter, } return render(request, "/products_index.html", context) products_index.html <form class="mb-1"> <div class="row g-2"> <div class="col-md-2 col-sm-4"> Category: <div class="form-floating"> <!-- <label for="searchTerm" class="form-label">Category</label> --> {{ product_filter.form.category }} </div> </div> <div class="col-md-2 col-sm-4"> Date: <div class="form-floating"> <!-- <label for="searchTerm" class="form-label">Category</label> --> {{ chart_filter.form.last_modified }} </div> </div> <div class="col-md-1 col-sm-4 pt-1"> </br> <button class="btn btn-secondary btn-lg" type="submit">Search</button> </div> </div> Number of available products: {{ products|length }} </form> Right now this … -
What does the u in a Django DateTimeField refer to?
In the source code for the DateTimeField (Python 3.8), it has the following error handling: default_error_messages = { 'invalid': _('“%(value)s” value has an invalid format. It must be in ' 'YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'), 'invalid_date': _("“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date."), 'invalid_datetime': _('“%(value)s” value has the correct format ' '(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) ' 'but it is an invalid date/time.'), } What is the uuuuu referring to? -
django rich text field data in email
I want to send Post data of a RTF Field (Rich text field) or a HTML Field data in a email, below are my code and it seems to be not happening, please guide me. models.py class Servicereport(models.Model): name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, null=True, blank=True) report = RichTextField(default='<p><b>sample data .... </b>') forms.py class ServicereportForm(ModelForm): class Meta: model = Servicereport fields = '__all__' widgets = { 'report': RichTextFormField() } views.py def createServicereport(request): form = ServicereportForm() if request.method == 'POST': form = ServicereportForm(request.POST) if form.is_valid(): subject = "SERVICE REPORT" html_message = render_to_string('report') message = EmailMessage(subject, html_message, 'from@email.com', [request.POST.get('email')]) message.content_subtype = 'html' message.send() form.save() return redirect('/') context = {'form': form} return render(request, 'service_report.html', context) I want to send POST data of RTF Field 'report" via email and the code will be in HTML, but I am unable to send, it is showing below error: TemplateDoesNotExist at /create_service_report/ report Request Method: POST Request URL: http://127.0.0.1:8000/create_service_report/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: report Exception Location: D:\development\website\venv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: D:\development\website\venv\Scripts\python.exe Python Version: 3.7.9 -
What is difference between explicit pk and auto pk in Django, which one is preferred?
→ Shows warning when using auto pk. (Auto-created primary key used when not defining a primary key type, by default) → Problem get saved pk in explicit defined: 19 class Post(models.Model): 20 id = models.IntegerField(primary_key=True) 21 timestamp = models.DateTimeField(auto_now_add=True) 22 content = models.TextField(max_length=4096) 23 user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="userPosts") The problem in: post = Post.objects.create( content = data.get("post"), user = request.user ) print(post.pk) Returns: None If comment line 20 above, Returns: 82 Why using auto-pk has warnings? While the explicit cant returns after saving the object? (Are there any solution?) -
Recreating JOIN query in django using select related
I am trying to figure out how to recreate the following SQL join in Django: SELECT taxonomy_request_id, proposed_taxonomy, data_source_field_name, data_source_table_name, data_source_database_name, data_source_server_name FROM taxonomy_process_field JOIN data_source_field dsf on dsf.id = taxonomy_process_field.data_source_field_id JOIN data_source_table dst on dst.id = dsf.data_source_table_id JOIN data_source_database dsd on dst.data_source_database_id = dsd.id JOIN data_source_server dss on dss.id = dsd.data_source_server_id WHERE taxonomy_request_id = 1 My models are: class DataSourceServer(models.Model): system = models.ForeignKey('System', models.DO_NOTHING, blank=True, null=True) data_source_server_name = models.TextField(blank=True, null=True) data_source_server_description = models.TextField(blank=True, null=True) server_location = models.ForeignKey('ServerLocation', models.DO_NOTHING, blank=True, null=True) data_source_server_owner_id = models.ForeignKey(Person, models.DO_NOTHING, blank=True, null=True) record_last_updated = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'data_source_server' class DataSourceDatabase(models.Model): data_source_server = models.ForeignKey('DataSourceServer', models.DO_NOTHING, blank=True, null=True) data_source_database_name = models.TextField(blank=True, null=True) data_source_database_description = models.TextField(blank=True, null=True) data_source_database_owner_id = models.ForeignKey(Person, models.DO_NOTHING, blank=True, null=True) record_last_updated = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'data_source_database' class DataSourceTable(models.Model): data_source_database = models.ForeignKey(DataSourceDatabase, models.DO_NOTHING, blank=True, null=True) data_source_table_name = models.TextField(blank=True, null=True) data_source_table_description = models.TextField(blank=True, null=True) data_source_table_owner_id = models.ForeignKey(Person, models.DO_NOTHING, blank=True, null=True) record_last_updated = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'data_source_table' class DataSourceField(models.Model): data_source_table = models.ForeignKey('DataSourceTable', models.DO_NOTHING, blank=True, null=True) data_source_field_name = models.TextField(blank=True, null=True) data_source_field_data_type = models.TextField(blank=True, null=True) data_source_field_data_len = models.TextField(blank=True, null=True) record_last_updated = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'data_source_field' class … -
How to implement feature flags efficiently for a backend?
Doesn't matter it is a web app or api, we need feature flags. If we don't need separate flags per user groups, the same flags works on all site. We don't update these flags too frequently. In this situation there are some options to store this flags. I believe the effects are similar for any framework such as Django, NodeJs, Rails, Spring. Database: We can store the flags in database, but the drawback it that, each time we access to a flag, it connects to database. Database + Application Constants: Application can read and cache the flags at the boot time. The drawback is that when we update a setting we have to restart all processes. Redis: Faster than database but the management is more hassle. SaaS Service: The slowest one because it works with connections to outside. Environment variables: Works native but updating them is not comfortable process, plus requires restart. I am curious if someone uses a way better than those. Or a technique removes the drawback. Thanks. I am looking the best way to implementing feature flags. -
How to add another dictionary entry in a nested python dictionary
I would like to make a dictionary in the dictionary. I have this code dictionary = {} for g in genre: total = 0 products = Product.objects.filter(genre=g) for product in products: total += product.popularity dictionary[g.category] = {g.name: total} I would like it to look like this, for example {'book': {'Horror':0, 'Comedy:0}, 'cd': {'Disco': 0, 'Rap': 0}} -
Why is mypy not inferring Django CharField choices as type with django-stubs?
I have a Django model with a field that is a models.CharField with choices: from django.db import models class MyChoice(models.TextChoices): FOO = "foo", _("foo") BAR = "bar", _("bar") BAZ = "baz", _("baz") class MyModel(models.Model): my_field = models.CharField(choices=MyChoice.choices, max_length=64) Then, if I use this choice field in a function that has it as a typed parameter, mypy catches it as an error. def use_choice(choice: MyChoice) -> None: pass def call_use_choice(model: MyModel) -> None: use_choice(model.my_field) # error: Argument 1 to "use_choice" has incompatible type "str"; expected "MyChoice" [arg-type] My configuration is as follows: # pyproject.toml [tool.poetry.dependencies] python = ">=3.10,<3.11" Django = "^3.2.8" [tool.poetry.dependencies] mypy = "^1.1.1" django-stubs = "^1.16.0" # mypy.ini [mypy] python_version = 3.10 ignore_missing_imports = True plugins = mypy_django_plugin.main [mypy.plugins.django-stubs] django_settings_module = "config.settings" Why is this happening? -
Looking for alternatives to Celery for running background tasks
I'm building an application using Django Rest Framework. One of the requirements is to initiate/maintain background tasks that will continuously monitor some cloud instances and update the database. For this, I used Celery in the way of creating Celery tasks via DRF code. However, it didn't help on long run since Celery was not able to scale up and became unstable. So, please suggest any alternate software/ methodology to accomplish the task. Thanks -
Migrating string column into array column django postgresql
In my models I have old field tag and created new one tags. tag = models.CharField(max_length=64, null=True, default=None, db_index=True, choices=[(tag, tag) for tag in TAGS]) tags = ArrayField(models.CharField(max_length=64, choices=[(tag, tag) for tag in TAGS]), db_index=True, null=True). Column tag have only strings, for example 'APPLE' or 'PEAR'. I want that column tags to be an array of one string after migrations. In my migrations after creating new field and before deleting old one I want to transfer data from column tag into tags. I tried using raw sql: cursor.execute("UPDATE form_builder_formfield SET tags = ARRAY[tag] WHERE tag IS NOT NULL") but this is not working. I recived errors: django.db.utils.DataError: malformed array literal: "["APPLE"]" "[" must introduce explicitly-specified array dimensions. I also tried using django queryset but I always end with this errors above. Any ideas how to do it? -
Problem with save data from popup form in Django
I have a problem with save data from popup form to sqlite database via django. My part code : dash.html: BUTTON FOR POPUP FORM <div class="card-footer clearfix"> <a href="" type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#newItem"><i class="fas fa-plus"></i> Add item</a> </div> POPUP CODE <div class="modal-content"> <div class="card card-success"> <div class="card-header"> <h3 class="card-title"><b>Add Item</b></h3> </div> <div class="card-body"> <form action="" method="post"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label> Item Name:</label> <input class="form-control form-control-lg" name="item_name" type="text" placeholder="Item name"> </div> </div> <div class="col-sm-6"> <!-- text input --> <div class="form-group"> <label> Item size:</label> <input class="form-control form-control-lg" name="item_size"type="text" placeholder="Item size"> </div> </div> <!-- /.card-body --> <div class="modal-footer"> <input type="submit" class="btn btn-default" value="submit"></input> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> popup Code is a part of dash.html models.py : class itemModel(models.Model): name = models.CharField(max_length=50) size = models.CharField(max_length=20) def __str__(self): return self.name I use SQLITE3 as a default database. forms.py: from django import forms from .models import itemModel class itemForm(forms.ModelForm): class Meta: model = itemModel fields = ["item_name", "item_size"] views.py: from django.shortcuts import redirect from dashboard.models import addItem def addItem(request): if request.method == "POST": name = request.POST['item_name'] size = request.POST['item_size'] itemModel.objects.create(Name=name, size=size) return redirect('dashboard') urls.py: from django.urls import path from . import views urlpatterns = … -
updating a django webpage as a result of information from a websocket from an external script
i have a django project and an external script. ive recently learened websockets and i am able to send info from my external script to my django consumers.py (which handles the websockets) however im struggling to update the django page based upon the info being passed from my external script. my original consumers.py in my django project class MiConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(text_data = json.dumps({ 'type' : 'connection_established', 'message': 'you are now connected!' })) async def receive(self, text_data=None, bytes_data=None): message = json.loads(text_data) print(message) if "ogilvie = free" in message: print("ogilvie = free") ogilvie_free = True elif "ogilvie = busy" in message: print("ogilvie = busy") ogilvie_free = False message = json.dumps({'message': message}) await self.send(message) at first i was looking for possibilities to directly change the webpage from here, but started to think that was impossible. so then i tried to have consumers.py pass on information to my html, after the consumers.py had recieved information from my external script. the js in my html is below, this does connect to my django consumers.py file. but never recieves anything more than the initial connection message from the connect function const socket = new WebSocket('ws://localhost:8000/ws/'); socket.addEventListener('message', function(event) { console.log("good socket") const message = JSON.parse(event.data).message;//.toString(); … -
Django Form Displaying Form Error on GET Method
I have been using django web framework for some time now, I would love to write a custom password change form without using the default provided by django or third-party packages. I have tried following a similar pattern used in django SetPasswordForm and PasswordChangeForm My Current Implementation project/app/forms.py class ChangePasswordForm(forms.Form): old_password = forms.CharField(max_length=50, ) password1 = forms.CharField(max_length=50, ) password2 = forms.CharField(max_length=50, ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() old_password = cleaned_data.get('old_password') password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') # Validate new user password if password1 and password2 and old_password: if not self.user.check_password(old_password): raise ValidationError("Invalid old password, please enter your current password") elif password1 != password2: raise ValidationError("Password mismatch, please re-type same password") password_validation.validate_password(password1, self.user) return cleaned_data def save(self, commit=True): new_password = self.cleaned_data.get('password2') self.user.set_password(new_password) if commit: self.user.save() return self.user project/app/views.py class ChangePasswordView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): form = ChangePasswordForm(request.user, request.POST) context = { 'form': form, } return render(request, 'auth/change_password.html', context) def post(self, request, *args, **kwargs): form = ChangePasswordForm(request.user, request.POST) if form.is_valid(): user = form.save() # log user out of all active sessions update_session_auth_hash(request, user) messages.success(request, "Password updated successfully") return redirect('custom_redirect') return redirect('custom_redirect')) HTML Template Rendering <form class="card-style mb-30" action="{% url 'account_change_password' … -
Django Bootstrap Search Bar on Navigation Bar
I have made a search bar on the navigation bar. However, when I search it, it has no response. I have made a separated file for my navigation bar - navbar.html. navbar.html <nav> <ul> {% if user.is_authenticated %} <form class="form-inline" action="{% url 'search_journal' %}" method="GET"> <input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> <li><a href="{% url 'journal_list' %}">HOME</a></li> <li><a href="{% url 'journal_list_favourite' %}">FAVORITE</a></li> <li><a href="{% url 'logout' %}">LOGOUT</a></li> <li class="profile"> <div class="profile-img-container"> <a href="{% url 'profile' %}"><img id="profile-img" src="{{ user.profile.image.url }}" alt="Profile Picture"></a> </div> <li class="nav-item"> <a class="nav-link active" href="#">Hi {{user.username}}</a> </li> {% else %} <li class="nav-item"> <a>Please Login!</a> </li> {% endif %} </ul> </nav> views.py @login_required def search_journal(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups= Q(title__icontains=query) | Q(content__icontains=query) results= Journal.objects.filter(lookups).distinct() context={'results': results, 'submitbutton': submitbutton} return render(request, 'audioJournaling/search_journal.html', context) else: return render(request, 'audioJournaling/search_journal.html') else: return render(request, 'audioJournaling/search_journal.html') search_journal.html {% extends "base.html" %} {% block content %} <h1>Search Page</h1> <br/> <!-- <form action="{% url 'search_journal' %}" method="GET" value="{{request.GET.q}}"> Search <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search posts"/> <input type="submit" name="submit" value="Search"/> </form> --> {% if submitbutton == 'Search' and request.GET.q != '' %} {% if results %} <h1>Results for <b>{{ … -
GDAL reprojection error: in method 'Geometry_Transform', argument 2 of type 'OSRCoordinateTransformationShadow *' error in Cartoview and Terria JS
While uploading layers in cartoview, these are uploaded but there is the error message in the console: GDAL reprojection error: in method 'Geometry_Transform', argument 2 of type 'OSRCoordinateTransformationShadow *' which is why in Terria JS the map is not shown. i.e. the integration is not complete. Can someone kindly help identify the issue? Thanks in advance.