Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to allow an empty foreign key in Django?
I'm very new to Django so this may be the dumbest question ever. I have 2 models set up in django; 'Class' and 'Profile'. The 'Profile' class has a foreign key that references 'Class'. When creating a profile on the front end I am unable to leave the form blank as ("Profile.group" must be a "Class" instance.). I want to be able to create a profile that doesn't have to belong to a class. class Class(models.Model): class_name = models.CharField(max_length=5) # a few other things that don't matter def __str__(self): return self.class_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # a few other things that don't matter group = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True) and in form.py class ProfileRegisterForm(forms.ModelForm): # a few other things group = forms.CharField(max_length=5, required=False) If there is anything important that I've missed out please let me know, it's my first time posting here so I don't know what the standard is. -
Reverse for '' not found '' is not a valid view function or pattern name
I'm getting the above message when trying to view the cart page in my Ecommerce site. I can see that this is a fairly common question but after trawling through multiple other threads here, none of the solutions are working. In the current iteration of my code I have added an app_name to the cart app and then referenced this in my html, but no joy. Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 2.2.5 Python Version: 3.8.1 Installed Applications: ['pages.apps.PagesConfig', 'accounts.apps.AccountsConfig', 'products.apps.ProductsConfig', 'cart.apps.CartConfig', 'search.apps.SearchConfig', 'crispy_forms', 'storages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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') Template error: In template C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\pages\templates\base.html, error at line 0 Reverse for '' not found. '' is not a valid view function or pattern name. 1 : {% load static %} 2 : 3 : <!DOCTYPE html> 4 : <html lang="en"> 5 : 6 : <head> 7 : <meta charset="utf-8" /> 8 : <!-- Set the viewport to allow responsiveness --> 9 : <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> 10 : <!-- Bootstrap CSS --> Traceback: File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Vegeta\OneDrive\Visual Studio Code\milestone-project-four\env\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response … -
Django Form Wizard - Using an image formset for a related post model
So I'm using the Django Form Wizard to split a simplified PostForm. In one of the steps, visitors can upload different images related to the Post. Within the done method for the SessionWizardView, I'm saving the instance first and then check for the images within the formset. However I get the following error message; save() prohibited to prevent data loss due to unsaved related object I tried setting the related Post id for the formset but I'm missing something here, formsets are still something I can't really follow.. Any help is appreciated! models.py class Post(models.Model) title = models.CharField(max_length=200) description = models.TextField(max_length=1000) def __str__(self): return self.title class Image(models.Model): post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True) file = models.ImageField(upload_to='images/', null=True, blank=True) alt = models.CharField(max_length=200, blank=True) views.py FORMS = [ ('title', PostCreateForm), ('image', ImageFormset) ] TEMPLATES = { 'title': 'post_form_title.html', 'image': 'post_form_image.html' } class PostWizardView(SessionWizardView): form_list = FORMS file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp/')) def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, form_dict, **kwargs): instance = Post() for form in form_list: instance = construct_instance(form, instance) instance.save() post_id = instance.pk if 'image' in form_dict: formset = form_dict['image'] if formset.is_valid(): formset.save(commit=False) for form in formset: form.post = post_id formset.save() forms.py class PostCreateForm(forms.ModelForm): class Meta: model = Image fields = '__all__' … -
Unable to implement a floating button in Django template
I am trying to create a floating button as shown in this video. However I am unable to implement the same. I am basically tying to add this to one my django templates. Here is the code of the HTML: {% extends "base.html" %} {% load bootstrap4 %} {% block content %} <button class="material-icons floating-btnz">Add</button> Some more code here {% endblock %} <style> .floating-btnz{ width: 80px; height: 80px; background: #009879; display: flex; border-radius: 50%; color: #ffffff; font-size: 40px; align-items: center; justify-content: center; text-decoration: none; box-shadow: 2px 2px 5px rgba(0,0,0, 0.25); outline: blue; border: none; cursor: pointer; } </style> I have included the material icon cdn in my base.html. It seems to me that the cdn is not working. Upon checking in the web console, the css is loading but not showing up on the button. Where am I going wrong? Any help is appreciated. -
How to logging information about 404 error while Debug = False
I have a django project on production. In my settings.py file Debug=False to avoid security risks which arrises when Debug=True I heard about python logging module which I am trying to set up. But after reading documentation like I understand I should put logging instances in each piece of code where error can be arrised, but what if I need to handle 404 errors? How I can handle them? Please anyone guide me -
How do I add TypeScript files in a Django project made with Visual Studio 2019
Is it possible to use TypeScript instead of JavaScript in a Django project developed using Visual Studio? At the moment I just tried to add a .ts file and import it to a HTML file. It fails when finding non-Javascript syntax though. I was wondering what I was missing. Do I have to configuration Visual Studio for it? (TypeScript sdk is already installed). Is it going to compile the .ts files into JavaScript by itself or do I have to go through extra steps? -
Inherit and rename the table from default setting
I would like to rename the default table comes from Django. Meta does copy the table but the columns are totally difference How can i over come with it? -
how to see if a value is present in a list in django template. tried using IN operator but does'nt work
I'm trying to enable a button dynamically but the IN operator on my html does not work. I tried converting everything to string as well but it still did not work. Models.py class Product(models.Model): name=models.CharField(max_length=100) image=models.ImageField(default='default.jpg',upload_to='productimages') description=models.TextField() category=models.CharField(max_length=100) price=models.FloatField() def __str__(self): return f'{self.name}' class Cart(models.Model): cart2user= models.ForeignKey(User, on_delete=models.CASCADE) cart2product=models.ForeignKey(Product, on_delete=models.CASCADE) quantity=models.IntegerField(default=1) views.py def home(request): productobj=Product.objects.all() cartobj=Cart.objects.filter(cart2user=request.user) cartobjlist=[x.cart2product for x in cartobj] print(cartobjlist) return render(request,'home.html',{'productobj':productobj,'cartobjlist':'cartobjlist'}) home.html {% for pobj in productobj%} <div class="col-xl-3 eachproduct"> <form action="{%url 'home'%}" method="GET"> {% csrf_token%} <img src="{{pobj.image.url}}" height="300px" width="100%"> <h3 class="name" name="{{pobj}}" value={{pobj}}>{{pobj.id}}</h3> <h3 class="price" name="price" value={{pobj.price}}>${{pobj.price}}</h3> {% if pobj in cartobjlist %} <a href="{% url 'cart'%}" class="btn buttoncart">Go to cart</a> {% else %} <a href="addtocart/{{pobj.id}}" class="btn buttoncart">Add to cart</a> {%endif%} </form> </div> {%endfor%} -
Error while migrating the django application
My database code: I think there is a problem in the database. This is working quite well in the localhost. while coming to deploying it shows the following error. Please help me out*** strong text ---------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'telusko', 'USER' : 'postgres', 'PASSWORD': 'XXXXXXX', 'HOST' : 'localhost', 'PORT' : '', } } --------------------------------------- ERROR ---------------------------------------- Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect … -
Need Help Setting Up A Comment Section For A Django Blog
I just started learning django and i am stuck on creating a comment section for logged in users on a blog, and the ability for users to reply to that comment. I am using class based views and i will like to add the comment to the DetailView (in my case PostDetailView). models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post (models.Model): title = models.CharField (max_length=100) content = models.TextField () date_posted = models.DateTimeField (default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='blog_images', blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.content def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Comment from .forms import CommentForm #from django.http import HttpResponse def home(request): context = { 'posts': Post.objects.all() } return render (request, 'blog/home.html', context) class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<mode>_<view_type>.html context_object_name … -
Tell me how to release password change for Django users?
Tell me how to create the ability to change the password using my html form? I do not want to use annual ChangePasswordForm. I’ve been suffering for 1 hour and can’t find a solution. -
facing TemplateDoesNotExist error. django version - 3.7.4
Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.2 Exception Type: TemplateDoesNotExist Exception Value: home.html Exception Location: C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\hp\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\hp\Desktop\mmpos\Django_project', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32\lib', 'C:\Users\hp\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Pythonwin'] Server time: Sun, 16 Feb 2020 10:36:49 +0000 -
How do I change my django generated form's width?
how are you? I have django forms generated using forms.py using jinja i can implement them in html yes and I have applied crispy forms api to add bootstrap but I cannot change the width using css! i can edit margin and etc. but not width. I would appreciate some help on how I can change width of my small form. thanks! -
How to nest abstract relationship in Django rest framework?
I have a model called Layer that has a one-to-one relationship with Geometry, and Geometry have the following design: class Geometry(models.Model): pass class Circle(Geometry): radius = models.CharField(max_length=255) class Rectangle(Geometry): height = models.CharField(max_length=255) width = models.CharField(max_length=255) How should I define the Layer serializer to make the layer json contain a property called "geometry" regardless of which child model it has a relationship with? I don't want the property to be called neither circle nor rectangle. Thanks in advance! -
django admin.autodiscover() import order on urls file
I cloned a sample app for django and run code inspection and found that admin.autodiscover is called before importing the views file, that's used for the patterns later: from django.contrib import admin from django.urls import path admin.autodiscover() import hello.views urlpatterns = [ path("", hello.views.index, name="index"), ... ] This triggers a PEP8 code style warning as the imports are not all on the top of the file. I'm afraid that moving it may have unintended side effects. Is that the case? -
Adding whitenoise to django gives an "ImproperlyConfigured: WSGI application" error
My application works if I were not to add "whitenoise.middleware.WhiteNoiseMiddleware" into the MIDDLEWARE in settings.py but if I were to add it back, then it would not work and would give this error django.core.exceptions.ImproperlyConfigured: WSGI application 'story_4.wsgi.application' could not be loaded; Error importing module. This is what is inside my wsgi.py file #wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'story_4.settings') application = get_wsgi_application() Any answer is appreciated. -
psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known
docker-compose run web python3 manage.py migrate WARNING: Found orphan containers (books_webapp_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up. Starting books_db_1 ... Starting books_db_1 ... done Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known -
Unable to get image data in an API along with json data for registration
I want to create a register API in which I have username,email, password input along with an image field.I am unable to receive and process the data properly.The default user class is extended to store image field. I have this extended user model:- from django.contrib.auth.models import User import os def get_upload_path(instance, filename): fileName, fileExtension = os.path.splitext(filename) return os.path.join("user_%s" % instance.user.username,"user_{0}.{1}" .format(instance.user.username,fileExtension)) # Create your models here. class Userprofile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) display_picture=models.ImageField(upload_to=get_upload_path) has_voted=models.BooleanField(default=False) voted_item=models.CharField(max_length=200,default='none') def __str__(self): return self.user.username These are the serializers:- from django.contrib.auth.models import User from .models import Userprofile class UserprofileSerializer(serializers.ModelSerializer): class Meta: model=Userprofile fields=['display_picture'] class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['username','email','password1','password2'] this is the path/url:- path('register',views.FileUploadView.as_view(),name='Register'), this is the view:- @csrf_exempt class FileUploadView(APIView): parser_classes=[MultiPartParser,FormParser] def register(self,request): display_picture=request.FILES["display_picture"] data=json.loads(request.data["data"]) #saving data using serializers return JsonResponse({'message': "Registered Successfully!"},status=200) I am getting this issue which says:- path('register',views.FileUploadView.as_view(),name='Register'), AttributeError: 'function' object has no attribute 'as_view' -
how to pass image file from database to html in django project
I tried many solution to solve it. But I can't fix and resolve. I can't able to pass the image file of my users to my html page. But I can able to access and pass all elements from database of a specific user. When I try to access the Image file of a user, it just returns a file path of the image. Please help me to resolve it. models.py class registration(models.Model): First_Name =models.CharField(max_length=50) Last_name = models.CharField(max_length=50) Phone_number = models.BigIntegerField() Email_id = models.EmailField() Password = models.CharField(max_length=20) Conform_Password = models.CharField(max_length=20) Register_No = models.BigIntegerField(primary_key=True) profile_pic = models.ImageField(upload_to="Profile") def __str__(self): return self.First_Name views.py def login(request, *args, **kwargs): if request.method == 'POST': user_Name=int(request.POST["stu_uname"]) pass_word=request.POST["stu_pwd"] get_user_name = registration.objects.filter(Register_No = user_Name).exists() if get_user_name is True: check_pwd = registration.objects.values('Password').filter(Register_No = user_Name) for check in check_pwd: pwd = check['Password'] if pwd == pass_word: user_objects = get_objects(user_Name) return render(request, "stu_profile.html", {'userObj': user_objects}) else: return HttpResponse("<h1> Password is incorrect</h1>") else: return HttpResponse("<h1> User name is incorrect </h1>") return redirect('student') def get_objects(name): check_objects = registration.objects.values().filter(Register_No = name) for check in check_objects: values = check return values HTML PAGE <div class="pro_pic"> <img src = "{{userObj.profile_pic}}"> <div> <p> {{userObj.First_Name}} {{userObj.Last_name}} </p> </div> </div> Settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'Pictures/') MEDIA_URL = '/Pictures/' -
Django no module named import_exportquestions
I am new to Django. I am trying to import questions from an excel file to my sqllite db. The steps i made is the following: 1) I have created a new env and installed django-import-export in it 2) started a project webload in Django 3) Created an app with name questions that defines the model Question like this from django.db import models # Create your models here. class Question(models.Model): q_id = models.CharField(max_length=10) category1 = models.CharField(max_length=100) category2 = models.CharField(max_length=100) descr = models.TextField() 4) registered my models in admin.py with the following from .models import Question admin.site.register(Question) from import_export import resources from core.models import Question class QuestionResource(resources.ModelResource): class Meta: model = Question but when i try to makemigrations the following error appears ModuleNotFoundError: No module named 'import_exportquestions' where is my mistake? -
django seems to have a leak of windows system handles
I've been practicing and learning Django. but i found that on my windows 7 64bit, when i run server, windows handles' number jump up by 2000 per second. very intimidating.(refer to my pic below) and then at the end , my laptop died with "insuffient recouses to complete service". I have to power off my laptop, even "shutdown" button can't work. running other python program works fine. I've been working on python for 2 years. django version = 1.11 , 3.0 I also tried, still the same. appreciate if you have some workaround. Danny windows handles 2000 added per a second when running django runserver -
How to display django success message in every template from one view?
Here I have one function for newsletter which will be used in every template in the project.The issue here is the success message is displaying only in the contact page template.I have placed django message tag {{message}} in the base.html only.It is working fine in the contact.html page.The corresponding message for contact and newsletter displays correctly in the contact_page template but not in other templates .Other templates also extends base.html like the contact.html. How can i display newsletter success message in every template.I don't want to write {{message}} in every template. Is there any solution for this ? views.py def contact(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your message has been sent successfully.') return redirect('contact:contact_page') return render(request, 'contact/contact_page.html', {'form': form}) def newsletter(request): form = NewsletterForm() if request.method == "POST": form = NewsletterForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank you for your subscription.') return redirect(request.META['HTTP_REFERER']) return render(request, 'base.html', {'news_form': form}) -
ERROR : Target WSGI script not found or unable to stat
I use elasticbeanstalk and setting .ebextensitons/django.config as : option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings and also, wsgi.py is exist in config. I don't know why below error message appear. [Sun Feb 16 06:24:43.546754 2020] [:error] [pid 4688] [client ~~~ip~~~~~] Target WSGI script not found or unable to stat: /opt/python/current/app/config [Sun Feb 16 06:15:55.043332 2020] [:error] [pid 4575] [client ~~ip~~~~~] Target WSGI script not found or unable to stat: /opt/python/current/app/config, referer: ~~~~~aws RDS endpoint~~~~~~ -
django File "options.py", line 581, in get_field return self.fields_map[field_name] KeyError: 'user_email' error
I have not changed code of any file of django project. But when I execute python manage.py migrate I 'm getting error - ''' File "C:\Python37-32\lib\site-packages\django\db\models\options.py", line 581, in get_field return self.fields_map[field_name] KeyError: 'user_email' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python37-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python37-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Python37-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Python37-32\lib\site-packages\django\core\management\commands\migrate.py", line 233, in handle fake_initial=fake_initial, File "C:\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python37-32\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python37-32\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Python37-32\lib\site-packages\django\db\backends\sqlite3\schema.py", line 138, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "C:\Python37-32\lib\site-packages\django\db\backends\base\schema.py", line 537, in alter_field new_db_params = new_field.db_parameters(connection=self.connection) File "C:\Python37-32\lib\site-packages\django\db\models\fields\related.py", line 971, in db_parameters return {"type": self.db_type(connection), "check": self.db_check(connection)} File "C:\Python37-32\lib\site-packages\django\db\models\fields\related.py", line 968, in … -
how do i get values from multiple selected choice box in django
i am trying to get values from multple selected choice box the bellow attached screenshot make sense what i want,so when i select all these fields i want to save them in database,and want to display all selected fields value in django admin in same column with comma (,) separated, but the code bellow i write geting nothing from the fields except this one as square bracket'[]' django = 3.3 python = 3.7 image file models.py YourRoleInCompany = models.CharField(max_length=100,) views.py YourRoleInCompany = request.POST.getlist('YourRoleInCompany') signup.html <input type="checkbox" value="Investitor / Actionar" id="1" name="YourRoleInCompany"> <input type="checkbox" value="Manager General (CEO)" id="2" name="YourRoleInCompany" <input type="checkbox" value="Manager de Departament" id="3" name="YourRoleInCompany" <input type="checkbox" value="Lider de Echipa" id="4" name="YourRoleInCompany"