Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django select rows by max value of field
I have a table in django like this: class Observation: plant = model.ForeignKey Trait = model.ForeignKey value = model.CharField creation_time = model.DateTimeField I want to make a query to get only the newest rows with unique plant/trait combination. Ex: row1 plant1 trait1 value1 dateyesterday row2 plant1 trait1 value3 datetoday row3 plant1 trait2 value1 datetoday The query should return only row2 and row3 I have resolved it in SQL: SELECT * FROM vavilov_observation AS o WHERE o.creation_time = (SELECT MAX(creation_time) FROM vavilov_observation AS o2 WHERE o.plant_id=o2.plant_id AND o.trait_id=o2.trait_id) Someone can help me transforming this SQL into a django queryset? Until now The only solution I have found is to make a raw queryset with this sql to get pks from and use them in a Observations.objects.filter(observation_id__in=rawquery_ids) query. This method is not well scalable. In one of the databases I have 500.000 rows and it takes too long to use in production. Any help? Thanks in advance peio -
Django 1.9 - Update or create, return added/edited id
im using update or create for a model as per the below device_inv = Inventory.objects.update_or_create( defaults={ 'location' : site, 'device' : dev_name }, device = dev_name ) Post which i assumed i would be able to use device_inv.id. however printi device_inv i get an object and False, which i presume is the object and the answer of whether it was updated or created? (true being created, false being edited) >>> print device_inv (<Inventory: Inventory object>, False) ive also tried a few ways of tyring to access the object none which seem to be working >>> for i in device_inv[0]: ... print i ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Inventory' object is not iterable >>> print device_inv[0]["id"] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Inventory' object has no attribute '__getitem__' Could anyone point me in the right direction? Thanks -
i want to use ajax variable in other function
I want to use modal, so i get the data value from ajax. the data is like that [{'source_name': '인터넷', 'description': '여행자료', 'source_slug': '_1', 'subject_name': '여행', 'subject_slug': '_6'}] I want to put the value of source_name "인터넷" to source_name variable. I want to use soure_name variable at this line. html += '<li><span> 출처 : <a href="/tag/' + source_slug + '">' + source_name + '</a>' but source_name is undefined. please help me this is code. function showModal(){ var pk = $(this).find('img').attr('id'); $.ajax({ url : '/photo/' + pk + '/', async: false, success: function(data){ data= JSON.stringify(data) var source_slug = data[0]["source_slug"]; var source_name = data[0]["source_name"]; var description = data[0]["description"]; var subject_slug = data[0]["subject_slug"]; var subject_name = data[0]["subject_name"]; } }); var src = $(this).find('img').attr('src'); var largeImg = $(this).find('img').attr('data-bsp-large-src'); if(typeof largeImg === 'string'){ src = largeImg; } var index = $(this).attr('data-bsp-li-index'); var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index'); var ulId = $(this).parent('ul').attr('data-bsp-ul-id'); var theImg = $(this).find('img'); var pText = $(this).find('.text').html(); var modalText = typeof pText !== 'undefined' ? pText : 'undefined'; var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null; clicked.img = src; clicked.prevImg = parseInt(index) - parseInt(1); clicked.nextImg = parseInt(index) + parseInt(1); clicked.ulIndex = ulIndex; clicked.ulId = ulId; $('#bsPhotoGalleryModal').modal(); var html = ''; var img … -
Django rest framework: automatically create a url for each field of a model
I have large table of data (~30 Mb) that I converted into into a model in Django. Now I want to have access to that data through a REST API. I've successfully installed the Django REST framework, but I'm looking for a way to automatically create a URL for each field in my model. My model has about 100 fields, and each field has about 100,000 entries. If my model is named Sample, models.py class Sample(models.Model): index = models.IntegerField(primary_key=True) year = models.IntegerField(blank=True, null=True) name = models.TextField(blank=True, null=True) ...97 more fields... then I can access the whole model using Django REST framework like this: urls.py class SampleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Sample fields = ( **100 fields**) class SampleViewSet(viewsets.ModelViewSet): queryset = Sample.objects.all() serializer_class = SampleSerializer router = routers.DefaultRouter() router.register(r'sample', SampleViewSet) But of course my browser can't load all of that data in a reasonable amount of time. I could manually make a different class and URL for each field, but there must be a better way... I want to be able to go to my_site.com/sample/year (for example) and have it list all of the years in JSON format, or my_site.com/sample/name and list all the names, etc. Please help me figure out … -
Modifying Django Command argument
Lets say i have a command like: class Command(object): help = 'roll over and die' def add_arguments(self, parser): parser.add_argument( '--foo', help='see command help', choices=['die','die_painfully'], required=True ) parser.add_agument( ... ) x 9001 and now i want to have an almost identical class but i dont want the argument '--foo' to required anymore. Can u modify that parser somehow if i super the hole add_arguments in the inhering method or something? -
Django: in-memory syncing of foreign key instances shared by two objects
I have a model (Child) with a foreign key (Parent). I load two instances of Child that have the same Parent into memory. parent = Parent() # Bind both children to the same parent instance child1 = Child(parent=parent) child2 = Child(parent=parent) child1.parent.change_property_x(new_value) child1.parent.save() current_value = child2.parent.get_property_x() assert new_value == current_value I would expect that when both children are loaded into memory simultaneously, their parents should be the same instance and that changing one should instantly change the other, but this doesn't seem to be the case. In my code, I have methods that perform multiple operations on many children and their parents at a time, and I would like to avoid having to refresh instances from database every time I need to access or modify their properties. Is that possible? -
Invalid URL pattern using Django with Mezzanine
I'm relatively new using Mezzanine and Django. But I run the manage.py with runserver as a parameter and I get the following error. ERRORS: ?: (urls.E004) Your URL pattern (u'^', (<module 'mezzanine.urls' from 'C:\Users\khirst\InovaSupportSiteIsolated\lib\site-packages\mezzanine\urls.py'>, None, Non e)) is invalid. Ensure that urlpatterns is a list of url() instances. HINT: Try using url() instead of a tuple. I browsed through Mezzanine's urls.py, and it seems to be properly updated for the new urlpatterns standards. I am using Django 1.10.0, and Mezzanine 4.2.2. There are several lines that use urlpatterns += [url("^", include("..") .. of some sort. I am guessing that means that for every url, add the following module as a possible match. It seems that Django doesn't like one of these. I can't find any help with this on Mezzanine's site or otherwise. Supposedly this version of Mezzanine and Django are supposed to be compatible. Has anyone else encountered this? -
First Post. Django
This is my first post on stackoverflow. I am a newbie when it comes to programming. Over the past month I have been teaching myself python and recently mustered up the courage to tackle Django. My question is two fold: Based on your personal experience, is there an increasing market demand for Django programmers? What resource(s) would you recommend for someone new to programming seeking to learn the framework? Because I am so new to all of this, I am wondering if my current rudimentary understanding of web development is sound. -Javascript--> used in front-end design. Allows you to create dynamic webpages -Html--> used in front-end design allows you to design the shell of your site. -CSS--> a styling language (front-end design) that allows you to improve your site aesthetically. -Bootstrap--> CSS library created by Twitter designers. Makes website design easier -Python/Django--> used to create the website logic/back end. I appreciate your help. -
Django Form from Model in pure Python
Intro I'm trying to create interface to provide easy access to online game data. There are some basic parameters of each hero in the database, created with HeroModel class (using SQLAlchemy). Problem Also there is need to create Manager class above the Model to change data in its instance (in the Manager), but not in the database. The only way to implement this, as I see now is to rewrite all the Model field to Manager class. "Form from Model" mechanism seems like right solution for me. Question How can I implement this idea in Python? -
Django script fails to save model instance, complains a field with a value is null...?
I'm doing the most simple of operations and getting an error... I'm pulling a model instance, updating some fields, and then saving those fields that I modified. I get back an error saying that a null value is not allowed for one of those fields. That boolean field has a default in models.py, AND in the database, AND it's one of the fields I'm saving a value for. models.py class Person(TimeStampedModel): # ... precertified = models.BooleanField(default=False) logic.py try: print('Getting Person %s...' % record['nurturing_id']) person = Person.objects.get(pk=record['nurturing_id']) except Person.DoesNotExist: person = None print('Person %s no longer exists.' % record['nurturing_id']) if person: person.uncorrected_address = person.address person.uncorrected_address_line_two = person.address_line_two person.uncorrected_city = person.city person.uncorrected_state = person.state person.uncorrected_zipcode = person.zipcode person.address = record['Address'] person.address_line_two = record['Address Line Two'] person.city = record['City'] person.state = record['State'] person.zipcode = record['Zipcode'] person.precertified = True person.precertified_check = now person.save(update_fields=['precertified', 'address', 'address_line_two', 'city', 'state', 'zipcode', 'uncorrected_address', 'uncorrected_address_line_two', 'uncorrected_city', 'uncorrected_state', 'uncorrected_zipcode', ]) Using person.save() also fails. Traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "/sites/easy/apps/JSM/logic.py", line 1349, in precertify_contacts person.save(update_fields=['precertified', 'address', 'address_line_two', 'city', 'state', 'zipcode', 'uncorrected_address', 'uncorrected_address_line_two', 'uncorrected_city', 'uncorrected_state', 'uncorrected_zipcode', ]) File "/Environments/easy/local/lib/python2.7/site-packages/model_utils/tracker.py", line 134, in save ret = original_save(**kwargs) File "/Environments/easy/src/easyapps/nurturing/models.py", line 248, in save super(Person, … -
django datetimefield and postgres
I have the following model and form class TravelShare(Share): # indirect derived via Share from models.Model source = models.PointField(geography=True, srid=4326) destination = models.PointField(geography=True, srid=4326) departure = models.DateTimeField(default=timezone.now) departure_delta = models.SmallIntegerField(default=60) objects = TravelShareManager() def __str__(self): return self.id class TravelShareForm(forms.ModelForm): class Meta: model = TravelShare fields = ['source', 'destination', 'departure', 'departure_delta'] When testing the form with def test_TravelShareCreate(self): source = Point(x=48.0, y=11.0, srid=4326) destination = Point(x=48.0001, y=11.0001, srid=4326) now = timezone.localtime(timezone.now()) print ("now : %s" % (now)) now_string = now.strftime('%m.%d.%Y %H:%M:%S') form_data = { 'source': source, 'destination': destination, 'departure': now_string, 'departure_delta': 30, } form = TravelShareForm (form_data) print (form.errors) self.assertTrue(form.is_valid()) form.instance.creator = self.creator result = form.save() self.assertEqual(result.creator_id, self.creator.id) self.assertEqual(result.source, source) self.assertEqual(result.destination, destination) result_dep = timezone.localtime(result.departure) print("result_dep : %s" % (result_dep)) self.assertEqual(result.departure, now) I am ending up in now : 2017-02-10 15:49:21.935894+01:00 result_dep : 2017-10-02 15:49:21+02:00 Failure Traceback (most recent call last): File "/home/michael/PycharmProjects/sharadar/main/tests/test_forms.py", line 43, in test_TravelShareCreate self.assertEqual(result.departure, now) AssertionError: datet[14 chars]017, 10, 2, 15, 49, 21, tzinfo=DstTzInfo 'Eur[25 chars]DST) != datet[14 chars]017, 2, 10, 15, 49, 21, 935894, tzinfo=DstTzI[32 chars]STD It seems that the resulted DateTime has a different TZ or at least shows +2 instead of +1 Thanks for any help Michael -
Django discard the join data when Serialize Json and geojson
In Django Views: I want join the data from two table. lease_geom.query gives right query but when i serialize the lease_geom there is no data from related table. def mapdata_leases_geom(request, lic): # only one table data lease_geom = Ssm_El_Ml_Pl_Blocks.objects.filter(license=lic).select_related() q = lease_geom.query lease_geom = serialize('geojson', lease_geom, geometry_field='geom') The function just return the geojson of 1st table. -
Improve AND query condition by AND/OR
I made a little script with Django in order to search and display objects with query request. I have 3 fields : lastname, firstname and birthday. Up to now, I had icontains conditions to both first one and birthday had only a contains condition. Because I just want to write year and get result. I can be more precise if I search YYYY-MM-DD obviously. I wrote my script like this : query_lastname_list = Identity.objects.filter(lastname__icontains=query_lastname, firstname__icontains=query_firstname, birthday__contains=query_birthday) But I have to fill all fields if I want a result. My question is : How I can write my line above in order to get a result if I filled only 1, 2 or 3 fields ? (Lastname and birthday, just firstname, 3 fields, ....). If I write something like : from django.db.models import Q query_result_list = Identity.objects.filter(Q(lastname__icontains=query_lastname) | Q(firstname__icontains=query_firstname) | Q(birthday__contains=query_birthday)) I just have to fill 1 field, but if I want write 2 fields, or even 3, what I have to write ? The scheme could be : Field 1 AND/OR Field 2 AND/OR Field 3 Thank you -
Django CAN find my static files, Pycharm CANNOT resolve them
I do not think this is a duplicate. I have looked at a lot of answers to similar problems. Please note: This runs perfectly fine and django finds all static files. Pycharm cannot resolve, whch means that I cannot use auto complete, and it is annoying. If I hit ctrl-space the only directory that pops up is admin. This means that PyCharm is completely ignoring my static directory. I have also tried making it a templates directory and a resourse director. No luck there either. {% load static %} <!-- {% load staticfiles %} --> ... <link rel="stylesheet" href="{% static ''%}"> <link rel="stylesheet" href="{% static 'css/skeleton.css' %}"> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> ... The code above works fine. PyCharm does not find the urls though. INSTALLED_APPS = [ 'django.contrib.staticfiles', # admin specific 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_URL = '/static/' -
Why does the admin site not care about my custom user's permissions?
I started a Django (1.10.3) project with a custom user model, inherited from AbstractBaseUser. A couple of weeks into developing the thing, I saw that I needed more granular permissions for admin users, so I extended my user model with PermissionsMixin, generated and applied migrations, and updated my ModelAdmin. To try it out I logged in to the admin with my superuser and created a new user with all permissions added manually. When I logged in with that new user, I was greeted by a nice "You don't have permission to edit anything". So I went to the shell, checked my user's permissions and they were there. >>> u = User.objects.get(username='new_user') >>> u.get_all_permissions() {'admin.add_logentry', ...} However, >>> u.has_perm('admin.add_logentry') False Now, what has_perm does, if the user is not an active superuser, is to call this: def _user_has_perm(user, perm, obj): for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: return False return False But, >>> from django.contrib.auth import get_backends >>> backend = get_backends()[0] # django.contrib.auth.backends.ModelBackend >>> backend.has_perm(u, 'admin.add_logentry') True So, Why are user.has_perm(perm) and backend.has_perm(user, perm) returning different values? And ultimately, how can I get the permissions system to work correctly in … -
Python Django no module named app in eclipse
I just made first django project in eclipse. I created an app and did 'make migration' so that create tables in admin but got this error message. Traceback (most recent call last): File "C:\Users\jeon hyun joo\workspace\blog\blog\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\apps\registry.py", line 115, in populate app_config.ready() File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\utils\module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\jeon hyun joo\workspace\blog\blog\polls\admin.py", line 2, in <module> from blog.polls.models import Question, Choice ImportError: No module named polls.models Finished "C:\Users\jeon hyun joo\workspace\blog\blog\manage.py makemigrations polls" execution. I registered app in settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls' ] and also I have init.py file in every packages. What I did in this project is creating one application and editing models.py and admin.py. I haven't created any other files. What can I do to solve this problem? -
Static file can't run succefully?
I have main.js file. I use the static's setting(red part) My hello_world.html use main.js file. But it can't run succefully. How to modify this? Thank you. -
Get data from User table and extended User table
I have extended user model in Django. The model for extending user is as follows : class Member(models.Model): user_id = models.ForeignKey(to=User) number = models.CharField(max_length=10) match_code = models.CharField(max_length=50) parent = models.ForeignKey("self", null=True, blank=True) name = models.CharField(max_length=100) address = models.CharField(max_length=255) postcode = models.CharField(max_length=10) city = models.CharField(max_length=100) country = models.ForeignKey(to=Country, null=True) language = models.ForeignKey(to=Language) telephone = models.CharField(max_length=50) mobile = models.CharField(max_length=50) main_email = models.EmailField(null=True) def __str__(self): return self.name Now I want to check if user exist matching email from User table and number from Member table. How can I do that? Right now I'm doing this as follows : email = "some@email.com" user = User.objects.get(email=email) member = Member.objects.get(user_id=user.id) Thus I get first data from User table and then I get everything from member table. But is there better way? -
Django, Sentry, Slack: How to capture/display request and response in slack?
I am using django-1.10 and have configured sentry logger to capture any response status greater than 400. Sentry is hooked with slack channel. I am able to get culprit and project information but it does not contains what was the url, request and response. Want to Log request and response along with culprit and project information. My Logging config:- ` LOGGING = { .... 'handlers': { 'sentry': { 'level': 'ERROR', 'class': ('raven.contrib.django.raven_compat.handlers.' 'SentryHandler'), }, }, 'loggers': { 'sentry_errors': { 'level': 'ERROR', 'handlers': ['sentry'], 'propagate': False }, } } ` Code raising sentry alerts:- ` logger = logging.getLogger('sentry_errors') logger.error("Handled exception occurred", exc_info=True, extra={ "request": renderer_context['request'].data, "response": renderer_context['response'].data }) ` I am only receiving Culprit and Project information on slack. Is it possible to capture request and response on slack? -
Returning a dictionary with all dates between a start and an end date
I have a Calendar on one of my django views. I am trying to return a dictionary with a list of dates between a start and an end date. At the moment, I can only return a list of start dates or end dates. I need these along with all the days in between to be part of the dictionary. class HolidayCalendar(HTMLCalendar): def __init__(self, holiday): super(HolidayCalendar, self).__init__() self.holiday = self.holiday_days(holiday) #some formatting def holiday_days(self, holiday): field = lambda holiday: holiday.start_date.day # field = lambda holiday: holiday.end_date.day return dict( [(day, list(items)) for day, items in groupby(holiday, field)] ) This is the view that calls this: def holiday(request): #some code date_today = datetime.now() year = date_today.year month = date_today.month my_holidays = Holiday.objects.order_by('start_date').filter( Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month) ) cal = HolidayCalendar(my_holidays).formatmonth(year, month) #form stuff context = { "holidayform": holidayform, "calendar": mark_safe(cal), } return render(request, "tande/calendar.html", context) Thanks! -
Django admin add_view/ change_view for inline
In Django admin we can override the add_view and change_view functions from the ModelAdmin class like this.. class ProductAdmin(admin.ModelAdmin) def add_view(self, request, form_url='', extra_context=None): self.readonly_fields = (...) //other code return super(ProductAdmin, self).add_view(request, form_url='', extra_context=None) It's similar as above for change_view as well. However, this is not the case for the Inline model admin. Is there anyway we can replicate the same for inlines like below? Note, the below code doesn't work. I just want to be able to do something like it. class SubProdInLine(admin.TabularInLine) def add_view(self, request, form_url='', extra_context=None): self.readonly_fields = (...) //other code return super(SubProdInLine, self).add_view(request, form_url='', extra_context=None) Basically, I want to be able to change the readonly_fields in the add_view. -
Search within nested Django JSONField (either via Django ORM or raw sql)
Versions: Django==1.10.3 and Postgres 9.6 Is there a way to search within a nested Django JSONField (backed by Postgres jsonb) for a specific key/value state? Ideally this would be a native Django but I can break out into raw sql if necessary. e.g. search for one or more occurrences of {"status":"running} within the following data: {"subtask1": {"status":"running"}, "subtask2": {"status":"complete"}} Background: I'm using a JSONField to log the current status of long-running subtasks. Each subtask updates it's element of the json field selectively via a nativePostgres jsonb_set() operation on the server. After each subtask, I want to query the log field to see whether this subtask was the last to complete. If all are complete (ie no occurences for {"status":"running"} within the nested json tree) then I'll update the main .complete field for the Django RunningTask instance. Sample & simplified model: class LongRunningTask(models.model): id = models.AutoField(primary_key=True) complete = models.BooleanField(default=False) log = JSONField(null=True, blank=True, default=dict) Example data for log field: {"subtask1": {"status":"running"}, "subtask2": {"status":"complete"}} Thanks in advance for any pointers. -
getting result in short running celery task (Django)
What is the best way to implement getting result in short running celery task (3-7 seconds) ? For now i use this method below. User clicks button which send request to api - api triggers celery task and returns task_id Then we are checking result of task_id via Ajax -
django allauth empty username causes duplicate key in postgress DB
Django 1.8.16 django-allauth 0.27.0 Using postgres as database. My application does not use usernames, only e-mail addresses as user id. So I use following settings: ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USER_MODEL_EMAIL_FIELD = 'email' Now when a new user registers, he uses his e-mail address. But when submitting the registration form, I get this error: IntegrityError at /accounts/signup/ duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=() already exists. Request Method: POST Request URL: http://swd.localhost:8000/accounts/signup/ Django Version: 1.8.16 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=() already exists. This says exactly what is wrong: The empty username already exists in the auth_user table, field "username", and it seems this is not allowed? But problem is that the username field is ALWAYS empty using above settings. So how can we get around this? I did not adapt the user model. -
Can't upload image in django use MEDIA_ROOT
I was trying to upload a image but I have been searching in google but I can not find a solution. Anyone help me to find the error, I use django 1.10 and Linux. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/imagenes/') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) Models.py from django.db import models from apps.almacen.categoria.models import Categoria # Create your models here. class Articulo(models.Model): idarticulo = models.AutoField(primary_key=True) codigo= models.CharField(max_length=50) nombre= models.CharField(max_length=100) stock= models.IntegerField() descripcion=models.CharField(max_length=512) imagen=models.FileField(upload_to = 'articulos/',null=True,blank=True) estado=models.CharField(max_length=20) idcategoria= models.ForeignKey(Categoria,db_column='idcategoria',null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.nombre) forms.py from django import forms from apps.almacen.articulo.models import Articulo class ArticuloForm(forms.ModelForm): class Meta: model = Articulo fields = [ 'idarticulo', 'nombre', 'codigo', 'descripcion', 'idcategoria', 'stock', 'imagen', ] labels = { 'idarticulo':'Articulo', 'nombre':'Nombre', 'codigo':'Codigo', 'descripcion':'Descripción', 'idcategoria':'Categoria', 'stock':'Stock', 'imagen':'Imagen', } widgets = { 'nombre': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Digite el nombre'}), 'codigo': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Digite el código'}), 'idcategoria': forms.Select(attrs={'class':'form-control'}), 'stock': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Digite el stock'}), 'descripcion': forms.TextInput(attrs={'class':'form-control','placeholder':'Digite la Descripción'}), 'imagen': forms.FileInput(attrs={'class':'form-control'}), } Views.py class ArticuloCreate(CreateView): model= Articulo form_class= ArticuloForm template_name='almacen/articulo/articulo_form.html' success_url= reverse_lazy('almacen_art:articulo_listar') def post(self, request, *args, **kwargs): self.object = self.get_object form = self.form_class(request.POST) if form.is_valid(): articulos = form.save(commit=False) articulos.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form)) articulo.html <form method="post" enctype='multipart/form-data'> {% csrf_token %} <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="form-group"> <label for="image">Imagen</label> …