Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow HTML characters in Django Rest Framework serializers
I am returning HTML text from Django Rest Framework, but special characters are rewritten as "HTML safe" text. How do I prevent this behaviour? I know there is a mark_safe() function in Django, but that would require me to rewrite the serializer. Is there an easy way to do this offered by DRF? Here is my serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ("html_text",) Note that the text is safe and only input by admins, not by end users. -
TemplateSyntaxError at GET in Django template
I'm working on Django template and setting Conditional branching whether there is a "query" or not. {% if {{ request.GET.query }} == "" %} <td><a href="/detail/{{item.id}}/{{item.item_hs6}}">detail</a></td> {% else %} <td><a href="/detail/{{item.id}}/{{item.item_hs6}}/{{ request.GET.query }}">detail</a></td> {% endif %} When I execute the above code, the error occurs here. Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{' from '{{' I know the code below is something wrong {% if {{ request.GET.query }} == "" %} How should I judge whether there is a query or not in Template? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Why my form shows a blank date field to be filled manually, instead of providing me a calendar to choose a specific date?
I created a model which has two date fields. When I use the form in the admin panel, I get to choose the dates from the attached calendar, but when I render the same form on the web-page, it gives me a blank field. There is no calendar. Below are my codes: models.py: from django.db import models from django.core.validators import RegexValidator from django.db.models.deletion import CASCADE # Create your models here. class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) class InitialData(models.Model): pattern = RegexValidator(r'RT\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') pattern1 = RegexValidator(r'OOPL\/D\/00[0-9]', 'Enter Case Number properly!') case_number=models.CharField(max_length=10, primary_key=True, unique=True, validators=[pattern1], blank=True) date_of_admission=models.DateField(default=None) date_of_discharge=models.DateField(default=None) name=models.CharField(max_length=100, default=None) mr_uid=models.IntegerField(default=None) rt_number=models.CharField(max_length=15, blank=False, validators=[pattern], default=None) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) forms.py: class TrackReportForm(ModelForm): class Meta: model=InitialData fields=('case_number', 'date_of_admission', 'date_of_discharge', 'name', 'mr_uid', 'rt_number', 'diagnosis') class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields=('diagnosis',) views.py: def initialview(request): if request.method=='POST': fm_diagnosis=DiagnosisForm(request.POST) fm_initialdata=TrackReportForm(request.POST) if fm_diagnosis.is_valid() and fm_initialdata.is_valid: diagnosis=fm_diagnosis.save() initial=fm_initialdata.save(False) initial.diagnosis=diagnosis initial.save() fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) else: fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) URLs: from account import views urlpatterns = [ path('admin/', admin.site.urls), path('data/', views.initialview), ] template: <body> <form action="" method="post" novalidate> {% csrf_token %} {{form1.as_p}} {{form2.as_p}} <button type="submit">Save</button> </form> </body> Any suggestions? -
django upload files using class based view
I am facing this problem when I try to upload files it doesn't work from the html page but from the admin panel it works. my model is: class contrat(models.Model): contrtID = models.CharField(max_length=25,unique=True) SHRPath = models.FileField(upload_to='contrats/') post_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.contrtID def delete(self, *args, **kwargs): self.SHRPath.delete() super().delete(*args, **kwargs) def get_absolute_url(self): return reverse('Scheduling') class Meta: ordering = ('-post_date',) The form is: class contrat_F(forms.ModelForm): contrtID = forms.CharField(label='Code',max_length=25) class Meta: model= contrat fields=('contrtID','SHRPath') The Views.py is: class Contratadd(LoginRequiredMixin, CreateView): model = contrat template_name = 'Home/Scheduling/Add_contract.html' form_class= contrat_F def form_valid(self, form): form =contrat_F(request.POST, request.FILES) form.instance.author = self.request.user return super().form_valid(form) the urls.py is: path('Add_Contrat/', views.Contratadd.as_view(), name='Add_Contrat'), the page html code is: <form method="POST"> {% csrf_token %} <div class="border p-2 mb-3 mt-3 border-secondary"> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.contrtID|as_crispy_field }} </div> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{form.SHRPath}} </div> </div> </div> <input class="btn btn-success mb-4" type="submit" value="ADD Contrat"> </form> THIS IS IN THE PAGE BUT IT DOESN'T UPLOAD THE FILE! where is my mistake please? -
Different number of columns needed for last page of paginated Django template
My question concerns needing to style the last page of a paginated Django template so that it displays as only one column if there are fewer than the maximum 6 entries on the page (the other pages of the template are displaying in two columns). I am using Django 3.1.7 I have a Django template that uses the following view: Django View: class SoundSeedView(generic.ListView): model = SoundFile fields = ['sound_file'] template_name = 'seed_history.html' paginate_by = 6 I am using two columns on my template as given below: CSS: #columns { columns: 2; } Django template: <h1>Sound file list</h1> <button id="comments-button" onclick="displayComments()">View Comments</button> <div id="blackbackground"> </div> <div class="container" id="columns"> {% for document in object_list%} <div id= "entryContainer"> <h2 id = 'ttitle'> {{ document.sound_file.name }} </h2> <p> Created on: {{ document.created_on}} </p> <div id = "nameTrunc"> <p> Created by: {{ document.user }} </p> </div> <div id="nc" class = "new-comments"> <audio controls class="thisAudio" id="player"> <source src="{{ document.sound_file.url }}"> </audio> {% if user.is_authenticated %} <a id = 'downloadbutton' class = 'dwnld-button' href="{{ document.sound_file.url }}" download >Download</a> {% endif %} <p class = "comments-text"> Comments: {{ document.comments }}</p> </div> </div> {% endfor %} </div> My problem is that if there are fewer than the maximum … -
running some codes after return response in python
My main question is how can i do something after return response. I have some codes like this : async def get(self, request): #do something here return Response(status=status.HTTP_200_OK) #do something after response... I used thread but it didn't work -
Django ReactJS: Pass array from JavaScript frontend to Django Python backend
I've made a website with Django and React JS. I'm trying to pass an array pict from my JavaScript frontend to Django, the Python backend. let pict = []; pictureEl.addEventListener(`click`, function () { console.log(`Take Pic`); pict += webcam.snap(); console.log(pict); }); pict is an array of images taken by the camera. How would I pass it to the backend? -
Configuring nginx to drop requests with no HTTP HOST header
The docs suggest that the following server block will drop all requests without a HTTP HOST header: server { listen 80; server_name ""; return 444; } However, when I make a request without a header, curl -I https://example.com/ -H "Host:" -v --http1.0 --insecure I'm getting an alert from Django, so it seems to be getting past nginx: Invalid HTTP_HOST header: '/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. I've also tried to implement this solution, but still get the same results. I'm wondering whether this has something to do with the extra server blocks automatically created by Certbot. Stopping the emails from Django isn't my desired solution, I'd rather nginx drops these requests before they hit the app. The nginx config file is being read correctly, because I can add a return 444; to the main server block and it'll block everything. Here's the entire /etc/nginx/sites-available/<name> config, with attempts at both solutions included: server { listen 80; server_name ""; return 444; } server { server_name example.com; if ($host !~* ^(example.com)$ ) { return 444; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl certificate /path/to/cert ssl_certificate_key /path_to_key include … -
Celery/Django worker detect when there are no jobs left
I have a Celery/Django worker connected via RabbitMQ to the server. When the worker finishes a job I want it to terminate if there are no jobs left - how can I achieve this? -
comment added by the logging in user didn't properly save
I have been currently working on an easy Django website. An error came up when I tried to implement a function that users can add comments to blogs. I succeeded to show the form where users can write their comments, but even if I pressed the add button, didn't save properly. I don't even know where I made a mistake coz I knew how to post and save information to the database. so, I ask you to help!! # add_comment.html {% extends 'base.html' %} {% block title %}|コメント追加{% endblock %} {% block content %} <div class="header-bar"> <a href="{% url 'blog' blog.id %}">&#8592; 戻る</a> </div> <div class="body-container blog"> <div class="body-header"> <h1>コメント追加</h1> </div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button class='button' type="submit">追加</button> </form> </div> </div> {% endblock %} # views.py @login_required def add_comment(request, pk): blog = get_object_or_404(Blog, pk=pk) if request.method == 'post': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.save() return redirect('blog', pk=blog.pk) else: form = CommentForm() context = { 'form': form, } return render(request, 'blog/add_comment.html', context) # urls.py from django.urls import path from . import views from .views import BlogCreate, BlogUpdate, BlogDelete, BlogList # blogs urlpatterns = [ path('', views.index, name='latest_blogs'), path('my_blogs/', views.my_blogs, name='my_blogs'), path('my_blogs/my_blog_search', … -
django configuration and conda error message
This error keeps showing up in my django configuration, and ends the server. I used the same config for the past year with django and conda, never had an issue and (as far as I know) I haven't made any change. Does anyone know what is going on here ? This error keeps showing up in my django configuration, and ends the server. I used the same config for the past year with django and conda, never had an issue and (as far as I know) I haven't made any change. Does anyone know what is going on here ? This is the error message I receive Traceback (most recent call last): File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", line 599, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", line 584, in start_django reloader.run(django_main_thread) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", line 299, in run self.run_loop() File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", line 305, in run_loop next(ticker) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", line 353, in tick self.notify_file_changed(filepath) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", line 328, in notify_file_changed trigger_reload(path) File "C:\Users\marcd\.conda\envs\mydjangoenv\lib\site-packages\django\utils\autoreload.py", … -
Confusion on choosing a language/framework, hosting provider and domain registrar to create a website for my Online Learning Platform
I have multiple questions on the same topic! I am thinking of making an online course website (a big project) with my friends by coding, for this, I have chosen Django as a backend (can suggest me other languages/frameworks). Before starting the project I want to finalize my plans, like which hosting provider to choose, what domain(.com, .net, or so on) to choose, after all, I have a low budget for this. My website will not have subdomains for the first 6 months, but according to my plans, I will add some sub-domains for forums and blogs. So for this, could anyone help me to choose a hosting provider and domain registrar? Hosting/domain Providers from Nepal would be more preferable as I am from Nepal, but will this even matter in choosing a hosting service? At least answer me: Which language/framework to choose Which hosting provider to choose What domain to choose -
how to develop a calendar feature through django rest framework? [closed]
I am working on a project to create timesheet for employees to fill their work hours. For that I need to show a calendar somewhere on a page. I have gone through videos where I got to know how to achieve the objective through Django. However, I am looking for a solution through Djangorestframework. I did come across a module called django-events-rest-framework, here is its pypi online document. I have tried using it through POSTMAN, but I do not think its the thing that I am looking for . Can somebody suggest please? Thank you. -
Django: Python check to see if a string contains only whitespaces not working using isspace method [closed]
I have many student profiles which are represented by a string. It was formed by the concatenation of various fields. However, if a student has not provided any detail, this string shall be having only whitespaces as I left spaces during fields when concatenating them together. I want to make a check first. I used the isspace method but it aint working Here is the code snippet: for id, profile in student_profiles: // it is giving me all the ids and profiles even if blank if not profile.isspace(): print(id) The output is like this: 3 I am an accomplished coder 6 7 8 JAVA SOFTWARE DEVELOPMENT ENGINEER 9 -
How to check if the file is uploaded to form in Javascript?
I created a form with Django. What I want is A warning popup appears when a user does not upload files to the system. I try to write a code bu it is not working. It works whether the file is uploaded or not. How can I fixed it? my code: <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-warning" name="is-file" onclick="return confirm_submit()" id="isEmpty">Make Non-report Analysis</button> </form> ... <script type="text/javascript"> function confirm_submit() { var x = document.getElementById("isEmpty").value; window.alert(x) if (!x){ return confirm('are you sure?'); } } </script> forms.py class PdfForm(forms.ModelForm): class Meta: model = Pdf fields = ['title', 'pdf', 'document_type', 'year', 'payment_behavior'] labels = { "payment_behavior": "Please Select the Payment Behavior of the Customer: ", "document_type": "Document Type", "title": "Document Name", "pdf": "Please Select a File to Upload", "year": "Financial Table Year" } models.py class Pdf(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True) document_type = models.CharField(max_length=200, default='Select', choices=CHOICES) ... -
how to show calendar through django rest framework?
I am working on a project to create timesheet for employees to fill their work hours. For that I need to show a calendar somewhere on a page. I have gone through videos where I got to know how to achieve the objective through Django. However, I am looking for a solution through Djangorestframework. I did come across a module called django-events-rest-framework, here is its pypi online document. I have tried using it through POSTMAN, but I do not think its the thing that I am looking for . Can somebody suggest please? Thank you. -
django: issue navigating from one page to another
I'm trying to run a django project on my system. my landing page url is localhost/landing_page/ To navigate from landing_page to another_page, in the <landing_page>.html i'm using: <a href='xxx/another_page.html'> click here </a> it's getting redirected to 'localhost/landing_page/xxx/another_page.html' and throwing an error instead of getting redirected to 'localhost/xxx/another_page.html'. how do i direct it to 'localhost/xxx/another_page.html' ? -
Djongo fails to migrate contenttypes migrations
I am using djongo for MongoDB connection in my project. I have cleaned all previous migrations, deleted the sqlite database and made migrations for the app again. Here are all the migrations that need to be run python3 manage.py showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices admin_interface [X] 0001_initial [X] 0002_add_related_modal [X] 0003_add_logo_color [X] 0004_rename_title_color [X] 0005_add_recent_actions_visible [X] 0006_bytes_to_str [X] 0007_add_favicon [X] 0008_change_related_modal_background_opacity_type [X] 0009_add_enviroment [X] 0010_add_localization [X] 0011_add_environment_options [X] 0012_update_verbose_names [X] 0013_add_related_modal_close_button [X] 0014_name_unique [X] 0015_add_language_chooser_active [X] 0016_add_language_chooser_display [X] 0017_change_list_filter_dropdown [X] 0018_theme_list_filter_sticky [X] 0019_add_form_sticky app [X] 0001_initial auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial It runs all migrations except the contenttypes migrations. Here is the output from python3 manage.py migrate Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying auth.0001_initial...This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using KEY" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://nesdis.github.io/djongo/support/ OK … -
I am facing myapp not found problem in Django-Heroku
Its my first heroku-Django project. Its working fine locally But when I tired to run on heroku, it deployed successfully, but shows the error in gunicorn (since I am using windows) So, I used 'waitress-serve --listen=*:8000 myapp.wsgi:application' in place of gunicorn. it again deployed successfully, but not working on heroku. It is Showing the error of "There was an exception (ModuleNotFoundError) importing your module. ", "No module named 'myapp'" in heroku logs. Please suggest a solution Thanks -
How to display or render multiple forms in django
I'm currently working on a personal project where in a page (purchases page), there will be the main form (includes product name, product category and product specifications fields). now, there is a link "Add New Product Category" that activates the modal. This modal includes a separate form. What you are seeing is the final output or what I want the page to be, i only did that in html, no django coding involve. My (stupid) question is, how am i going to display BOTH forms? I don't understand how {{form}} works. I successfully rendered the productCategoryForm in the modal by using the code {{form}} but when I do the same in the second form productDetailsForm it's not rendering or displaying. It's blank. I'm not sure how is this going to work. Below is my Views.py and Forms.py codes. Views.py def addNewCategory(response): if response.method == "POST": form = productCategoryForm(response.POST) if form.is_valid(): a = form.cleaned_data["productCateg"] b = productCategory(productCat=a) b.save() return HttpResponseRedirect("/acctg/purchases/") else: form = productCategoryForm() return render(response, 'purchases.html', {"form": form}) def addNewProduct(response): form = productDetailsForm(response.POST) return render(response, 'purchases.html', {"form": form) Forms.py class productCategoryForm(forms.Form): productCateg = forms.CharField(label="Product Category", max_length=100, required=True, widget= forms.TextInput(attrs={'class':'form-control col-sm-8 col-form-label'})) class productDetailsForm(forms.Form): productName = forms.CharField(label="Product Name", max_length=100, required=True, widget= … -
Heroku site throws ModuleNotFoundError: No module named 'config'
I am using Pycharm and django to launch a test website on heroku but the site shows an Application Error: Heroku Log: (venv) C:\Users\Artur\PycharmProjects\dfb2_home_about\pages>heroku logs 2021-06-25T06:27:56.488118+00:00 app[web.1]: return self.load_wsgiapp() 2021-06-25T06:27:56.488119+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-06-25T06:27:56.488119+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-06-25T06:27:56.488120+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app 2021-06-25T06:27:56.488120+00:00 app[web.1]: mod = importlib.import_module(module) 2021-06-25T06:27:56.488121+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2021-06-25T06:27:56.488121+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-06-25T06:27:56.488122+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-06-25T06:27:56.488122+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-06-25T06:27:56.488122+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked 2021-06-25T06:27:56.488123+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-06-25T06:27:56.488123+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-06-25T06:27:56.488124+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-06-25T06:27:56.488124+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-06-25T06:27:56.488124+00:00 app[web.1]: ModuleNotFoundError: No module named 'config' 2021-06-25T06:27:56.488217+00:00 app[web.1]: [2021-06-25 06:27:56 +0000] [8] [INFO] Worker exiting (pid: 8) 2021-06-25T06:27:56.524674+00:00 app[web.1]: [2021-06-25 06:27:56 +0000] [4] [INFO] Shutting down: Master 2021-06-25T06:27:56.524822+00:00 app[web.1]: [2021-06-25 06:27:56 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-06-25T06:27:56.639146+00:00 heroku[web.1]: Process exited with status 3 2021-06-25T06:27:56.714706+00:00 heroku[web.1]: State changed from starting to crashed 2021-06-25T06:27:56.718477+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-25T06:28:01.999568+00:00 heroku[web.1]: Starting process with command … -
MultiValueDictKeyError at edit
I writing a code for my class to create a list from users input. on the list there is an option for editing each entries; however when i click on my edit bottom i get multi value error. Could anyone please let know how to fix this error? My html part for the list: Your wish list: <table> <thead style="background-color: rgb(226, 220, 220)"> <th>Item</th> <th>Date added</th> <th>Actions</th> </thead> <tbody> {% for wish in all_wishes %} <tr> <td><h5><a href="/wishes/{{wish.id}}">{{wish.wish}}</a></h5></td> <td> Added on {{wish.created_at}} </td> <td> <a href="/wishes/{{wish.id}}/delete" role="button">Remove</a> | <a href="/wishes/{{wish.id}}/edit">Edit</a> | <a href="/wishes/{{wish.id}}/granted" role="button">Granted!</a> </td> </tr> {% endfor %} </tbody> </table> My urls: I removed other urls to make it clean here from django.urls import path from .import views urlpatterns = [ path("wishes/<int:wish_id>/edit", views.edit), ] my views.py (edit part): def edit(request, wish_id): wish = Wish.objects.get(id=wish_id) wish.description = request.POST['description'] wish.save() return redirect("wishes/showall.html") redirect to html on top My Model: class Wish(models.Model): description = models.CharField(max_length=255) My error message: MultiValueDictKeyError at /wishes/32/edit 'description' Request Method: GET Request URL: http://localhost:8000/wishes/32/edit Django Version: 2.2 Exception Type: MultiValueDictKeyError Exception Value: 'description' C:\Users\wishlist_app\views.py in edit wish.description = request.POST['description'] -
Django display selected multi checkbox on template
I have a form with multi checkbox selection and a template that displays the form (with some additional styling so the checkboxes are in a dropdown). I want to display the selected by the user checkboxes next to the field. How do I access the selected values from the field in my template? Form: class ReadData(forms.Form): def __init__(self, elems, *args, **kwargs): super().__init__(*args, **kwargs) for i, elem in enumerate(elems): self.fields['class-%d' % i] = forms.MultipleChoiceField(label='Select', widget=forms.CheckboxSelectMultiple, choices=CHOICES, required=False) Template: {% for form in form.visible_fields %} <div class="field-element"> <button class="btn btn-stereo dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <label>{{ form.label_tag}}</label> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <div class="list-stereo">{{form}}</div> </div> </div> -
Why use aggregate to find average value instead of using tutal_sum/n in django
Here we calculate using aggregate >>> avg = Book.objects.aggregate(average_price=Avg('price')) {'average_price': 34.35} But why we don’t use below concept in above. a = Books.objects.all() Avg = sum([x.price for x in a])/len(a) 34.35 I want to know use aggregate rather than second procees. -
'UserManager' object has no attribute 'validate'
My usual registration and login validators stopped working and I'm banging my head against the wall trying to figure out why. This is the error: AttributeError at /register 'UserManager' object has no attribute 'validate' Models.py class UserManager(models.Manager): def validate(self, postData): errors = {} if len(postData['first_name']) < 3: errors['first_name'] = 'First Name must be at least 2 characters' if len(postData['last_name']) < 3: errors['last_name'] = 'Last Name must be at least 2 characters' EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') if not EMAIL_REGEX.match(postData['email']): errors['email'] = "Invalid email address!" email_check=User.objects.filter(email=postData['email']) if email_check: errors['email'] = ("Email address already taken!") if len(postData['password']) < 8 : errors['password'] = 'Password must be at least 8 characters' if postData['password'] != postData['confirm_password']: errors['password'] = 'Passwords do not match' return errors views.py def register(request): if request.method == "GET": return redirect('/') errors = User.objects.validate(request.POST) if errors: for e in errors.values(): messages.error(request, e) return redirect('/') else: new_user = User.objects.register(request.POST) request.session['user_id'] = new_user.id return redirect('/profile')