Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass conditional attributes to template in Django ListView
I'm trying to make a list of employees that each day contains information ("today_note") if they are present at work or are sick. I had no problem to do this in Flask, I simply rendered a template as below: def employees_list(): all_employees = Employee.query.order_by(Employee.name).all() today = date.today() for employee in all_employees: today_sick = db.session.query(SickLeave).filter(SickLeave.start_date <= today).filter( SickLeave.end_date >= today).filter(SickLeave.person_id == employee.id).all() if len(today_sick) != 0: employee.today_note = "C" else: employee.today_note = "✓" return render_template("employees_list.html", all_employees=all_employees) and could access today_note for each employee in the template: {% for employee in all_employees %} {{ employee.today_note }} {% endfor %} Now I need to do the same in django. I can't figure out how to pass today_note to each instance of User model to be able to display it in the template. class AllEmployeesList(ListView): template_name = "users/all_employees.html" model = User context_object_name = 'employees' def get_context_data(self, **kwargs): context = super(AllEmployeesList, self).get_context_data(**kwargs) all_employees = User.objects.all() today = date.today() for employee in all_employees: today_sick = Sickleave.objects.filter(Q(start_date__lte=today)&Q(end_date__gte= today)&Q(employee__id=employee.id)).all() if len(today_sick) != 0: employee.today_note = "C" else: employee.today_note = "✓" return context I'm aware that here I completely miss reference to context -
Get number of objects in serializer where foreign key field is x
Suppose class ABC(models.Models): ... id = models.SlugField(...) user = models.ForeignKey(settings.AUTH_USER_MODEL) ... Now i want something like [{id: adfsdd, no_of_user_objects: 5}, {id: gdfvsdf, no_of_user_objects: 0}, {id: ergthf, no_of_user_objects: 2}] How do i achieve this? -
DJANGO: How to stop the first function when the second function is called?
I have called the first "a1" function and it's starts running in the loop and when I called the second "a2" function, the first "a1" function supposed to stop and second function has to start running, but the two functions are running parallelly. I need to stop the first function when the second function is called. Please help def a1(request): if request.method == "POST": add = request.POST['addition'] while True: add = add + 1 print(add) time.sleep(2) return render(request, blog/finished.html) def a2(request): if request.method == "POST": check = request.POST['checking'] while True: print(check) print("second function: ",check) time.sleep(2) return render(request, blog/finished.html) -
What is the difference between using django signals and calling a method?
I am trying to implement a function which sends a notification to all employee records whenever a new document record is published. In the models, I still needed to import the receiver function because my sender model lives in a different project: receiver function (lives in a different app in project): def new_document_version_published(sender, instance, **kwargs): print("New version of document published!") print(sender) print(instance) # Get all employees employees = [] # Send notifications to employees buttons = [NotificationButton(button_text="New version of document", value="Ok", style="primary")] notifyUsers("A new version of the document has been published", buttons, employees, []) sender (lives in a different app in project): from django.db.models.signals import post_save from api.views import new_document_version_published class DocumentVersion: ... def save(self, *args, **kw): if self.pk is not None: orig = DocumentVersion.objects.get(pk=self.pk) if orig.date_published != self.date_published: print('date_published changed') notify_employees() if orig.date_approved != self.date_approved: print('date_approved changed') super(DocumentVersion, self).save(*args, **kw) def notify_employees(): post_save.connect(new_document_version_published, sender=DocumentVersion) I know there is something wrong with my implementation because I don't understand what is the difference between using the signal and just importing and calling the receiver function. All help appreciated! -
Nested one-to-many relationship sqlalchemy filtering
I'm trying to filter nested one-to-many relationship in sqlalchemy, but it gives the filter only in the inner join ( second one), how Can I specify the filter in the outer join not the internal one? I have one-to-many school -->classes one-to-many class -> student I'm trying to get all the students in specific school, in specific class Models.py class School(Base): __tablename__ = 'schools' id = Column(Integer, primary_key=True) name = Column(String) # # Relationship for one-many - parent of classes classes = relationship("Class") def __repr__(self): return "<School(name='%s')>" % self.name class Class(Base): __tablename__ = 'classes' id = Column(Integer, primary_key=True) name = Column(String) # foreign Key for the parent - child of school school_id = Column(Integer, ForeignKey('schools.id')) # Relationship for one-many - parent of students students = relationship("Student") def __repr__(self): return "<Class(name='%s')>" % self.name class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) # foreign Key for the parent - child of school class_id = Column(Integer, ForeignKey('classes.id')) def __repr__(self): return "<Student(name='%s', fullname='%s', nickname='%s')>" % ( self.name, self.fullname, self.nickname) the query is info = session.query(SchoolModel). \ options(subqueryload(SchoolModel.classes).subqueryload(ClassModel.students)). \ filter(SchoolModel.id == parent_lookup_class__student). \ filter(ClassModel.id == parent_lookup_class). \ filter(StudentModel.id == pk). \ first() The output is … -
ValueError at /polls/add/ The view polls.views.addQuestion didn't return an HttpResponse object. It returned None instead
I am trying to pass data from html template to django addQuestion view in my polls app.I want to make an add quetion along their vote options template and I am using django==3.2 Here my html code <form action="{% url 'polls:add' %}" method="post"> {% csrf_token %} <label for="your_queston">Question: </label> <input id="question" type="text"> <br> <label for="choices">Choice 1</label> <input id="choice1" type="text"><br> <label for="choices">Choice 2</label> <input id="choice2" type="text"> <br> <label for="choices">Choice 3</label> <input id="choice3" type="text"> <br> <input type="submit" value="add"> </form> and here my addQuestion function in view.py def addQuestion(request): if(request.POST): try: if(request.POST['question']): qtext = request.POST.get('question') q = Question(question_text=qtext, pub_date=timezone.now()) q.save() if(request.POST['choice1']): q.choice_set.create( choice_text=request.POST.get('choice1'), votes=0) if(request.POST['choice2']): q.choice_set.create( choice_text=request.POST.get('choice2'), votes=0) if(request.POST['choice3']): q.choice_set.create( choice_text=request.POST.get('choice3'), votes=0) q.save() return HttpResponseRedirect(reverse('polls:index')) except: pass else: return render(request, 'polls/addQuestion.html') -
No able to save data in django model without any error
below mentioned are code complete details I have tried everything and also applied methods available on the internet but the problem still continues. I did not get any errors while submitting the form. Model: class Subscriber(models.Model): id = models.BigAutoField(primary_key=True) email = models.EmailField(null=False, default=1) date = models.DateTimeField(auto_now_add=True) View: from .models import Subscriber def subscriber_view(request): if request.method == 'POST': email = request.POST.get('email') subscriber = Subscriber(email=email) subscriber.save() return render(request, 'homepage') urls.py path('', views.subscriber_view, name='subscriber'), base.html {% load static %} <div class="footer-newsletter"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-6"> <h4>Join Our Newsletter</h4> <p>Tamen quem nulla quae legam multos aute sint culpa legam noster magna</p> <form method="POST" action="{% url 'subscriber' %}" id="subscriber" role="form" novalidate="novalidate" > {% csrf_token %} <input class="form-control" id="email" placeholder="Email Address" type="email" name="email"> <input type="submit" value="Subscribe"> </form> </div> </div> </div> </div> -
"Authentication credentials not provided" issue when using Nextjs server side rednering
I am using Nextjs as my frontend and Django as a backend server. I have configured django and Nextjs to run under the same domain and I was able to use django default session based authentication from my nextjs application. After logging in when I make a request from client side using Nextjs the request works perfectly since the Nextjs request is sending the sessionid cookie to the django server. The issue comes when I try to use NextJs server-side rendering. When I try to send a request from getServerSideProps in Nextjs django responds with "Authentication credentials not provided" I want to send request to my django server from getServerSideProps function for SEO What should I do to solve this issue. Thanks in advance. -
How do I preserve previous data when deleting new columns or deleting exists table in Django models?
I am developing an ERP with groups of developers and we need to preserve customers data when deleting existing columns or table for Dajngo models and DB. For Example: I added a column named columns1 and I gave the customer a release product of the System and then, but a week later I had to delete that new column but the customer have data stores in the column1 column, here how can I preserve data or solve this situation. Another Example: I have a new column name column2 with unique attr but here the customer have data, but I can not add new column with out allowed it to store the null data, but in this situation I not want to allow null data in column column2 and I can't put default attr because it has unique attr. How to solve these things in Django. -
How do I add a class to a custom widget?
I've defined the following custom widget in forms.py, which over rides the standard HTML to create a "live search" select menu (user can enter free text to search options, useful when there are many options). For this widget to work, the class="selectpicker" class must be applied. How do I apply this class at the widget level? class LiveSelectWidget(forms.widgets.Select): template_name = "widgets/live_select.html" option_template_name = 'widgets/live_select_option.html' -
How to update through model in django many to many?
class Blog(): likes = models.ManyToManyField(User, through="myapp.Like") class Like(): user = models.ForeignKey(Like) blog = models.ForeignKey(Blog) liked_at = models.DateTimeField(auto_now_add=True) some_bool_field = models.BooleanField(default=False) Now in views: def like_blog(request, id): blog = Blog.objects.get(id=id) blog.users.add(request.user) # now how can I update some_bool_field and How can I make use of this field In future I can use some query like blog.users.filter(some_bool_field=False) so for that case I want to update this field. -
Django - ServiceWorker, Uncaught (in promise) TypeError: Failed to execute 'addAll' on 'Cache': Request failed
I want to use ServiceWorker of javascript to cache an HTML file for offline view. But problem is I have a django application. and I don't know how can I specify my template files in service-worker.js. I specified a URL for service-worker.js in my urls.py like this - path('service-worker.js', (TemplateView.as_view(template_name="menu/service-worker.js", content_type='application/javascript', )), name='service-worker.js') this is my index.html template file - <script> if('serviceWorker' in navigator) { let registration; const registerServiceWorker = async () => { registration = await navigator.serviceWorker.register("{% url 'service-worker.js' %}"); }; registerServiceWorker(); } </script> everything working great so far. this is my service-worker.js const cacheName = 'my-cache'; const filesToCache = [ "/index.html", ]; self.addEventListener('activate', e => self.clients.claim()); self.addEventListener('install', e => { e.waitUntil( caches.open(cacheName) .then(cache => cache.addAll(filesToCache)) ); }); self.addEventListener('fetch', e => { e.respondWith( caches.match(e.request) .then(response => response ? response : fetch(e.request)) ) }); I'm getting this error Uncaught (in promise) TypeError: Failed to execute 'addAll' on 'Cache': Request failed and I know this is because index.html file is not found and returning 404 error. but I don't have any idea how should I specify the template file here. can anyone please help me with how should I import template files in service-worker. or I may have some totally different … -
Custom authentication middleware for specific routes in Django
I implemented a custom authentication setup for my Django project. There are some user roles for users. Now I want to ensure that some specific routs may acceptable only of specific user roles. Let's say the edit/uploaded-files can be acceptable only for the user with role = 1. So I created a middleware for that. from django.shortcuts import redirect class HRMiddleware(object): def process_request(self, request): user = request.user if not (user and user.is_authenticated() and user.email): return redirect('') if user.role_id.id != 1: raise 403 return None Now how can i apply this middleware for some specific routes only ? I found some solutions like using decorator @decorator_from_middleware(MyMiddleware) and specifying the routes in middle ware. Is there any better way to do this ? Actually I am a Laravel developer. This is my first Django project. In laravel we can specify the middlewares in the routes. Please help me -
Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance
models.py from django.contrib.auth.models import User class Profile(models.Model): name = models.OneToOneField(User,on_delete=models.CASCADE,related_name='user') bio = models.CharField(max_length=300) photo = models.ImageField(upload_to='images/profile_photos/') def __str__(self): return self.name.username class Comment(models.Model): comment_user = models.ForeignKey(Profile, on_delete=models.CASCADE) comment_text = models.TextField(blank=True) todo = models.ForeignKey(Todo, on_delete=models.CASCADE,related_name='comment') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) def __str__(self): return self.comment_text +" "+ self.comment_user.name.username serializers.py class CommentSerializer(ModelSerializer): comment_user = serializers.StringRelatedField(read_only=True) class Meta: model = Comment exclude = ('todo',) #fields = "__all__" views.py class CommentCreateApiView(generics.CreateAPIView): serializer_class = CommentSerializer #permission_classes = [TodoCreatorOrReadOnly] # def get_queryset(self): # return Comment.objects.all() def perform_create(self, serializer): id = self.kwargs['todo_id'] todo_item = Todo.objects.get(pk=id) user_comment = self.request.user print(user_comment) comment_query = Comment.objects.filter(todo=todo_item,comment_user__name__username=user_comment).exists() if comment_query: raise ValidationError('User Comment is already exist..!') else: serializer.save(todo=todo_item,comment_user=user_comment) errors File "D:\python_projects\todo_project\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__ raise ValueError( ValueError: Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance. I have tried several times to comment on a specific todo item. A single authenticated user can write one comment on a single todo item. When I have been sending a post request the response shows Cannot assign "<User: shakil>": "Comment.comment_user" must be a "Profile" instance. I guess the problem occurs inside below the line: serializer.save(todo=todo_item,comment_user=user_comment) -
Show not already selected values of many to many field in django admin
I am trying to show values from a many to many field which are not already selected. It is working fine on add. But on change form, not able to see the selected values. forms.py class TagGroupAdminForm(forms.ModelForm): selected_tags= Taggroup.objects.all().values('tags') all_tags= Tags.objects.filter(tagtype=2) filtered_tags=all_tags.exclude(id__in=selected_tags) tags=forms.ModelMultipleChoiceField(queryset=filtered_tags, widget=FilteredSelectMultiple( verbose_name='Tags', is_stacked=False )) class Meta: model= Taggroup fields='__all__' def __init__(self, *args,**kwargs): super(TagGroupAdminForm,self).__init__(*args,**kwargs) -
How to filter through date in django-views?(Doesn't show the expired one)
models.py class Dibbs_Fields(models.Model): hash = models.CharField(max_length=16) nsn = models.CharField(max_length=32) nomenclature = models.TextField() technical_documents = models.TextField() return_by = models.DateField() How to filter this class in django views according to the date return_by ? I don't want to show the data that is expired i.e. if the return_by date is earlier than today's date, then it should not show. -
Why does React Native receive models.TextChoices from Django as a tuple converted to a string?
I have this text choices model class PostType(models.TextChoices): DECLARE = 'DECLARE' UPDATE = 'UPDATE' SUCCESS = 'SUCCESS' for some reason on the mobile front-end it's returning as LOG ('UPDATE', 'Update') LOG string This tells me that Django is sending it as a tuple of ('<type all caps>', '<type camel case>') and then React Native is converting it to a string and printing is as such. Why is this happening? What can I do on Django to ensure just 'Declare', 'UPDATE' or 'SUCCESS' is returned to the react native? -
django.db.utils.OperationalError: no such table: auth_group
https://github.com/monobot/simpletickets i am trying to add this application into my project. Now i am stuck in this error after adding "on_delete=models.CASCADE" into FK fields in the Ticket table in models and after that i changed that import in views.py "from django.core.urlresolvers import reverse" into this "from django.urls import reverse" after all of that when i run this statement "python manage.py migrate" i got that new error "django.db.utils.OperationalError: no such table: auth_group" and i dont get any positive result to resolve this error...error -
Foreign key in Django Models does not seem to auto generate
models.py class Job(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField(default = True) freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(default=timezone.now) date_modified=models.DateTimeField(null = True) version=models.IntegerField(default = 1) class Job_detail(models.Model): job_type=models.IntegerField() json = models.CharField(max_length = 1000) jobid = models.ForeignKey(Job, on_delete=models.CASCADE) class Job_track(models.Model): status = models.IntegerField(default = 3) output = models.CharField(max_length=500, blank = True) location = models.CharField(max_length = 500, blank = True) jobid = models.ForeignKey(Job, on_delete=models.CASCADE) jobdetailid = models.ForeignKey(Job_detail, on_delete=models.CASCADE) forms.py class JobForm(ModelForm): class Meta: model = Job fields = [] class JobDetailForm(ModelForm): class Meta: model = Job_detail fields = [] exclude = ['jobid'] class JobTrackForm(ModelForm): class Meta: model= Job_track fields = [] exclude = ['jobid', 'jobdetailid'] Within the function of my views: def device_port_selected(request, pk): devices = Device.objects.get(pk=pk) if request.method == "POST": job = JobForm(request.POST) jobdetail = JobDetailForm(request.POST) jobtrack = JobTrackForm(request.POST) if job.is_valid() and jobdetail.is_valid() and jobtrack.is_valid(): #For Job j = job.save(commit=False) hostname = devices.id print(type(hostname)) ipaddr = devices.ipaddr print(type(ipaddr)) name = str(hostname) + ',' + ipaddr j.jobname=name current_user = request.user j.owner = current_user.username j.enabled = "True" j.freq_type = 1 j.freq_interval = 0 j.freq_recurrence = 0 … -
Will increasing memory in AWS solve the sigkill issue in celery
I have a django application running that uses celery to run tasks. The tasks take between 8 and 10 hours to complete. In my local system, the application was running fine. I have a mid 2015 Macbook pro with an i7 processor and 16 gigs of RAM. I recently deployed the application into a 2core 4GB server in AWS. Now the tasks are being killed. This is the exact error I get Task handler raised error: WorkerLostError('Worker exited prematurely: signal 9 (SIGKILL) Job: 0.') When I read on this, I came to know that this happens due to memory leakage or memory swap issues. My question is, will increasing the memory in AWS solve the issue? -
How we can deploy django app on cpanel with uvicorn server?
I wanna deploy django app on cloud server using cpanel. But I cannot found any article which describe me deploying django app with uvicorn on cpanel. -
ImproperlyConfigured: SQLite 3.9.0 or later Error When Using Django
I'm receiving the below error message when running this command in my django project "python manage.py migrate" How do you upgrade to a later version of SQLite on CentOS 7 x64bit? Error: SQLite 3.9.0 or later is required (found %s).' % Database.sqlite_version django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.1 7). # python -V Python 3.6.8 # sqlite3 --version 3.7.17 2013-05-20 00:56:22 118a3b35693b134d56ebd780123b7fd6f1497668 # uname -a 3.10.0-1160.25.1.el7.x86_64 #1 SMP Wed Apr 28 21:49:45 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux # python3 -c "import django; print(django.get_version())" 3.2.9 # cat /etc/centos-release CentOS Linux release 7.9.2009 (Core) -
Django static files - Failed to load resource network connection was lost
I am working on a Django website development where I am trying to serve the static files by putting all the static files in the STATICFILES_DIRS directory. The static directory structure is follows: static/css: bootstrap-theme.min.css bootstrap.min.css daterangepicker.css font-awesome.min.css jquery.dataTables.min.css static/images: sort_asc.png sort_asc_disabled.png sort_both.png sort_desc.png sort_desc_disabled.png static/js: Chart.min.js daterangepicker.min.js jquery.min.js moment.min.js bootstrap.min.js jquery.dataTables.min.js jsapi popper.min.js static/webfonts: fa-brands-400.eot fa-brands-400.ttf fa-brands-400.woff2 fa-regular-400.svg fa-regular-400.woff fa-solid-900.eot fa-solid-900.ttf fa-solid-900.woff2 fa-brands-400.svg fa-brands-400.woff fa-regular-400.eot fa-regular-400.ttf fa-regular-400.woff2 fa-solid-900.svg fa-solid-900.woff settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), ] urls.py urlpatterns += staticfiles_urlpatterns() Including static files as below: {% load static %} <script src="{% static 'js/jsapi' %}"></script> <script src="{% static 'js/jquery.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/moment.min.js' %}"></script> <script src="{% static 'js/daterangepicker.min.js' %}"></script> <script src="{% static 'js/Chart.min.js' %}"></script> <script src="{% static 'js/jquery.dataTables.min.js' %}"></script> <script src="{% static 'application1/jquery.cookie.js' %}"></script> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" /> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' %}" /> <link rel="stylesheet" href="{% static 'css/daterangepicker.css' %}" /> <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}" /> <link rel="stylesheet" href="{% static 'css/jquery.dataTables.min.css' %}" /> <link rel="stylesheet" href="{% static 'application1/style.css' %}"/> Getting errors: The above errors are directly leading to: [Warning] jQuery.Deferred exception: $('#table').DataTable is not a function. (In '$('#table').DataTable({"paging": true})', '$('#table').DataTable' … -
How to generate a random number in django?
I want to generate a random number to be added to a counter. But I am receiving an error and cant figure out why. Appreciate your help. from django.shortcuts import render, redirect, HttpResponse from random import random, randint # Create your views here. def index(request): if 'counter' not in request.session: request.session['counter'] = 0 return render(request, 'index.html') def process_money(request): print(request.POST['custId']) if request.method == 'POST': if request.session['custId'] == '1': request.session['counter'] += random.random() # Add a random number to the counter if request.session['custId'] == '2': request.session['counter'] += 10 request.session['custId'] = request.POST['custId'] return render(request, 'index.html') This is the error I get in the console: AttributeError: 'builtin_function_or_method' object has no attribute 'random' -
The view account.views.updatedata didn't return an HttpResponse object. It returned None instead
I have an issue with my update button and it show this error to me when I click the update button, it is suppose to redirect me to the next page where the staff can update the details, how do I fix that error, so that it can redirect me to the next page where it will show the forms for the staff to update the details The error I had is shown below here (Traceback error): Environment: Request Method: POST Request URL: http://127.0.0.1:8000/updatedata/17/ Django Version: 3.1.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms', 'channels'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 307, in check_response raise ValueError( Exception Type: ValueError at /updatedata/17/ Exception Value: The view account.views.updatedata didn't return an HttpResponse object. It returned None instead. views.py @login_required() def updatedata(request, id): photo = get_object_or_404(Photo, id=id) if request.method == 'POST': # check for the post request body form = UpdateForm(request.POST) if form.is_valid(): form.save() return redirect('/logdata') else: msg = 'form is not valid' # Show an error message …