Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin panel is not displayed correctly, how to fix it?
This screenshot show the problem i am having. However, when you minimize window, the page is displayed normally.enter image description here -
no module named parsing when importing django models to python script
Hi there Im having issues importing my models into my application called parsing project structure looks like: manage.py enumproject/ db.sqlite3 parsing/ with enumproject/settings.py I have it in INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'parsing', 'parsing.apps.ParsingConfig', ] models.py under parsing/models.py has: from enumproject import models # Create your models here. class tbl(models.Model): nm=models.CharField(max_length=20, unique=True) dtAdded=models.DateTimeField() #etc... im attempting to run parse.py from parsing/parse.py from parsing.models import * #python code here when I run this file, I get: Traceback (most recent call last): File "parse.py", line 8, in <module> from parsing.models import * ModuleNotFoundError: No module named 'parsing' thoughts? -
Question about parsing a URL generated during a button click event in HTML
I built a form in HTML5 to take input from users. I'm using the GET method. I want to assign the data the user put into the form and assign it to variables in a python script, which will do some logic then render another page at the end of the script which will present the data to the user. I have been researching the past day or so about different methods by which this can happen. I'm running on Django right now. I was going to use CGI, because the syntax seemed pretty straightforward: import cgi form = cgi.FieldStorage() py_var = form.getvalue('name-in-html-tag') But from what I've read is that this method is only suitable for cgi scripts. When I print() py_var I continually get a value of None. So I started reading about using the urllib package to parse GET method urls. But the examples I keep finding online show the URL hardcoded into the scripts, which isn't much help in my situation. Is there a way that I can get the URL generated from the GET method so that I can parse it and use the data in a python script? Everyone seems to have their own way … -
Django save() method executed twice
I,m developing a simple CRUD app. There are two main models: empleado (employee) and oficina (office or department). Each "empleado" belongs to a "oficina" class empleado(models.Model): """Model definition for empleado.""" apellidos = models.CharField('Apellidos', max_length=50, blank=False) nombres = models.CharField('Nombres', max_length=50, blank=False) full_name = models.CharField('Nombre completo', max_length=50, blank=True) dni = models.CharField('DNI', max_length=50, blank=False, unique=True) habilidades = models.ManyToManyField(habilidad, blank=False) area = models.ForeignKey(oficina, on_delete=models.CASCADE, blank=False, related_name = 'area_empleado') The model for "oficina" has a field called "personal" that stores the number of employees in that department class oficina(models.Model): """Model definition for oficina.""" nombre = models.CharField('Nombre', max_length=50) nombre_corto = models.CharField('Nombre corto', max_length=50) personal = models.PositiveIntegerField(default = 0) I used generic views to create new employees class EmpleadoCreateView(CreateView): model = empleado template_name = "empleado/create.html" form_class = EmpleadoForm success_url = reverse_lazy('empleado_app:Lista de empleados') def form_valid(self, form): emp = form.save(commit=False) emp.full_name = emp.nombres + ' ' + emp.apellidos emp.save() return super(EmpleadoCreateView, self).form_valid(form) This is the EmpleadoForm class: class EmpleadoForm(forms.ModelForm): """Form definition for Empleado.""" class Meta: """Meta definition for Empleadoform.""" model = empleado fields = ('apellidos', 'nombres', 'dni', 'habilidades', 'area', ) widgets ={ 'habilidades' : forms.CheckboxSelectMultiple() In order to keep the number of employees updated, I use a couple of signals (for the "empleado" model): def update_personal_dec(sender, instance, **kwargs): … -
unable to render the context value in django template on ubuntu server
I have this piece of code that is working fine on my PC environment (virtual environment) but causing problems in a ubuntu, Nginx server. It is a digital ocean droplet actually. I am not very much familiar with ubuntu that's why I am unable to understand the cause of the problem. Now the problem is, that the 'checkout.html' template doesn't render the value of 'fire'. I have tried to troubleshoot manually and in the 'inspect' window I only see an empty label. Why is this happening, is it because of the django=2.2.3 version or ubuntu or Nginx or am I missing anything here? Note: I am updating the files through Filezilla. Kindly help, please. Views.py def checkout(request): return render(request, 'checkout.html', {'fire':"fire"}) checkout.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <label>{{fire}}</label> </body> </html> urls.py from .views import * path('checkout-page', checkout, name="checkout"), -
Urls file in django application
I am working with Django,have a type error TypeError: path() got an unexpected keyword argument 'name' but my urls.py file reads from. import views from importlib.resources import path from unicodedata import name urlpatterns=[ path('register_user/ ',views.register,name='user'), path('register/',views.registering_patient,name='register_patient'), ] -
Django i18n - how to translate included templates
I have a django project using i18n for translations. When I type : python3 manage.py makemessages -a All my project templates and views are processed to build the django.po file except the templates that are included within another template. Example the high-level template has: {% include 'journey/journeysTable.html' %} With journey/journeysTable.html looking like: {% load i18n %} {% load static %} <table class="table table-striped caption-top tableRowIsLink"> <thead> <tr> <th scope="col">{% trans "Code" %}</th> <th scope="col">{% trans "Name" %}</th> {%if hide_user is None %} <th scope="col">{% trans "Artist" %}</th> {% endif %} <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody id="journeysTableBody"> ... </body> </table> The {% trans %} tags do not produce any error, but associated text is not in the django.po file. journey is an app and the included template is in journey/templates/journey/ folder. Other templates in the same folder are translated. Is it a normal behaviour? I understand that both templates are rendered separately but they should both be translated. -
FileResponse with file opened using smart-open
I'm trying to let a user download a file from my webpage. The file is in an S3 bucket I'm accessing using smart-open. The issue I'm having is how to combine that with FileReader. Presently I'm getting a TypeError: "expected str, bytes or os.PathLike object, not Reader". The filetypes will be .txt, .pdf and .doc/.docx My view: @api_view(['GET']) def download_attachment(request, pk): session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) obj = Attachment.objects.get(id=pk) with smart_opener(f's3://______media/public/{str(obj)}',"rb",transport_params={'client':session.client('s3')}) as attachment: response = FileResponse(open(attachment, 'rb')) response['Content-Disposition'] = f'attachment; filename={obj.file.name}' return response -
define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
I have no idea what to Ive tried uninstalling python and django. Reinstalled it failed, installed it in Unbuntu still doesnt work. I get the same error message. Nothing works! ''' Traceback (most recent call last): File "/tmp/virtual-virgin_env/my_env/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/conf/init.py", line 92, in getattr self._setup(name) File "/tmp/virtual-virgin_env/my_env/lib/python3.10/site-packages/django/conf/init.py", line 72, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ''' -
how to find sum from foreign key table along with some filtering in django orm?
class UserAndQuiz(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) quiz = models.ForeignKey(QuizInfo,on_delete=models.CASCADE) created_at = models.DateTimeField(null=True,blank=True) is_submit = models.BooleanField(default=False) result = models.IntegerField(default=0) class QuizInfo(models.Model): quiz_name = models.CharField(unique=True,max_length=255) number_of_question = models.IntegerField() number_of_option = models.IntegerField() quiz_type = models.CharField(max_length=255,choices=quiz_status) price = models.FloatField(default=0.0,null=True,blank=True) image = models.ImageField(upload_to='pics') description = models.TextField() def __str__(self) -> str: return self.quiz_name Related SQL query = SELECT sum(price) from quizsession_quizinfo as q JOIN user_userandquiz as p on q.id = p.quiz_id where p.is_submit=1; what is the ORM of this query? -
Why i am getting this error no such table: main_person, if i never tried to create that table?
I am trying to create my first crud with django, but now i came across with this error i have the urls like this, this is in the same level with wsgi.py urlpatterns = [ path('admin/', admin.site.urls), path('getData/', include('main.urls')), ] now i create other urls in my app inside: from django.urls import path from .views import getCars urlpatterns = [ path('', getCars), ] this is the view import imp from urllib import response from django.shortcuts import render from django.http import JsonResponse from django.core.serializers import serialize from .models import Person def getCars(request): cars = Person.objects.all() response_object = {'data': serialize("json", cars)} return JsonResponse(response_object) and the model is this from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) in any moment i am using main_person but i am getting this error: django.db.utils.OperationalError: no such table: main_person -
Packages Are not Importing on Docker even though they seem to be installed
I have tried installing new packaged. they all seem to load without and issue but somehow they are not importing. I have tried docker-compose build to no avail. They show up on pip freeze. My guess is somehow these are not loaded on my docker container but I am not sure what else to do. Sorry if my question is too elementary for this sub. I am a CS major and this is our first large project working with backend and frontend and I have stayed up all night trying to figure this up but I am lost I feel. Thanks for your help. Here are some of the packages in question drf-spectacular 'rest_framework', 'rest_framework.authtoken', django-address here is the content of my requirement.txt: Django>=3.2.4,<3.3 djangorestframework>=3.12.4,<3.13 psycopg2>=2.8.6,<2.9 drf-spectacular>=0.15.1,<0.16 here is what I have under registered apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'rest_framework', 'rest_framework.authtoken', 'drf_spectacular', 'user', 'address', 'phonenumber_field', pip freeze shows the following Mobile>pip freeze absl-py==1.0.0 alabaster @ file:///home/ktietz/src/ci/alabaster_1611921544520/work anaconda-client @ file:///C:/ci/anaconda-client_1635342725944/work anaconda-navigator==2.1.1 anaconda-project @ file:///tmp/build/80754af9/anaconda-project_1626085644852/work anyio @ file:///C:/ci/anyio_1620153135622/work/dist appdirs==1.4.4 argh==0.26.2 argon2-cffi @ file:///C:/ci/argon2-cffi_1613037869401/work arrow @ file:///C:/ci/arrow_1617738834352/work asgiref==3.5.2 asn1crypto @ file:///tmp/build/80754af9/asn1crypto_1596577642040/work astroid @ file:///C:/ci/astroid_1628063282661/work astropy @ file:///C:/ci/astropy_1629829318700/work astunparse==1.6.3 async-generator @ file:///home/ktietz/src/ci/async_generator_1611927993394/work atomicwrites==1.4.0 attrs @ file:///tmp/build/80754af9/attrs_1620827162558/work autopep8 @ … -
Advance django filters
I am working on a management system. Where I have models: class FeeType(models.Model): name = models.CharField("fee Type", max_length=200) duedate = models.DateField("due date") class Meta: verbose_name_plural = "Fee Type" def __str__(self): return self.name class CollectFee(models.Model): boarder = models.ForeignKey(Boarder, on_delete=models.CASCADE) feetype = models.ForeignKey(FeeType, on_delete=models.CASCADE) amountpaid = models.PositiveIntegerField("amount Paid") class Meta: verbose_name_plural = "Collect Fee" def __str__(self): return self.boarder.name Now in a template I want to show the list of all the boarders/students, who have not been assigned the last fee. e.g if "July Fee" is the last object in the FeeType model then show all those boarders who have not been assigned the JulyFee. I have tried a view for this: def feedue(request): last_fee_type = FeeType.objects.last() boarders = CollectFee.objects.exclude(boarder__collectfee__feetype=last_fee_type) context = {'boarders':boarders} return render(request, 'fee-due.html', context) It does not show the boarders who have been assigned the last feetype, that's correct. But if the boarder is not assigned the last feetype then it shows the boarder name as many times as he have been assigned the previous feetypes. Hope you understand. Help please. -
Issues with connecting python/pandas, to a Postgress DB hosted on Django Digital Ocean
I have difficulty finding my known tables in a Django/Postgress DB hosted on Digital Ocean. I seem only to get an outer layer of the database and not the tables working on the site's front end. conn = psycopg2.connect( host=HOST, database=DATABASE, user=USERNAME, password=PASSWORD, port=PORT, ) cur = conn.cursor() cur.execute("""SELECT table_name FROM information_schema.tables""") for table in cur.fetchall(): print(table) Here is a portion of the results, and not a single one is a known table books. ('pg_type',) ('pg_foreign_server',) ('pg_roles',) ('pg_settings',) ('pg_cursors',) ('pg_stat_bgwriter',) ('pg_subscription',) ('pg_stat_progress_vacuum',) ('pg_stat_progress_cluster',) ('pg_attribute',) . . . ('view_table_usage',) ('foreign_server_options',) ('column_options',) ('foreign_data_wrapper_options',) ('foreign_tables',) ('foreign_data_wrappers',) ('foreign_servers',) ('foreign_table_options',) ('user_mappings',) ('user_mapping_options',) I hope to finally run: df = pd.read_sql('select * from books', my_eventual_successful_connection) I get more discouraging results from SQLAlchemy, which does not output a result nor logging info for the following: engine = create_engine(f"postgresql+psycopg2://doadmin:{PASSWORD}@{HOST}:{PORT}/{USERNAME}?sslmode=require") from sqlalchemy import MetaData metadata_obj = MetaData() for t in metadata_obj.sorted_tables: print(t.name) While this: metadata_obj.tables.keys() returns (including the logging): INFO:sqlalchemy.engine.Engine:SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = %(schema)s AND c.relkind in ('r', 'p') INFO:sqlalchemy.engine.Engine:[cached since 38.66s ago] {'schema': 'public'} dict_keys([]) Though when I run: with engine.connect() as connection: df = pd.read_sql('select * from user', connection) df I get user 0 doadmin note … -
Django rest framework - Limiting get request access to only authorized user
You can see in this serializer I am checking that the authenticated user matches the instance's user: class CreateSupplierSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=200) email = serializers.EmailField(max_length=200) phone = serializers.IntegerField() def update(self, instance, validated_data): if str(self.context['request'].user) != str(instance.username): raise exceptions.PermissionDenied('You do not have permission to update') supplier = Supplier.objects.create(user=instance, **validated_data) return supplier class Meta: model=Supplier fields=['name','email','phone'] I am wondering how I can implement this same method into my get request, here is my get request format... models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.CharField(max_length=200) email = models.CharField(max_length=200) class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.IntegerField() email = models.EmailField(max_length=200) views.py: class getsuppliers(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = GetSuppliersSerializer lookup_field = 'username' serializers.py: class SuppliersSerializer(serializers.ModelSerializer): class Meta: model = Supplier fields = ['pk','user','name','email','phone'] class GetSuppliersSerializer(serializers.ModelSerializer): supplier_set = SuppliersSerializer(read_only=True, many=True) class Meta: model = User fields = ['supplier_set'] -
Django combine search filter and annotation does not work
i am try to filter by datetime range but get wrong annotation results. def is_valid_queryparam(param): return param != '' and param is not None def my_func(request, tenant): products = Product.objects.filter(tenant=tenant).annotate( s_product=Sum('order_items__quantity'), vlera=Sum('order_items__price')) date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') if is_valid_queryparam(date_min): products = products.filter(Q(created__gte=date_min)) if is_valid_queryparam(date_max ): products = products.filter(Q(created__gte=date_max)) the filter date range works for objects products, but not for the order_items__quantity and order_items__price, the result are incorrect -
How do I add a manytomany model field instance inside a ModelForm?
I have implemented a CustomUser model(using AbstractUser) and it has some ManytoManyFields. Now I can add an instance of it inside the admin panel but I haven't found out any ways to do it inside a ModelForm(without already having some ready made instances of it in database). The pic below shows the difference I'm trying to describe between what is available inside the admin and inside html templates form. -
Django Safari Iframe Issue
We have shopify app in django that is embedded in shopify. But this app is facing issues as an iframe in Safari Browser. I have referenced this doc https://pypi.org/project/django-iframetoolbox/ . But I didnt understand the order in which I have to include this in the MIDDLEWARE_CLASSES in settings.py. 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', 'csp.middleware.CSPMiddleware', 'shopify_app.middleware.LoginProtection', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'iframetoolbox.middleware.IFrameFixMiddleware', ] This is the current order in which I have given and this is giving me the following error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'shopify_django_app.wsgi.application' could not be loaded; Error importing module. -
Django - Google Analytics not tracking properly
Followed a tutorial and added google analytics to my django site by placeing the tracking code into the head of my base.html as well as a different page that does not extend from base. <!DOCTYPE html> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-trackcode"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-trackcode'); </script> </head> However the other day I ran a facebook ad and sent over 200 clicks to my site, google only tracked 30 of these clicks. And when viewing my pages it does not seem to properly track individual pages and only tracked 3 pages, the majority of the traffic is just under the root domain. (its a blog style site so i need to see exactly what pages users are most interested in) -
Django annotation with reference to another table
I have two Django models as follows: class TableA(Model): some_string_id: str something_i_need: int class TableB(Model): some_string_id: str I am trying to create a group_by operation of some_string_id of TableA, but also add the something_i_need from TableB accordingly. I thought on doing something as follows, but am not sure what to replace the ??? with. Any ideas? TableA.objects.filter(...).values("some_string_id").annotate(something_i_need=???) P.S: I know that a foreign key could have helped, but those are not my tables to edit... -
Return Upper Date in DateTimeTZRange
I have a model where i have a field called date range. which returns a range of date range both the date range is same but the time changes how can i access one date from range in the model using ORM. class My_model(models.Model): date_range = ranges.DateTimeTZRange() -
The current path, index.php, didn’t match any of these
** Good day, please am new to Django and am facing some challenges which have tried to resolve but am not yet resolve please i need your help. ** the error are below Page not found (404) Request Method: GET Request URL: https://mydomain/pages/index.php** Using the URLconf defined in dcitygate.urls, Django tried these URL patterns, in this order: admin/ [name='index'] blog/ [name='blog'] audio_messages/ [name='audio_messages'] imgc/ [name='imgc'] imgc/<int:id> [name='imgc_detail'] tsc/ [name='tsc'] tsc/<int:id> [name='tsc_detail'] word_prayer/ [name='word_prayer'] word_prayer/<int:id> [name='word_prayer_detail'] video_messages/ [name='video_messages'] contact_us/ [name='contact_us'] couple_meeting/ [name='couple_meeting'] kcc/ [name='kcc'] kcc/<int:id> [name='kcc_detail'] pages/streaming/ [name='streaming'] watchlive/ [name='watchlive'] <int:id> [name='audio_streaming_detail'] listenlive/ [name='listenlive'] blogs/ audio_msg/ ^media/(?P<path>.*)$''' *The current path, index.php, didn’t match any of these* my Project.url from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url urlpatterns = [ path('admin/',admin.site.urls), path('', include('pages.urls')), path('blogs/', include('blogs.urls')), path('audio_msg/', include('audio_msg.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MyApp.url from django.urls import path, re_path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), path('blog/',views.blog, name='blog'), path('audio_messages/', views.audio_messages, name='audio_messages'), path('imgc/', views.imgc, name='imgc'), path('imgc/<int:id>', views.imgc_detail, name='imgc_detail'), path('tsc/', views.tsc, name='tsc'), path('tsc/<int:id>', views.tsc_detail, name='tsc_detail'), path('word_prayer/', views.word_prayer, name='word_prayer'), path('word_prayer/<int:id>', views.word_prayer_detail, name='word_prayer_detail'), path('video_messages/', views.video_messages, name='video_messages'), path('contact_us/', views.contact_us, name='contact_us'), path('couple_meeting/', views.couple_meeting, name='couple_meeting'), path('kcc/', views.kcc, name='kcc'), path('kcc/<int:id>', views.kcc_detail, name='kcc_detail'), … -
Validate Password In Reset Django View
**Iam using the built-in django view to reset password so my Question is how can i validate the password to make it have 1 capital letter and 1 symbol at least?? -
Resolve Django/DRF ImageField URL from F() function
I have a use case where I'm attempting to override an Image URL if it exists in our database. Here is the section of the queryset that is grabbing the ImageField from via an F() query. preferred_profile_photo=Case( When( # agent not exists Q(agent__id__isnull=False), then=F("agent__profile__profile_photo"), ), default=Value(None, output_field=ImageField()), ) The Case-When is resolving correctly, but the issue is the value returns from F("agent__profile__profile_photo") is not the URL than can be used by the UI. Instead it is something like: "agentphoto/09bd7dc0-62f6-49ab-blah-6c57b23029d7/profile/1665342685--77e51d9c5asdf345364f774d0b2def48.jpeg" Typically, I'd retrieve the URL via agent.profile.profile_photo.url, but I receive the following when attempting to perform preferred_profile_photo.url: AttributeError: 'str' object has no attribute 'url'. I've tried wrapping in Value(..., output_field=ImageField()) with no luck. The crux here is retrieving the url from the ImageField after resolving from F() For reference, I'm using storages.backends.s3boto3.S3Boto3Storage. Appreciate any help! -
DJango error: 'MercanciasForm' object is not callable
I'm building a CRUD, for insert and delete I use a modal (works perfect in both cases), but not for edit, I redirect or render to a create.html page. In all cases I use the current View (ListView, CreateView, UpdateView and DeleteView). In the especific case of UpdateView named MercanciasUpdateView I got this 'MercanciasForm' object is not callable error. MercanciasForm is the form that I use in all cases. In MercanciasListView I have to set this line context['form'] = MercanciasForm() becasue it ws the only way of Modal recognize the form, not recognize the form_class. The Form code class MercanciasForm(ModelForm): codigo = CharField(label='Code',widget=TextInput(attrs={'class':'form-control','placeholder':'Código'})) nombremercancia = CharField(label='Nombre',widget=TextInput(attrs={'class':'form-control', 'placeholder':'Nombre'})) um = CharField(label='UM',widget=TextInput(attrs={'class':'form-control', 'placeholder':'UM'})) clasificacion = ClasificacionesModelChoiceField(label='Clasificación',queryset=Clasificaciones.objects.order_by('id'), empty_label='Seleccione: ', widget=Select(attrs={'style':'width: 100%', 'class':'form-control select2bs4'}), to_field_name='clasificacion') descripcion = CharField(label='Descripción',widget=Textarea(attrs={'style':'height:150px', 'class':'form-control', 'placeholder':'Descripción'})) class Meta: model = Mercancia fields='__all__' The views.py code class MercanciasListView(ListView): model = Mercancia template_name = 'mercancia/index.html' form_class = MercanciasForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Lista de mercancias" print(reverse_lazy('mercancias')) context['form'] = MercanciasForm() return context class MercanciasCreateView(SuccessMessageMixin, CreateView): model = Mercancia form_class = MercanciasForm success_url = reverse_lazy('mercancias') success_message = "Insertado correctamente!!!!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class MercanciasUpdateView(SuccessMessageMixin, UpdateView): model = Mercancia form_class = MercanciasForm() template_name = 'mercancia/edit.html' success_url …