Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my submit button relocated outside Django form when the form is reloaded from invalid post?
I have a template which includes a ModelForm, a ModelFormSet, and a submit button which is supposed to submit all form data from both the Form and FormSet. The problem is, when I submit the data, if the data is invalid, sometimes the template will reload with the submit button relocated outside the form container - how does that even happen? - and though the user can edit the data in the forms to be valid, they are no longer able to submit the form(s). Also, the submit button is not floated. Template: <form method="post" class="form-horizontal"> {% crispy incident_form %} <input type="button" id="delete_field_data" class="btn btn-outline-danger" value="Delete Field Incident Data"> <div id="form_set_class"> {{ incident_formset.management_form }} {% for form in incident_formset %} {{form.non_field_errors}} {{form.errors}} {% crispy form %} {% endfor %} </div> <div id="add_field_data_div"> <p>If the incident occurred in the field, add field incident data.</p> <input type="button" id="add_field_data" class="btn btn-outline-warning" value="Add Field Incident Data"> </div> <p>Add a part deficiency report for each component which needs repair or replacement</p> <input type="button" id="add_def_report" class="btn btn-outline-dark" value="Add Part Deficiency Report"> <div id="empty_form" style="display:none"> <div id="incident___prefix__"> <fieldset> <legend>Part Deficiency Report</legend> {{incident_formset.empty_form}} <br> <input type="button" id='delete_incident___prefix__' class="btn btn-outline-danger" value="Delete Part Deficiency Report" onclick="delete_def_report()"> </fieldset> </div> </div> <input … -
How to pass a variable from Django to TypScript?
In Django I have a template file that looks somewhat like this: my_template.html: <script> let config = '{{ my_config_variable }}'; </script> <script src="{% static 'script.js' %}"></script> script.ts: // do something with the config variable: console.log(config); This would work in JavaScript, because JavaScript doesn't care. But if I try to compile this in TypeScript, I, of course, get error. So, what the right way to pass some variables from Django to TypeScript (and maintain some type safety if possible)? -
How can I combine these two model fields into one?
Let's say I have this model: class ParticipationCount(models.Model): female = models.PositiveIntegerField() male = models.PositiveIntegerField() I would like to combine them permanently into: people = models.PositiveIntegerField() I would like for all the existing male and female ones to both be combined into "people." As we already use this model and have data. Here is the admin: class ParticipationCountAdmin(admin.ModelAdmin): list_display = ("shift_datetime", "shift", "location", "female", "male") search_fields = ["location", "female", "male"] form = ParticipationCountForm So, in summary: How do I combine the "male" and "female" into one field, and continue using this field from here on out, because we don't refer to genders anymore. -
PUT multipart-formdata containing PNG with XMLHttpRequest in vanilla javascript
I'm trying to PUT svg, a string and a png together to a Django REST api from a pure javascript client. I'm currently stuck with error 400 "Upload a valid image. The file you uploaded was either not an image or a corrupted image." response from the backend. The png comes from Pablo's "toImage"-function, which converts the svg to png. The file itself doesn't appear to be corrupt, it opens with python pillow (Which is also used by Django). var formData = new FormData(); var file = new Blob([svgData], { type: 'text/xml'}); var img = Pablo(document.getElementById('stage')).toImage('png', appendImgToFormAndSend); var xhr = new XMLHttpRequest(); xhr.open("PUT", "http://myapi.local/upload_all_the_data"); function appendImgToFormAndSend() { var picture = new Blob([img[0].src], { type: 'image/png'}); formData.append('picture', picture, 'picture1.png') formData.append('rawdata', file, 'rawdata'); formData.append('url', location.href); xhr.send(formData) }; xhr.onload = function() { console.log("ANSWER"); console.log(this.responseText); var data = JSON.parse(this.responseText); console.log(data) } Have I got a conceptual misunderstanding here? -
object has no attribute 'POST'
I am just trying to capture values from a HTML form to MySQL DB using Django framework in Python. Here is the problem I am facing I am getting this error, Error Log, Request Method: POST Request URL: http://127.0.0.1:8000/pages/submitUser Django Version: 2.1.4 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'POST' Exception Location: D:\\...\DjangoApps\commondata\views.py in create_user, line 25 Python Executable: C:\\...\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.7 'User' object has no attribute 'POST' This is what I have in my models.py file, from django.db import models class User(models.Model): user_name = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) user_id = models.CharField(primary_key=True, max_length=255) user_department = models.CharField(max_length=100) email = models.CharField(max_length=70) digital_signature = models.FileField(upload_to='uploads/') In urls.py, path('pages/createUser', commons_views.display_user_form, name='create_user'), path('pages/submitUser', commons_views.create_user, name='submit_user'), In views.py, def display_user_form(request): return render(request, "pages/user_registration.html") def create_user(request): // from the error log line 25 => userdata = User(user_name=request.POST['user_name'], password=request.POST['password'], user_id=request.POST['user_id'], user_department=request.POST['user_department'], email=request.POST['email']) return render(request, "pages/thankyou.html") I refereed stackoverflow and found 2 similar answers but still I am facing the error, 'WSGIRequest' object has no attribute 'Post' Django 'WSGIRequest' object has no attribute 'Post' All of my POST are in capital letters Django Error in Post Request: 'module' object has no attribute 'POST' I have request in create_user function. What would be the problem … -
Trying to update the post in database.But getting Page not found (404)?And want to know how to update the data in database?
I'm trying to create a blog app with django.When clicked on a post it displays that post in separate page.In that i created edit and delete option.When i click on edit it returns edit option.But when i change some content and click on update it returns page not found error. #urls.py from django.urls import path,include from . import views urlpatterns=[ path('',views.homepage), path('register',views.register,name='register'), path('login',views.login,name='login'), path('logout',views.logout,name='logout'), path('newpost',views.newpost,name="newpost"), path('<int:pk>', views.post_detail, name='post_detail'), path('<int:pk>/edit', views.edit, name='edit'), path('update', views.update, name='update'), ] <!---update.html page---> {% extends 'layout.html' %} {% block content %} <div class="box"> <form action="updated" method="POST"> {% csrf_token %} <h3>Title of Post</h3> <input type="text" maxlength="100" name="title" class="inputvalues" value={{post.title}}> <h3>Description</h3> <textarea name="desc" style="width: 500px;margin: 0 auto;padding: 5px;height:40%" >{{post.desc}}</textarea> <a href="update"></a> <button type="submit" id="lg" >Update</button> </a> </form> </div> {% endblock %} #views.py def edit(request,pk): post=Post.objects.get(pk=pk) return render(request,'update.html',{'post': post}) def update(request): post=Post.objects.get(pk=pk) title=request.POST['title'] desc=request.POST['desc'] update = Post(title=title,desc=desc,author_id=request.user.username) update.title= title update.desc= desc update.save(); return redirect('indpost.html') the url for displaying individual post is http://127.0.0.1:8000/48 where 48 is pk_id the url when i click on edit is http://127.0.0.1:8000/48/edit the url when i click on update is http://127.0.0.1:8000/48/updated -
How do i run two command lines in AWS simultaneously?
I have a Django app that I am trying to deploy to AWS. I need two command lines to run the app. One command line will be used to runserver and another one to run a background task. That is how the app runs in my localserver. How do I start two command lines in AWS? Thanks -
Django render() - Reverse for '' not found. '' is not a valid view function or pattern name
This is yet another question involving paths in Django. I have not been able to find my answer anywhere and have done lots of searching on this. The return() function in my view is throwing the error django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name.. Here is my code. When I hit enter on the search bar it will route to the proper view function and do all the necessary computations, but it fails on the render() function. The url I have in my browser is: http://localhost:8000/siren-search/search/?query=jobsite9. Here is a link to my traceback: http://dpaste.com/2KFAW9M# -
Django Admin includes folder templates not customizable
I have a custom model admin template in: ./templates/admin/myapp/mymodel/change_form.html I also want a custom version of ./templates/admin/includes/fieldset.html which, according to the path logic, should be put in: ./templates/admin/myapp/mymodel/includes/fieldset.html My app now loads the specific change_form.html for myapp/mymodel but not the custom fieldset.html. What is the correct path? Ref: https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/includes/fieldset.html https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ -
How to set certain permissions to different "Groups" in Django REST framework
I am trying to let only users in say group 1 to be able to read the api, and then users in group 2 to read or write. I was able to do a very basic version with using permission_classes = (permissions.IsAuthenticatedOrReadOnly,) I'd like to make that functionality more specified to groups instead of just users that login. -
Issue is probably caused by a circular import showing after running django server
i'm trying to runserver for a django project and it shows me this error : django.core.exceptions.ImproperlyConfigured: The included URLconf 'hello.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.` path('articles/', include('articles.url')) --> This line causes the problem, whenever i comment this line django server run appropriately. my urls file of the project : hello.urls from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('about/',views.about), path('',views.homePage), path('articles/', include('articles.url')), ] my urls for my apps : articles.urls from django.urls import path from . import views urlpatterns = [ path('',views.articleList), ] -
How do I add a custom header to the swagger UI when using drf-yasg?
When doing API documentation there is an API which reads a token from the headers. It should not be a part of the authentication as the authentication system is not yet built. There is only one API which has to read this particular header. Is there anything that I can do with the annotation @swagger_auto_schema? -
Django email not sending mail
I created a view for email that worked for sometime but recently stopped sending mails. However I can see the mail in the console. I don't know what is wrong. I have used both send_email and Emailmessage but none of them work. views.py def mail(request): msg = EmailMessage('Request Callback', 'Here is the message.', to=['****@gmail.com']) msg.send() return HttpResponseRedirect('/') settings.py DEFAULT_FROM_EMAIL = '****@gmail.com' SERVER_EMAIL = '****@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = '****@gmail.com' EMAIL_HOST_PASSWORD = '***********' -
Can´t import an existing chatbot into Django Framework
I´ve already programmed a simple chatbot some time ago. Now I want to implement it into my Django project. I tried: from .bsbot import model bsbot.model.response() bsbot is the name of my folder in wich I programmed the bot. In this folder there is an training_data file wich was created when I run train.py. If I try to run my Django server the Errormsg says: File"bsbot/model.py", line 16, in <module> data = pickle.load(open("training_data", "rb")) FileNotFoundError: [Errno 2] No such file or directory:'training_data' If already tried some different kinds of importing like: import bsbot.model.response or from .bsbot import * or from smarthome.web.bsbot import model I´ve also put an init.py into my folder so that python knows it´s a package. But it´s empty. Should there be any code in it? I think the problem is that can´t find the training_data file. If I run just the bot everything works fine. -
How to remove Ck editor tag in django rest framework
I am using Django rest framework. The CkEditor tags I've used for the web appear in the API part. How do I remove these tags from the API I had not used Ckeditor before, I was using the Django TextField field models.py class Lesson(models.Model): ... lesson_content = RichTextField( verbose_name=_('Ders İçeriği'), blank=True ) ... seriaizer.py class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = (...,'lesson_content',...) output(Json Data) "id":1, "user":2, "lesson_name":"Microprocessors","lesson_content":"/<p>Merkezi .</p>", "lesson_notes":"<p>&nbsp;</p>\r\n\r\n<p>Yazıcı, R., 1998, Mikrobilgisayar Donanım ve Yazılımı, KT&Uuml; Yayınları, Trabzon, 345 s.</p>\r\n\r\n<p>Brey, B., B., 1984, Microprocessor/Hardware Interfacing and Applications, Merrill, 414 p.</p>\r\n\r\n<p>Leventhal, L., A., 1979, Z80 Assebly Language Programming, Osborne/McGraw-Hill, 612 p.</p>\r\n\r\n<p>Uffenbeck, J., 1985, Microcomputers and Microprocessors: The 8080, 8085, and Z80 Programming, Interfacing, and Troubleshooting, Prentice-Hall, 670 p.</p>\r\n\r\n<p>&nbsp;</p>" <p> & nbsp; </p> \ r \ n \ r \ n <p> I don't want the tags to appear -
Filter data on django admin console with URL
Is there any way to filter modal data on Django admin console with URL and POST request? I have a dynamic URL which I am creating on the basis of filters on template. As this is a GET request and length of URL depends on the results filtered. HTTP URL has length restriction. For smaller number of results it is working fine but problem with very long number of results. Is there any other way to filter data on admin console or is there any way to filter results rendered with POST request? Otherwise there is overhead to create custom template which may lead to performance and other issues for large numbers of records (>4K). url = self.reverse("admin:appName_modalName") + "?id__in=" + ",".join( [str(x) for x in records.values_list("id", flat=True)]) -
How to get uwsgi init status?
I use uwsgi to start my Django application by executing command uwsgi --init uwsgi.ini, uwsgi.ini is the uwsgi's config file. I use echo $? to check out the uwsgi init status, But I found out whether my Django application starting success or not, echo $? always return 0, the question is how can I get uwsgi starting status correctly? -
Putting methods in a class in views.py
I am creating a simple todo app just to learn Python & Django. My current code: def create_task(request): # code for creating a task def delete_task(request, task_id): # code for deleting task def show(request, task_id): # show a task def list(request): # show list of tasks def create_sub_task(request): # code for creating a sub_task def delete_sub_task(request, sub_task_id): # code for deleting sub_task def flip_sub_task_completed(request, sub_task_id) # make a sub_task completed/uncompleted As you can see, a task has subtasks. This is working fine. But I think it would be better to separate Tasks and SubTasks, and create 2 classes for them. Would it be better? And how would I go on achieving that? How would I need to change my urlpatterns = [ to make it work? Thanks a lot! -
attempt to write a readonly database SQLite, Django
I have implemented my simple Django applications on server, but my forms for users can not save anything. My database settings looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } My error which template receives looks like this: nvironment: Request Method: POST Request URL: http://68.183.76.239/wyniki-wyszukiwania/konta-bankowe/ Django Version: 2.2.2 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'django_filters', 'crispy_forms', 'django_select2'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/app/lib/python3.5/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) File "/home/app/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (attempt to write a readonly database) was the direct cause of the following exception: File "/home/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/app/app/app/views.py" in search_results_account 149. product_broken_form.save() File "/home/app/lib/python3.5/site-packages/django/forms/models.py" in save 458. self.instance.save() File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in save 741. force_update=force_update, update_fields=update_fields) File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in save_base 779. force_update, using, update_fields, File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in _save_table 870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/app/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert 908. using=using, raw=raw) File "/home/app/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/app/lib/python3.5/site-packages/django/db/models/query.py" in _insert 1186. … -
Not able to Migrate DB, using python manage.py makemigrations
I want to migrate model in DB, so I am using this command in my active environment python manage.py makemigrations But it gives me this error File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax Can you please provide me solution for it? -
Django Custom Multi User Model Data filling
I wanted to make an app which hold information about different types of account. Problem I can fill the form but its not taking the input and storing it in the model i want to store it into. Models.py from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) username_regex = '^[a-zA-Z0-9+-]*$' # Create your models here. class AccountManager(BaseUserManager): def create_account(self, username, email, password=None): if not email: raise ValueError('Users must have a email id') account = self.model( username = username, email=self.normalize_email(email), ) account.set_password(password) account.save(using=self._db) return account def create_student(self,username, email, password=None): account = self.create_account( username = username, email=email, password=password,) account.is_student = True account.save(using=self._db) return account def create_teacher(self, username, email, password=None): account = self.create_account( username = username, email=email, password=password,) account.is_teacher = True account.save(using=self._db) return account def create_superuser(self, username, email, password=None): account = self.create_student( username = username, email=email, password=password,) account.is_student = True account.is_teacher = True account.is_admin = True account.is_staff = True account.save(using=self._db) return account class Account(AbstractBaseUser): username = models.CharField(max_length=60, validators =[RegexValidator(regex = username_regex, message = 'Username must be alphanumeric', code = 'Invalid_username')], unique=True) email = models.EmailField(verbose_name='Email Address', max_length=255, unique=True, ) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default = False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = … -
Django models attributes - can't resolve attribute reference
I tried to resize profile photo, but it sends no errors, and it does nothing. Only thing that my pycharm says is this 'unresolved attribute reference path for class ImageField'. Any idea what should I do? I tried with .path and .url, neither work. But in django documentation for FieldFile, both attributes seem to exist. def save(self, *args, **kwargs): if not self.id and not self.image: return super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) -
how to pass the dictionary to django template using javascript
I am trying to pass the dictionary values to django template through JavaScript Views.py population_count = ( {'name': 'Year 1800', 'data': '[107, 31, 635, 203, 2]'}, {'name': 'Year 1900', 'data': '[133, 156, 947, 408, 6]'}, {'name': 'Year 2012', 'data': '[1052, 954, 4250, 740, 38]'}, ) population_count_js = json.dumps(population_count) jsonstring return render(request, 'index.html', {'data': population_country_js},{'count': population_count_js}) But I am getting the error like " Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at (index):17" var b = '{{count|safe}}'; console.log(JSON.parse(b)) index.html var a = '{{data|safe }}'; console.log(JSON.parse(a)) var b = '{{count|safe}}'; console.log(JSON.parse(b)) Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Historic World Population by Region' }, xAxis: { categories: JSON.parse(a) }, series: JSON.parse(b) }); I except the output in the chart Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at (index):17 -
How to change a OneToOneField into ForeignKey in django model with data in both table?
I am having a model Employee with a OneToOneField relationship with Django USER model. Now for some reason, I want to change it to the ManyToOne(ForeignKey) relationship with the User model. Both these tables have data filled. Without losing the data how can I change it? Can I simply change the relationship and migrate? -
After first query in the database, I want to Make a boolean field false
I'm trying to implement a mechanism were by only 1 one query will be made in the database after the query, a boolean field in the database will change its status from true to false. I don't know how to accomplish this. The Model class Code(models.Model): best_before = models.DateTimeField(auto_now=True) expiry_date = models.DateTimeField(auto_now=True) code = models.CharField(max_length=8, blank=True, unique=True) status = models.BooleanField(blank=True) And I'm using a get request to query code field in the database. View def index(request): info = Code.objects.all() query = request.GET.get('q') print(query) if query: info = info.filter(code__exact=query) context = { 'info':info, 'query':query } return render(request, 'drugs/index.html', context)