Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to render a file upload template
I have a python django based server that a client can access through a javascript plugin. The plugin allows the server to collect user's login information of another platform and connect to that platform on his behalf. To access our server, the plugin initiate the following instruction: chrome.tabs.create({ url: targetURL + '?random_code=' + username + '&token=' + token }) where target url contain our IP and two functions in defined in views.py (function 'A' and 'B') targetURL =IP+'/A//B/'. When receiving the request, the server collects the login information through A and returns a response containing the username. Function B then redirects the user to another view (C) rendering some processing results. I would like to insert a file upload page where users will upload a txt file that the server will then process before function B is executed. I have tried to link view A to a template containing the file upload html code however at every execution the file upload page doesn't display and users directly get the result of C. I also tried to remove B (from the plugin as well) and directly return C from A if request.FILES is defined or return the file upload html page … -
NOT NULL constraint failed: app_business.user_id
I am rendering a form and when I am submitting that form getting this error IntegrityError at /business/ NOT NULL constraint failed: app_business.user_id models.py class business(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=400) rate_it = models.BooleanField(default=False) availibility = models.BooleanField(default=True) def __str__(self): return self.name forms.py class businessform(forms.ModelForm): class Meta: model = business fields = ['name', 'rate_it', 'availibility'] views.py def formview(request): if request.method == 'POST': form = businessform(request.POST) if form.is_valid(): form.save() return HttpResponse('saved') else: form = businessform return render(request, 'business.html', {'form':form}) I don't know why this error is coming. -
Django model missing inherited fields from base class
I have made some models in my Django app to describe different types of polls that exist in my application. from django.db import models from api.models.helpers import JSONSerializableModel from api.models.speaker import Speaker from api.models.auth import Attendee from api.models.event import Event class BasePoll(JSONSerializableModel, models.Model): text = models.CharField('текст опроса', max_length=300, blank=False) class Meta: abstract = True class MultipleChoicePoll(JSONSerializableModel, models.Model): @property def results(self): results = multiplechoicepollresponse_set.all().annotate(Count('multiplechoicepollresponse')) return average_rating class RatingPoll(BasePoll): @property def average(self): average_rating = ratingpollresponse_set.all().aggregate(Avg('rating')) print(average_rating) return average_rating class OpenQuestionPoll(BasePoll): pass I've made the migration and all seemed fine, but now when I try to use the interactive shell: In [6]: poll = MultipleChoicePoll.objects.all()[0] In [7]: poll.text = 'Some poll text' In [8]: poll.save() In [9]: poll = MultipleChoicePoll.objects.all()[0] In [10]: poll.text --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-10-28f6dbcd48ba> in <module>() ----> 1 poll.text AttributeError: 'MultipleChoicePoll' object has no attribute 'text' poll seems to be missing all the fields I have created for it. Is it because I have inheritted those fields? -
Return file using HttpResponse
Good afternoon. I need to download data from database in excel format. Below, my code and its working correct when i'm trying to download file through firefox, but using chrome this view returning archive with some openpyxl files. Openpyxl - this library i'm using to filling excel table from database in excel_download() function. Will you please help me to solve it? def excel_download_view(request, **kwargs): if 'sorting_argument' in kwargs: queryset = Lot.objects.filter( Q(bank__slug__iexact=kwargs['sorting_argument']) | Q(auction_date__iexact=kwargs['sorting_argument']) | Q(which_time_auction__iexact=kwargs['sorting_argument']) | Q(fgvfo_number__iexact=kwargs['sorting_argument']) | Q(prozorro_number__iexact=kwargs['sorting_argument']) | Q(decision_number__iexact=kwargs['sorting_argument']) ) else: queryset = Lot.objects.all() excel_download(queryset) data = None with open('media/excel/lots.xlsx', 'rb') as f: data = f.read() return HttpResponse(data, content_type='application/vnd.ms-excel') -
is there a way to return a response first but still does something else after the response? django
I want to return a response in django view first then does something after the response. Let's say I have something like this as example..... class Res(View): def post(self, request): data = request.POST new_obj = Model.objects.create(name=data.['name']) # what is below does not have to be done RIGHT AWAY, can be done after a response is made another_obj = Another() another_obj.name = new_obj.name another_obj.field = new_obj.field another_obj.save() # some other looping and a few other new models to save return JsonResponse({'status': True}) So I am wondering if there is a chance to return the response first? What's above is an example of what I mean. I am not sure if this can be done in django, if possible, can someone let me know who this can be done Thanks in advance. -
Get details of users those who rate the business
I have three columns named as business name , rate it, .com availability in a table. I want details of those users who hit the rate it button. models.py file class VNN: def set_params(self, W_x_h, W_h_h, W_h_y, b_h, b_y, h_prev, ch_2_ix, ix_2_ch): self.W_x_h = W_x_h self.W_h_h = W_h_h self.W_h_y = W_h_y self.b_h = b_h self.b_y = b_y self.h = h_prev self.ch_2_ix = ch_2_ix self.ix_2_ch = ix_2_ch self.vocab_size = len(ch_2_ix) self.words=[] def sample(self, seed_ix, n, _temperature=1): """ sample a sequence of integers from the model h is memory state, seed_ix is seed letter for first time step """ h = self.h x = np.zeros((self.vocab_size, 1)) x[seed_ix] = 1 ixes = [] for t in range(n): h = np.tanh(np.dot(self.W_x_h, x) + np.dot(self.W_h_h, h) + self.b_h) y = np.dot(self.W_h_y, h) + self.b_y p = np.exp(y / _temperature) / np.sum(np.exp(y / _temperature)) ix = np.random.choice(range(self.vocab_size), p=p.ravel()) x = np.zeros((self.vocab_size, 1)) x[ix] = 1 ixes.append(ix) return ixes def unique_words(self, seedword, seed_ix, n, _temperature=1): out_words = [] ch_batch_size = 100 while len(out_words) < n: sample_ix = self.sample(seed_ix, ch_batch_size, _temperature) txt = ''.join(self.ix_2_ch[ix] for ix in sample_ix) raw_words = txt.split('\n') for word in raw_words: if not (word in self.words) and not (word in out_words): out_words.append(seedword+word) return out_words … -
Why does Django give me an invalid filter error when I try to apply two filters?
I want to make two changes to the text that is displayed in my Django template. First, I want to strip the text of any HTML. The following code works for me: {{ article.abstract|striptags }} Second, I want to replace all instances of \n with <br /> I tried: {{ article.abstract|striptags|replace('\n', '<br />') }} That gave me an invalid filter error. I even tried: {{ article.abstract|striptags|replace('\n', '') }} That did not work either. Are there any suggestions? Thank you. -
NoReverseMatch at /accounts/detail
I got an error,NoReverseMatch at /accounts/detail Reverse for 'upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'accounts/upload/(?P\d+)/$'] . I wrote in detail.html like <body> <a href="{% url 'accounts:upload' %}"><img src="{% static 'accounts/Send.jpg' %}" alt="SEND"></a> </body> My ideal system is when I click images, it sends to upload method(maybe I should say photo.html). I wrote in views.py like def detail(request): return render(request, 'registration/accounts/detail.html') def upload(request, p_id): form = UserImageForm(request.POST or None) d = { 'p_id': p_id, 'form':form, } return render(request, 'registration/accounts/photo.html', d) in urls.py urlpatterns = [ url(r'^detail$', views.detail,name='detail'), url(r'^photo/$', views.photo, name='photo'), url(r'^upload/(?P<p_id>\d+)/$', views.upload, name='upload'), ] When I access http://localhost:8000/accounts/detail, these error happens.How can I fix this?What should I write it? -
Datafile not found, datafile generation failed in confusable_homoglyphs/categories.py
I'm setting up a django project on an apache server. It is running fine on my PC under using manage.py runsslserver. When I load onto the apache server I can run manage.py migrate and collectstatic and a number of setup programs. BUT when I try to enter the webpage I get error message "Datafile not found, datafile generation failed" with this traceback: Environment: Request Method: GET Request URL: https://ekim.hexiawebservices.co.uk/ Django Version: 1.11.5 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'registration', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'djangosecure', 'sslserver', 'ekim'] 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 "/var/www/ekim/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/var/www/ekim/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "/var/www/ekim/env/lib/python2.7/site-packages/django/urls/resolvers.py" in resolve 362. for pattern in self.url_patterns: File "/var/www/ekim/env/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/var/www/ekim/env/lib/python2.7/site-packages/django/urls/resolvers.py" in url_patterns 405. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/var/www/ekim/env/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/var/www/ekim/env/lib/python2.7/site-packages/django/urls/resolvers.py" in urlconf_module 398. return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/var/www/ekim/ekim/urls.py" in <module> 30. url(r'^accounts/', include('registration.backends.hmac.urls')), File "/var/www/ekim/env/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include 50. urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/var/www/ekim/env/lib/python2.7/site-packages/registration/backends/hmac/urls.py" in <module> 10. from . import views File "/var/www/ekim/env/lib/python2.7/site-packages/registration/backends/hmac/views.py" in <module> … -
Apache config for Django
Django / MySQL / Apache2 - everything up-to-date (as far as I can tell) and there is Django data in the correct db/table I'm struggling to get my Django stuff to appear on my webbrowser. If I use python3 manage.py runserver 192.168.0.10:8000, I can see the Django install and admin page, but I'd like to see it without specifying a port number, and I'm aware that using runserver is the development side, rather than deployment. Also worth noting that I have NOT used any form of VirtualEnv as this is a dedicate Pi/Project, and I was getting confused with the libraries, local python install, virtual python install etc. Trying to narrow things down, I think I've got one of three problems. 1 - Apache isn't configured correctly 2 - Permissions/ownership issue of MySQL (e.g. apache not reading from table) 3 - Permissions/ownership issue of dir's (e.g. /var/www) I posted a similar question not too long ago, I've revisited that and the links that came with it, but it's not helped. I did have PHP and a VirtualEnv installed that time, and this is a fresh installation without either. I'm looking to have php install to have a bit of a … -
Heroku warning:django.request:not found: /
apologies i need some help. cant find a solution after 3 full days. i'm having this error shown on heroku- warning:django.request:not found: / i suppose this relates to static files and have done the below: a) heroku run ls -l project/ enter image description here --> the static folder here contains css, js, img, vendor files. As static folder appears in heroku, this looks correct? b) heroku run python manage.py collectstatic --dry-run --noinput --> 0 static files copied to '/app/static', 1115 unmodified. I think something could be wrong here? c) followed all deployment steps in django, django cms, aldryn and heroku. Hence I think settings, wsgi should be correct. The guides have been pretty silent on urls.py so I suspect my errors could be: a) potential error 1? urlpatterns = [ url(r'^tools/$',views.tickervalu, name='tools'), url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^admin/', admin.site.urls), url(r'^', include('cms.urls')), ] if settings.DEBUG: urlpatterns += [ url(r'^static/(?P<path>.*)$', serve,) ] b) potential error 2? BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'aldryn_boilerplates.staticfile_finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Thanking you in advance. Please let me know if more information is needed, really appreciate it. -
ValueError: Related model u'app.model' cannot be resolved when running tests
I have a doubt, so I am asking here for some help. Thanks in advance. I am trying to run some tests on a Django project (Django version 1.11.4) using Python 3.5.0. I have 2 applications inside my project: uploads and testgen. Those are my models: (Here there are only the special fields, like the relationships fields. The rest of the fields are CharField, PositiveIntegerField and BooleanField mainly.) uploads\models.py (a simplified version) class Document(models.Model): (any relationship fields) class Word(models.Model): synonyms = models.ManyToManyField("self") antonyms = models.ManyToManyField("self") class Sentence(models.Model): words = models.ManyToManyField(Word) class Paragraph(models.Model): sentences = models.ManyToManyField(Sentence) class Text(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) paragraphs = models.ManyToManyField(Paragraph) testgen\models.py (a simplified version) class Issue(models.Model): content = models.OneToOneField(Sentence, related_name="issue_content", null=True) question = models.OneToOneField(Sentence, null=True) class FillableIssue(Issue): replaceable_words = models.ManyToManyField(Word) class StatementIssue(Issue): replaceable_words = models.ManyToManyField(Word) class AppTest(models.Model): text = models.ForeignKey(Text, null=True) fillable_issues = models.ManyToManyField(FillableIssue) statement_issues = models.ManyToManyField(StatementIssue) testgen\tests.py from django.test import TestCase from testgen.models import AppTest class AppTestTestCase(TestCase): def test_apptest_has_positive_number_issues(self): """ has_positive_number_issues() returns True if the test's number issues is greater than zero. """ app_tests = AppTest.objects.get_queryset().all() for app_test in app_tests: self.assertIs(app_test.has_positive_number_issues(), True) project settings file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploads', 'testgen', ] Note: I use the uploads models inside the … -
HTML not rendering arabic [on hold]
I have a website where I want to display a dropdown. The values can be a mixture of english and arabic. My application is in django-python. I have a unicode : u'GO \u062a\u0631\u0641\u064a\u0647' I want to render it on UI as arabic but, If I send it to html as is, I get Uncaught SyntaxError: Unexpected string If i do encode('utf-8') it gets translated to some garbage. What should I do? Note: I have # -- coding: utf-8 -- at the top of my view. I have <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> at the top of my html . What am I missing? -
MultiValueDictKeyError at /accounts/upload_save/ "'image'"
I got an error,MultiValueDictKeyError at /accounts/upload_save/ "'image'". I wrote in views.py @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) in index.html <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> in forms.py class UserImageForm(forms.ModelForm): class Meta: model = ImageAndUser fields = ('image',) in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images', null=True, blank=True,) Traceback is Traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/XXX/Downloads/xxx/accounts/views.py" in upload_save 85. data.image = request.FILES['image'] File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/datastructures.py" in getitem 85. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /accounts/upload_save/ Exception Value: "'image'" My ideal system is image& user's data put in ImageAndUser model.Once I wrote in … -
Jumping from Django and basic JS directly into React Native?
For the last months I have this very interesting project of trying to learn how to build an app. I've spent some time on Django and Python and I plan on increasing my knowledge further. Using Django as a backend solution leaves open the question of the technologies to actually built the app. There are web based solutions (Phonegap etc.). But I am very interested in React native. So my question is - can I jump right into React native without knowing ReactJS before? And also I am really interested in the experiences you guys have with Django and React native? Is it a good fit? Thank you. -
Django: Get nearest object in future or past
How can you achieve this with one query: upcoming_events = Event.objects.order_by('date').filter(date__gte=today) try: return upcoming_events[0] except IndexError: return Event.objects.all().order_by('-date')[0] My idea is to do something like this: Event.objects.filter(Q(date__gte=today) | Q(date is max date))[0] But I don't know how to implement the max date. Maybe I've just to do it with Func. Or When or Case in django.db.expressions might be helpful. -
Can't implement partial update in Django REST Framework
I'm trying to implement partial update through PATCH requests on my Profile model. This is my class: class ProfilePartialUpdateView(viewsets.ModelViewSet): serializer_class = ProfileSerializer def partial_update(self, request, username): user = User.objects.get(username=username) serializer = ProfileSerializer(user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) However, when I send in the request, this is the response I get: NotImplementedError at /profile/update/new7/ update() must be implemented How should I implement it? -
DJango Attribute error : object 'A' has not attribute 'B' objects
model.py from __future__ import unicode_literals from django.db import models # Create your models here. class apartmentModel(models.Model): zone = models.ForeignKey('homepage.Zone',default='') siz_Of_house = models.IntegerField() rent = models.IntegerField() contact_number = models.CharField(max_length=14) details = models.TextField(max_length=120) parking_space =models.BooleanField() def __str__(self): a = str(self.siz_Of_house) b = str(self.zone); return a + " sq. feet apartment at " + b view.py from django.shortcuts import render from django.http import HttpResponse from apartment.models import apartmentModel as ap # Create your views here. def apartmentView(request): # template = loader.get_template('apartment/index.html') add_list = ap.obejcts.all() print(add_list) dict ={'ads':add_list} return render(request,'apartment/apartment2.html',None) I am new to django .While trying to load the apartment2.html i get 'Attribute error'like this : Exception Value: type object 'apartmentModel' has no attribute 'obejcts' I have checked few other related questions on the site .But i those were not enough. Thanks in advance . -
Django - how to save json posted data to REST API
I have the following json posted to localhost/api/user_add { "username":"test", "first_name":"First", "last_name":"Last", "address": { "street":"street", "town":"town" }, } The address need to be saved into the mysql table named address while the user info is saved into the table users with a column named address_id. I was able to write a simple model/serializer in order to be able to save username/first_name/last_name into the database, but i don't know how to save the address. I am using the django-rest-framework -
Incorrect view Django
I have a GET part of the view: def get(self, request, event_id, *args, **kwargs): form = self.form_class(initial={}) evnt = Event.objects.get(id=event_id) cmnt = Comments_events.objects.filter(event_cmnt_id=event_id) ANSWR = HOW TO GET? return render(request, self.template_name, {'event': evnt, 'comments': cmnt, 'answers': ANSWR, 'form': form}) Two models: class Comments_events(models.Model): ... class Answers(models.Model): ... comment_answr = models.ForeignKey('Comments_events') ... On the page I post a post, a comment to it, and I want to display the answers to the comments. Tell me how to correctly make GET "answr" in a view to display it in html? -
How to use a view to process different template in django
I would love to this in my project if it ever possible. I have a view like this class TrackUploadView(base.View): template_name = "track/uploadtrack.html" form_class = forms.TrackUploadForm trackdata = ['title', 'artist', 'genre', 'album', 'image', 'date'] def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) template_name = 'track/edittrack.html' form_edit = forms.TrackEditForm() datas = {} if form.is_valid(): audio_file = request.FILES['audio_file'] metadata = mutagen.File(audio_file, easy=True) audio = models.Track(audio_file=audio_file) audio.save() for field in self.trackdata: if metadata and metadata.get(field): data[field] = metadata.get(field) return render(request, template_name, {'form':form_edit,'data':data, ) return render(request, self.template_name, {'form':form}) on request==POST, I want it render another template for editing trackdata and another view will taking control of saving the data. Error i got! on submitting the data i got page not found! -
Jquery hide and django form widget
I'm using some jQuery code to hide and show a select in a form base on some circumstances. Everything it's fine, but I would like start the widget as hidden when the form is loaded the first time. The jQuery hide/show manipulate the style of the select. When is hidden: `display: hidden;' when is shown: 'display:block;'. Is there a way to change the attrs on the Django widget to add the `style="display: hidden;"? In the init of my form: self.fields['state'].widget.attrs.update({..}) Is possible to set the style using the attrs? -
Specifying quantity in django models OneToMany
I've been searching across the interwebs and can't seem to find a way to specify a quantity with django models ForeignKey field. For example, I want to create an apartment model and only want 4 tenant models to be associated with the apartment model. class apartmen(...): ... class tenant(...): tenants = ForeingKey(apartment, limit_choices_to ={(Only allow 4 per apartment model)} Any help is greatly appreciated. -
What is the best way to import a small sized MySQL Database to Django?
Schematics Image I have created a simple 5 table SQL Database for my family company. It consists of tables: Companies, CompanyDetails, Contacts, Continents, Products. I am focusing on making a frontend interface for displaying the Companies using drop-down menus for Type, Category, Country and/or Continent. Since, I already learned a bit of Python, I decided to use the Django framework to get it done. Now, I realize that importing a legacy DB using inspectDB is a non-trivial exercise in Django. Would it be a better/easier approach to just create a fresh model in Django and import csv s obtained from the database into it as there are only 5 tables in the first place? If yes, how do I do this in Django? -
ModelForm has no model class specified How can I connect model&form?
I got an error,ValueError at /accounts/upload_save/ ModelForm has no model class specified. I wrote in forms.py class UserImageForm(forms.ModelForm): owner = forms.CharField(max_length=20) image = forms.FileField() in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") image = models.ImageField(upload_to='images', null=True, blank=True,) in views.py @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = UserImageForm() data.owner = forms.cleaned_data['user'] data.image = request.FILES['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/accounts/photo.html', {'form': form}) in index.html <form action="{% url 'accounts:upload_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn"> <span class="btn btn-primary btn-lg"> <input type="file" style="display:none" name="files[]" multiple> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </form> When I put SEND button, upload_save method is read.And my ideal system is image& user's data put in ImageAndUser model.What is wrong in my codes?How can I connect model&form?