Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using javascript or python regular expressions I want to determine if the number is 1-99 how to make it?
var category = prompt("where do you go? (1~99)", ""); hello Using regular expressions I want to determine if the category is 1-99. How can I solve it? Thank you if you let me know. -
How to populate the form with value from current page?
I am learning to build a Post-comment app on Django. I understand how and why the current user can be assigned as author in the Comment form. But I do not understand how the post_id can be assigned to connect the comment with a particular post. Tried using various methods obtained from searching the web. I keep getting various errors- TypeError, KeyError, ValueError etc. My models.py is set up like this: class Post(models.Model): pid = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home')#, kwargs={'pk':self.pk}) class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) The views.py with the comment create view is as follows: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['comment'] def form_valid(self, form,**kwargs): form.instance.author = self.request.user form.instance.post_id = self.kwargs['post_id'] # IS THE ABOVE LINE CORRECT? return super().form_valid(form) The Answer button is on the home page included in every post block. The html for the same with the url for it is as below: {% extends "blog/base.html" %} {% block … -
how to implement form based cart/basket in django where you select the items from form based ui without any image?
Once you select the items from form and click on add to cart it should take you to checkout the cart, do payment and close the transaction. -
How to create the list of users who enter the page?
I'm new into Django and as the training I decided to create a blog application. But I have a one problem. I don't know how to create a view where I will can see which users saw this post. It can be simple, only user nick and date. -
I get a MissingSchema error within my python file that is trying to read a local JSON file
This is the error I get when I try to load my indexes.html page: MissingSchema at /indexes/ Invalid URL "<_io.TextIOWrapper name='tableInfo.json' mode='r' encoding='cp1252'>": No schema supplied. Perhaps you meant http://<_io.TextIOWrapper name='tableInfo.json' mode='r' encoding='cp1252'>? I am not sure why this is happening, I am trying to read from a local JSON file and display it in a table This is my views.py code: def indexes(request): with open('tableInfo.json') as json_file: if request.POST: form = Sea(request.POST) po = request.POST.get('poNo') dc = request.POST.get('dcNo') vendor = request.POST.get('vendor') order_date = request.POST.get('order_date') delivery_date = request.POST.get('delivery_date') payload = {} if len(po) > 8: payload['poNo'] = po if "DC" in dc: payload['dcNo'] = dc if len(vendor) > 8: payload['vendorNo'] = vendor if len(order_date) > 6: payload['orderDate'] = order_date if len(delivery_date) > 6: payload['deliveryDate'] = delivery_date data = json.loads((requests.get(json_file, payload)).content) if data['returnCode'] == 0: resultList = data['resultList'] else: resultList = [] else: form = Sea() resultList = [] context = { 'data': resultList, 'form': form } return render(request, 'users/indexes.html', context) -
How to get urls and views correct with this code
Hey guys I'm trying to set up my chatterbot to work with Django but for some reason I can't seem to get the urls and views correct for Django to show the chatbot on my server. Django 2.1.1 is the version I'm running on with Python 3.7 as my interpreter. My chatbot is in the same project in a folder called Sili with it's own views.py and urls.py in that folder. I have tried this but no luck from django.contrib import admin from sili import views urlpatterns = [ path('admin/', admin.site.urls), path('', home.views), ] this is what is in my views.py from django.shortcuts import render,render_to_response from django.http import HttpResponse import json from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot # from chatterbot.trainers import ChatterBotCorpusTrainer chatbot=ChatBot('Sili',trainer='chatterbot.trainers.ChatterBotCorpusTrainer') # Train based on the english corpus chatbot.train("chatterbot.corpus.english") @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) def home(request, template_name="home.html"): context = {'title': 'Sili Chatbot Version 1.0'} return render_to_response(template_name, context) what do I add to the urls.py so that it shows … -
Override default templates in Django admin site
I'd like to override some of the django admin templates found in django/contrib/admin/templates/admin. I would just like to get rid of some unnecessary parts in some templates. I'd like to do so without copying and pasting the templates, minus the parts I don't want, into the templates/admin/my_app/ directory like they mention here https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#overriding-admin-templates. Is there any way other approach to this? -
Keep getting "IntegrityError FOREIGN KEY constraint failed" when i am trying to delete a post
Every time i try to delete a post i keeping getting this error, but my delete button use to work before. I think it has something to do with the on_delete attribute but i changed its value a few times and it still did not work. //models.py from django.db import models from django.conf import settings from django.urls import reverse User = settings.AUTH_USER_MODEL class PostManager(models.Manager): def search(self, query): qs = self.get_queryset().filter(title__icontains=query) if qs: return qs return None def get_by_id(self, id): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() else: return None # Create your models here. class PostModel(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=50) message = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def __str__(self): return self.title objects = PostManager() def get_total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse("birdpost:detail", kwargs={"id": self.id}) def get_like_url(self): return reverse("birdpost:like-toggle", kwargs={"id": self.id}) def get_delete_url(self): return reverse("birdpost:delete_post", kwargs={"id": self.id}) //views.py def del_post(request, id): obj = get_object_or_404(PostModel, id=id) if request.user != obj.user: print("Ooh no looks like this post is not yours... ") else: obj.delete() return redirect("home") -
How can i combine two ModelForms in a single django views
Goodday everyone, so i have two models, one of which has a foreignkey field pointing to the other and i have model forms for each model class and in my views.py, i would like to make the model with the foreignkey point at the other model i made a modelforms (CharacterForm and RoleForm) in my forms.py which would show all fields but in my html, i would hide the player field (a foreignkey which points to the other model) so in my views.py i would automatically make the newly created character the player. models.py class Character(models.Model): #some fields class Role(models.Model): player = models.ForeignKey(Character, on_delete=models.PROTECT, related_name='the_player') views.py def NewRole(request): if request.method == 'POST' form = CharacterForm() formset = RoleForm() if all([form.is_valid, formset.is_valid]): role_player = form.save() formset.player = role_player formset.save() return redirect('index') else: form = CharacterForm() formset = RoleForm() return render(request, 'new_role.html', {'form':form, 'formset':formset}) i just wanted the player field under the role model to point at the Character model the user just created and i dont know the best way to do it. i thought this would work but i keep getting ForeignKey Constraint error. -
How to populate my django database with json that I scraped from a website
I have scraped data from a website using their API on a Django application. The data is JSON (a Python dictionary when I retrieve it on my end). The data has many, many fields. I want to store them in a database. I need to use their fields to create the structure of my database. Any help on this issue or on how to tackle it would be greatly appreciated. I apologize if my question is not concise enough, please let me know if there is anything I need to specify. I have seen many, many people saying to just populate it, such as this example How to populate a Django sqlite3 database. The issue is, there are so many fields that I cannot go and actually create the django model fields myself. From what I have read, it seems like I may be able to use serializers.ModelSerializer, although that seems to just populate a pre-existing db with already defined model. -
How to prevent primary key from appending to django rest framework url
I have a django project and i am trying to integrate django rest framework into it. I currently have a viewset and I want to do two things. I want to add two filter parameters into the url and grab them in the viewset and use them in the queryset to filter records that match those filters. I also want to prevent the primary key filter to append to the url when i try to access the viewsets... Here is the url: router.register(r'preferences/(?P<namespace>.+)/(?P<path>.+)', PreferencePathViewSet, basename='Preference-path') router.register(r'preferences/(?P<namespace>.+)', PreferenceNamespaceViewSet, basename='Preference-namespace') router.register(r'preferences', PreferenceUserViewSet, basename='Preference') Here is the viewsets: class PreferenceUserViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def get_queryset(self): queryset = Preference.objects.filter(user_id=1) return queryset class PreferenceNamespaceViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer lookup_namespace = 'namespace' def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def get_queryset(self): namespace = self.request.query_params.get('namespace') queryset = Preference.objects.filter(user_id=1, namespace=namespace) return queryset class PreferencePathViewSet(viewsets.ModelViewSet): model = Preference serializer_class = PreferenceSerializer lookup_namespace = 'namespace' lookup_path = 'path' def get_permissions(self): if self.action == 'create' … -
Azure development center unsupported python version error
I am attempting to get a Django website hosts on Azure that I build in Visual Studio. I am able to publish it and get a dedicated url, however in order to get the site to load properly I need to load my code to azure. So in the development center tab I tried creating a dev ops project to read from, I also tried to upload it through the github repo, with both options I get and error that I am running an unsupported version of python. I ran commands in my local project to see what versions I am using, which are as follows: python - 3.7.3 Django - 2.1 pip - 19.1.1 Command: "D:\home\site\deployments\tools\deploy.cmd" Handling python deployment. Creating app_offline.htm KuduSync.NET from: 'D:\home\site\repository' to: 'D:\home\site\wwwroot' Deleting app_offline.htm Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. Detecting Python runtime from site configuration Detected python-2.7 Found compatible virtual environment. Pip install requirements. Downloading/unpacking django>=2.1.6,<3.0 (from -r requirements.txt (line 1)) Running setup.py (path:D:\home\site\wwwroot\env\build\django\setup.py) egg_info for package django ========================== Unsupported Python version ========================== This version of Django requires Python 3.5, but you're trying to install it on Python 2.7. This may be because you are using a version … -
Django REST framework. How i can make export model in csv
I have the following models: class Student(models.Model): first_name = models.CharField(verbose_name='student first name', max_length=64) last_name = models.CharField(verbose_name='student last name', max_length=64) email = models.EmailField() class Meta: db_table = 'student' def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True, blank=True, default=None) end_date = models.DateField(null=True, blank=True, default=None) class Meta: db_table = 'course' def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE) student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE) completed = models.BooleanField(null=False, default=False) class Meta: db_table = 'course_participant' def __str__(self): return self.course, self.student And urs: urlpatterns = [ path('course', CourseAPIView.as_view()), path('course/<int:pk>/', CourseAPIDetailView.as_view()), path('student', StudentAPIView.as_view()), path('student/<int:pk>/', StudentAPIDetailView.as_view()), path('student/assigned_to_course', StudentAssignedToTheCourseAPIView.as_view()), path('student/assign_student_to_course', StudentAssignToCourse.as_view()), path('student/assigned_to_course/<int:pk>/', StudentAssignedToTheCourseDetailView.as_view()), path('student/report/<int:pk>/', StudentReportView.as_view()), ] I need made export some data in csv, in next format: student full name number of assigned courses to the student number of completed courses by student For example: Test Student,10, 3 Test Student1,12, 1 Test Student2,5, 3 Test Student3,5, 4 So, what view should be for it. I mean, how i can get data like student full name and etc. I will be grateful for the help -
Imported script executing itself in a unittest class even though if __name__ == "__main__" guard is present
Testing functions from an imported python script which creates django boilerplate leads to said function executing itself when the test is run. The testing file is in the same folder as the script being tested. The testing file includes unittest.main() as per the unittest documentation. The tested script also includes if __name__ == "__main__" under which is the main function calling all the other functions in the script. If I put if _name__ == "__main__" at the top of the tested script and run the entire script under that if block, the script still works as intended, however an ImportError is thrown upon running the testing file. Link to the script(It's not very long): https://github.com/PersonRP7/django_tests_generator_standalone/blob/functional_refactor/mts_functional.py import unittest import mts_functional class TestMakeTestStandalone(unittest.TestCase): def test_set_app_name(self): app_name = "one" response = mts_functional.set_app_name() self.assertEqual( response, "one" ) When I run the above test(either in Atom, or in the powershell, using python -m unittest discover), I am prompted for the app_name and if my answer corresponds to the app_name variable defined in the test_set_app_name(self), the test passes. If it doesn't, the test fails. I've also tried importing individual functions using from mts_functional import some_function, but the result was the same. I'm not sure if this … -
How to extend the event/occurrence models in django-scheduler
I'd like to augment events/occurrences in django-scheduler with three things: Location Invitees RSVPs For Location, my initial thought was to subclass Event and add Location as a foreign key to a Location class, but my assumption is that each occurrence saved won't then include Location, so if the location changes for one occurrence, I'll have nowhere to store that information. In this situation, is it recommended to create an EventRelation instead? Will I then be able to specify a different Location for one occurrence in a series? The EventRelation solution seems untidy to me, I'd prefer to keep models in classes for clarity and simplicity. I think Invitees is the same problem, so presumably I should use a similar solution? For RSVPs, I intend to make an RSVP class with Occurrence as a foreign key, and as far as I can tell that should work without any issues as long as I save the occurrence before attaching it to an RSVP? I've read all the docs, all the GitHub issues, various StackOverflow threads, the tests, the model source, etc, but it's still unclear what the "right" way to do it is. I found a PR which introduces abstract models: https://github.com/llazzaro/django-scheduler/pull/389 … -
How to call a template?
How can I call the the about.html from the following index.html? What to add to urls and views? All the html files including about and index are collected in the project/static folder. # This is part of the index.html, where I want to call the about.html <div class="card-footer"> <a href="#" class="btn btn-primary">Learn More</a> </div> # Here is the project/urls.py from django.contrib import admin from django.urls import path from app1 import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.index), ] urlpatterns += staticfiles_urlpatterns() -
Django caching image from external api
I want to cache images that comes to my app from google api. Settings (Note that I prefer using FileBasedCache): CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': CACHE_ROOT, 'TIMEOUT': 0, } } Here's my code that is called whenever I want to get any photo: # Shorting later syntaxes photo_ref = photo["photo_reference"] # Setting up cache key cache_key = "PHOTO_IMAGE" + photo_ref # Getting previous cache cached_data = cache.get(cache_key) # Checking if previously cached data exists if cached_data != None: # Returning cached data return cached_data else: image = "IMAGE NONE" # Getting temp image URL = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key=" + settings.KEY URL += "&photoreference=" + photo_ref result = urllib.request.urlretrieve(URL) img_temp = NamedTemporaryFile(delete = True) img_temp.write(urlopen(URL).read()) img_temp.flush() # Saving new data to cache cache.set(cache_key, File(img_temp), django_settings.CACHES["default"]["TIMEOUT"]) return img_temp But this code throws me: TypeError at /api/image_gallery/ChIJvxOujlf6PEcRIG3Mt57gV4A cannot serialize '_io.BufferedRandom' object Full traceback: Internal Server Error: /api/image_gallery/ChIJvxOujlf6PEcRIG3Mt57gV4A Traceback (most recent call last): File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dolidod/.local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/dolidod/.local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File … -
ERROR at setup of TestWebsockets.test_authorized_user_can_connect
following tutorial on testdriven.io i have created a websocket test for testing my websocket connection tests/test_websockets.py from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.test import Client from channels.db import database_sync_to_async from channels.layers import get_channel_layer from channels.testing import WebsocketCommunicator from nose.tools import assert_equal, assert_is_none, assert_is_not_none, assert_true import pytest from dc_wb.routing import application from posts.models import Trip TEST_CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } @database_sync_to_async def create_user(*,username='rider@example.com',password='pAssw0rd!',group='rider'): # Create user. user = get_user_model().objects.create_user( username=username, password=password ) # Create user group. user_group, _ = Group.objects.get_or_create(name=group) user.groups.add(user_group) user.save() return user @pytest.mark.asyncio @pytest.mark.django_db(transaction=True) class TestWebsockets: async def test_authorized_user_can_connect(self, settings): # Use in-memory channel layers for testing. settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS print(settings.CHANNEL_LAYERS) # Force authentication to get session ID. client = Client() user = await create_user() client.force_login(user=user) # Pass session ID in headers to authenticate. communicator = WebsocketCommunicator( application=application, path='/taxi/', headers=[( b'cookie', f'sessionid={client.cookies["sessionid"].value}'.encode('ascii') )] ) connected, _ = await communicator.connect() assert_true(connected) await communicator.disconnect() i have created pytest.ini [pytest] DJANGO_SETTINGS_MODULE = dc_wb.settings python_files = test_websockets.py but whenever i run pytest i just got this error ========================================================================== ERRORS =========================================================================== _____________________________________________ ERROR at setup of TestWebsockets.test_authorized_user_can_connect ______________________________________________ request = <SubRequest '_django_db_marker' for <Function test_authorized_user_can_connect>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will … -
How to set multiple rate limits , per 10sec, per 10min, per 1 day using django-ratelimit or throttling?
I want to set the rate limits for my views based on duration of 10sec, 10min and 1 day. So let say user can send 20 requests/ 10 sec, 100 requests/ 10min and 1000 request per day. I have tried throttling but couldn't find any way to set multiple requests. I have tried django-ratelimit package, but i couldn't find any such option in that too as it sets a single string for rate, such as rate = '5/10m'. Please let me know if there is any way out to solve this problem -
How to return a 404 for paths that do not exist in a Django app?
I'm noticing that I'm getting a HTTP 204 "No Content" when I hit certain urls that are invalid. For instance, if I mistakenly type myapp.com/loggin instead of myapp.com/login I would expect an HTTP 404. How can I make it such that any invalid url returns a 404 in Django? -
Why is Django sending duplicate error messages after upgrade to v2.2?
After upgrading to Django 2.2, my app began receiving duplicate error messages. Every error, no matter the type, is now sent to my ADMINS email twice. I am running my app on Heroku and tried their support, but they determined that it had something to do with my app. I have been unable to find similar issues online or on stackoverflow. MY LOGGING CONFIGURATION LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } MY VERSIONS Django==2.2.2 PyJWT==1.4.0 Pygments==2.0.2 bpython==0.13 django-braces==1.4.0 django-gulp==4.1.0 django-debug-toolbar==1.9 django-model-utils==2.0.3 django-heroku-memcacheify==1.0.0 django-pylibmc==0.6.1 django-mptt==0.9.1 django_storages==1.7.1 logutils==0.3.3 oauthlib==1.0.3 python-openid==2.2.5 social-auth-app-django==3.1.0 social-auth-core==3.2.0 google-api-python-client==1.7.4 geopy==1.17.0 requests==2.9.1 requests-oauthlib==0.6.1 six==1.10.0 sqlparse==0.3.0 django-redis==4.10.0 redis==2.10.6 kombu==4.3.0 hiredis sparkpost==1.3.6 pillow==6.0.0 python-twitter==2.2 python-wordpress-xmlrpc==2.3 python-instagram==1.3.2 celery==4.2.0 boto==2.49.0 gevent==1.4.0 waitress==1.0.2 unidecode==0.4.21 djangorestframework==3.9.4 numpy==1.15.0 pandas==0.23.4 dj-database-url==0.4.2 gunicorn==18.0 psycopg2==2.8.2 uwsgi==2.0.15 newrelic -
Django Image processing app ? where should i call the imageprocess function ? in the views or the forms?
I want to make a django app where i can process Images and show both the preprocessed and the processed,i have the function already ready and tested,how i should implement it? I already developed mini apps where it basically takes a user input without actual processing just showing it in views with some restriction and validations.I have a basic idea how i should construct the model of this app and it looks like this: class Image(models.Model): user = models.ForiegnKey(user,on_delete=models.CASCADE) preprocessed = models.ImageField(upload_to=user_path) processed = models.ImageField(upload_to=another_path) so should i call the process function in the views/forms ? I think it's in the views but how it should really looks like? should i call the form and save the input from the form if it's valid to the model ? how should i call the image preprocessed to process it and show it in a detail view ? -
view must be a callable or a list/tuple in the case of include
I am a beginner in django I'm getting this error when running : python manage.py runserver this is my app url (main.urls) from . import views from main import views as main_views from django.contrib.auth import views as auth_views from main.views import blog, about from django.conf.urls import include, url urlpatterns = [ path('about/', 'main.views.about', name='about'), path('', 'main.views.blog', name='blog'), ] this is my full project: https://github.com/ouakkaha/pr i will be so thankful if you find i solution for me:) -
Django: Set initial on a form when the form is submitted (POST)
class MyView(FormView): # get works def post(self, request, *args, **kwargs): field1 = self.kwargs.get('field1', None) if(not field1): field1 = request.POST['field1'] # field1 exists in the URL, and also as an input on the form field2 = 'Test2' field3 = 'Test3' initial={'field1': field1, 'field2': field2, 'field3': field3} # Not bound, but data does not get set input_form = MyForm() print(form.is_bound) form.initial = initial form2 = MyForm(initial, initial = initial) # Also tried # form2 = MyForm(request.POST, initial = initial, initial) with same results print(form2.is_bound) # True print(form2.has_changed()) # true print(form2.changed_data) # field2, field3 - not set return render( self.request, 'template.html', context = { 'form': form # form2 } ) Form: class MyForm(forms.ModelForm): class Meta: model = models.MyModel initial_fields = [ 'field1', 'field2', 'field3' ] fields = [ 'field1', 'field2', 'field3' ] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() return cleaned_data Template: Nothing works - ckeaned_data has only the args in the URL that was set in the get request. {{form.cleaned_data}} {{form.field2.value }} {{ form.field3 }} {% if form.field3.value %} <div class="row"> <div class="col-md-12"> <h5> Field3: </h5> {{form.field3.value}} </div> </div> {% endif %} -
The current URL, pnp4nagios/graph, didn't match any of these
We are using icinga2 o monitor our infrastructure and we are trying to install PNP plugin to have a beautiful view but we are facing the following issue: Using the URLconf defined in graphite.urls, Django tried these URL patterns, in this order: ^admin/ ^render ^composer ^metrics ^browser ^account ^dashboard ^whitelist ^version ^events ^tags ^functions ^s/(?P<path>.*) [name='shorten'] ^S/(?P<link_id>[a-zA-Z0-9]+)/?$ [name='follow'] ^$ [name='browser'] The current URL, pnp4nagios/graph, didn't match any of these. I don't have any experience with django can someone help me please!