Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't identify which variable does not exist in VariableDoesNotExist error
My site works fine but my log.django file is showing a django.template.base.VariableDoesNotExist error and I can't identify which variable is not valid. Here's the full traceback: Traceback (most recent call last): File "/home/zorgan/app/env/lib/python3.5/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [lst] in "[{'None': None, 'True': True, 'False': False}, {'user_inbox': <QuerySet [<Inbox: Inbox object>]>, 'allauth_login': <LoginForm bound=False, valid=False, fields=(login;password;remember)>, 'request': <WSGIRequest: GET '/post/'>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fd0339c67f0>, 'user_settings': <UserSettings: UserSettings object>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fd033a1db70>,'user': <SimpleLazyObject: <User: zorgan>>, 'DEFAULT_MESSAGE_LEVELS': {'ERROR': 40, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'DEBUG': 10}, 'csrf_token': <SimpleLazyObject: 'bagt2zVjPiMiyi0ojTxTVbHHOBiIei7hqZQZ5sDITfzZ9khSbszkDCvcawQuHSxR'>, 'allauth_signup': <SignupForm bound=False, valid=False, fields=(username;email;password1;password2)>, 'inbox_status': 'read'}, {}, {'form_post': <PostForm bound=False, valid=False, fields=(title;content;entered_category;image;imageURL;user)>, 'via': 'news'}, {}, {'block': <Block Node: footer. Contents: [<TextNode: '\\n\\n'>, <IfNode>, <TextNode: '\\n\\n'>]>}]" Any idea? -
Heroku - Declare it as envvar or define a default value
I am trying to run my Heroku app locally and followed the instructions here: https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally When I tried to run the following command: python manage.py collectstatic i've got this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Python36-32\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Python36-32\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Python36-32\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python36-32\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\robina\Ubelt-Dorm\ph_dorms\settings.py", line 25, in <module> SECRET_KEY = config('SECRET_KEY') File "C:\Python36-32\lib\site-packages\decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "C:\Python36-32\lib\site-packages\decouple.py", line 85, in __call__ return self.get(*args, **kwargs) File "C:\Python36-32\lib\site-packages\decouple.py", line 70, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value. The SECRET_KEY has been declared as a Config … -
Django - Uploading and viewing file on page without saving it
I'm writing a view function that just needs to display an image uploaded by the user. I have a form which has the file selector and upload button that will submit the image. In the class definition for the form, there is a field that stores a reference to a model which I thought should be left blank since I'm not actually going to be storing the image in a database but when I try to run the server I get the following error: ValueError: ModelForm has no model class specified. What would be the correct way to display an image after it is uploaded without having to save it to a db? -
Expose the functionality of an installed app via REST
How can I expose the functionality of an installed app via REST in Django framework? -
Generate PDF from html template and send via Email in Django
I'm trying to generate a pdf file from an HTML template and I need to send it via email. Here's what i have tried: def send_pdf(request): minutes = int(request.user.tagging.count()) * 5 testhours = minutes / 60 hours = str(round(testhours, 3)) user_info = { "name": str(request.user.first_name + ' ' + request.user.last_name), "hours": str(hours), "taggedArticles": str(request.user.tagging.count()) } html = render_to_string('users/certificate_template.html', {'user': user_info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=certificate_{}'.format(user_info['name'] + '.pdf') pdf = weasyprint.HTML(string=html).write_pdf(response, ) from_email = 'our_business_email_address' to_emails = ['Reciever1', 'Reciever2'] subject = "Certificate from INC." message = 'Enjoy your certificate.' email = EmailMessage(subject, message, from_email, to_emails) email.attach("certificate.pdf", pdf, "application/pdf") email.send() return HttpResponse(response, content_type='application/pdf') But it returns an error as TypeError: expected bytes-like object, not HttpResponse How can I generate and send a pdf file to an email from HTML template? Help me, please! Thanks in advance! -
Dynamic, django rendering img tag Javascript/HTML
I am working on a multifaceted web project. I have ran into an issue that I don't know the answer to. I am running a Javascript function after an HTML page loads. I have a frame for images that I want to update with a timer. I am successfully able to run the timer, and I can even collect the latest source name for my img to be posting. But the images don't render. The views stays its default image: image1.png. I am loading this HTML through a django framework using templating. <article> <script type="text/javascript"> window.onload = startTimer(); function displayNextImage() { console.log("Next image should show") x = (x === images.length - 1) ? 0 : x + 1; document.getElementById("img").src = images[x]; console.log(document.getElementById("img").src) } function startTimer() { setInterval(displayNextImage, 3000); console.log("Timer started"); } var images = [], x = -1; images[0] = "../media/image1.png"; images[1] = "../media/image2.png"; images[2] = "../media/image3.png"; </script> <img src="{% static 'image1.png' %}" alt="Frame" id="img" /> </article> -
No module found error in Django when trying to run Celery workers
I have a python script in my Django app that creates a celery app, and attempts to send a simple task to my Redis broker to be processed. In the directory where the script is, I run the celery command celery -A tasks worker --loglevel=info The test works, the task is processed, and all is well in the world. When I attempt to import a model in that script, and rerun that same celery command, I get a Module not found error ModuleNotFoundError: No module named 'wikipedia' Not sure why it can't communicate with the rest of my Django applicaton. celery_redis_rabbit_tut / wikipedia / tasks.py from celery import Celery import time import bs4 from wikipedia.models import WikipediaPage app = Celery('tasks', broker='redis://localhost') @app.task() def grab_idle_pages(): print('X') grab_idle_pages.delay() Traceback Traceback (most recent call last): File "/Users/tim/Timothy/virt_envs/xena/bin/celery", line 11, in <module> sys.exit(main()) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/__main__.py", line 14, in main _main() File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", line 279, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline self.app = self.find_app(app) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", line 503, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/app/utils.py", line 355, in find_app sym = symbol_by_name(app, imp=imp) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", … -
Installing geodjango on Windows
I would like to use geodjango, but the error that I am getting when following the official installation guide is: File "c:\users\me\appdata\local\programs\python\python36-32\Lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 193] %1 is not a valid Win32 application I see that this error has been addressed here OSError: [WinError 193] %1 is not a valid Win32 application but I still don't know how to fix it in this case. Do I have to make some change to that line? -
django rest framework get() returned more than one object after using filter() method
In model.py, I've two models class student(models.Model): name = models.CharField(max_length=255) registration_number = models.CharField(max_length=255) session = models.CharField(max_length=255) college = models.ForeignKey(to='college', on_delete=models.CASCADE) class Meta: db_table = 'student' class semester(models.Model): semester = models.IntegerField() student = models.ForeignKey(to='student', on_delete=models.CASCADE) sgpa = models.FloatField() grade = models.CharField(max_length=255) is_fail = models.BooleanField(default=True) class Meta: db_table = 'semester' Serializer classes looks like class SemesterSerializer(serializers.ModelSerializer): class Meta: model = models.semester fields = ('id', 'semester', 'sgpa', 'grade', 'is_fail',) class StudentSerializer(serializers.ModelSerializer): class Meta: model = models.student fields = ('id', 'name', 'registration_number', 'college', 'session',) and views.py contains class SemesterViewSet(viewsets.ModelViewSet): def get_queryset(self): if 'semester' in self.kwargs: return models.semester.objects.filter(semester=self.kwargs['semester']) else: return models.semester.objects.all() lookup_field = 'semester' serializer_class = serializer.SemesterSerializer url patterns are router = DefaultRouter() router.register('semester', views.SemesterViewSet, base_name='semester') urlpatterns = [ url(r'', include(router.urls)), ] When I tried url/semester/8, MultipleObjectsReturned exception raised and showes get() returned more than one semester -- it returned 2! error message. Here I've not used any get() method. Why this is happening and what is solution? -
Django/Views executing two forms
I'm really having some trouble with this. I've got some custom user's setup and those users can be attached to companies via foreign key. I'm just having trouble saving them. I've tried a ton of different variations of getting the user attached to a company and I just can't crack it. The forms do work and it does both create a "customer" and a "customer company". I know this needs to be a variation of: if customer_form.is_valid() and customer_company_form.is_valid(): customer_company = customer_company_form.save() customer = customer_form.save(commit=False) customer.user = customer_company customer_company.save() models.py class CustomerCompany(models.Model): COUNTRIES = ( ('USA', 'United States'), ('CAN', 'Canada') ) name = models.CharField(max_length=100, blank=True, unique=True) website = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=10, blank=True) address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=255, blank=True) state = USStateField(blank=True, null=True) us_zipcode = USZipCodeField(blank=True, null=True) ca_province = models.CharField(max_length=50, blank=True, null=True) ca_postal_code = models.CharField(max_length=7, blank=True, null=True) country =models.CharField(max_length=3, choices=COUNTRIES, blank=True) def get_absolute_url(self): return reverse('accounts:customer_company_detail',kwargs={'pk':self.pk}) def __str__(self): return self.name class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='customer_profile') company = models.ForeignKey(CustomerCompany, on_delete=models.CASCADE, null=True) phone = models.CharField(max_length=10) def __str__(self): return self.user.first_name + ' ' + self.user.last_name forms.py class CustomerSignupForm(UserCreationForm): first_name = forms.CharField(max_length=50, required=True) last_name = forms.CharField(max_length=50, required=True) phone = forms.CharField(max_length=10, required=True) email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User … -
How get multiple BooleanFields in a form using Django
I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid. The field "who paid" is a table containing the name of all users and a checkbox. Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text). How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name? model.py from django.db import models #created_date attibute needs it from django.utils import timezone # This Model is a super class "Financial Transaction" class GroupTransaction(models.Model): name = models.CharField(max_length=257, default='') who_paid = models.CharField(max_length=257, default='') value = models.DecimalField(max_digits=6, decimal_places=2) justification = models.CharField(max_length=257, default='') created_date = models.DateTimeField(default=timezone.now) date = models.CharField(max_length=257, default='') receipt = models.FileField(upload_to='comprovantes', blank=True, null=True) its_type = models.CharField(max_length=257, default='') def __str__(self): #INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant) return "%s - %s" % (self.name , self.who_paid) view.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from deposit.forms … -
Django admin: how can i make related modle show only after selecting primary model
class Company(models.Model): name = models.CharField(max_length=200, help_text="Enter Company name") class Product(models.Model): company = models.ForeignKey('Company', on_delete=models.SET_NULL, null=True) sku = models.CharField(max_length=200,null=True,blank=True,unique=True) class Inventory(models.Model): product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) quantity = models.PositiveIntegerField(null=True,default=0) Every product is owned by a Company, in my Add Inventory i have Product dropdown field but it only displays Product, how can I make the user first select the company then the product owned by that company displays? -
Django: How to use get_form() method in CreateView?
I have a CustomForm in my forms.py that needs the public key of the URL. I mean e.g. /book/<pk>/create. In my views.py there is this CreateView: class CustomCreateView(CreateView): form_class = CustomForm Now my question is how can I pass the public key of the URL to the CustomForm. The CustomForm expect a keyword argument named pk. I thing the get_form() method could help, but I am not sure and do not know how to use it: https://docs.djangoproject.com/en/2.0/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form -
If condition works not so as I expect it
On screenshot below you can see Im trying to save this model given one value for "RESULTAT 1 HZ" and empty value for "RESULTAT 1 HZ" on downside. In my my_callback Im doing some calculation but as you can see only if both of fields are not None. So, why I get error that shown on second screenshot? TypeError Exception Value: '>' not supported between instances of 'int' and 'NoneType' @receiver(pre_save, sender='tournament.GroupstageTournamentModel') def my_callback(sender, instance, *args, **kwargs): # Point for first half time if not (instance.team_1_first_halftime_score is None and instance.team_2_first_halftime_score is None): if instance.team_1_first_halftime_score > instance.team_2_first_halftime_score: instance.team_1_first_halftime_point = 2 Here is my Traceback http://dpaste.com/0DDP4QC -
Angular relationship of tables from many to many
I have a problem in angular i dont now how to call from the table to an object that has many to many relationship [ { "id": 2, "username": "test", "email": "test1@gmail.com", "groups": [ { "id": 2, "name": "Empleados", "permissions": [] } ] }, ] <tr *ngFor="let item of users;"> <td>{{item.id}}</td> <td>{{item.username}}</td> <td>{{item.email}}</td> <td>{{item.groups.name}}</td> <td> <a href="" class="btn btn-default">Leer</a> <a href="" class="btn btn-warning">Editar</a> <button class="delete" (click)="Eliminar(item)">Eliminar</button> </td> </tr> that does not work for me, it only works for me when the relationship is one to many try to do this, I only work the first column {{item.groups[0].name}} -
Django: Form validation based on public key/foreign key
I have an Event model and a Registration model (one event can have multiple registrations -> ForeignKey). At event/<pk>/register I want to present a Form where you can register for the certain event. So, I have to do Form validation in my forms.py. However, I need access to the public key of the URL. But I do not know how I get the public key? The other way would be to include the pk to the Form. Problem here is that when you surf at event/5/register the field for the event MUST be 5 and should not be editable. But I could not find a solution to initially set the Event in the Form for the Registration creation. Additionally, it must not be editable. I'm pretty sure that's quite a common problem. What is the solution? -
Django with PIL - '_io.BytesIO' object has no attribute 'name'
I'm using PIL to resize an uploaded photo before saving. Note that I'm using formsets to upload the pictures. I'm using BytesIO to open the file. At the last step, I get the error - '_io.BytesIO' object has no attribute 'name'. Why is this? def fsbo_create_listing(request): PhotoFormSet = formset_factory(OwnerListingPhotoForm, extra=15) if request.method == 'POST': form = OwnerListingForm(request.POST) photo_formset = PhotoFormSet(request.POST, request.FILES) if form.is_valid() and photo_formset.is_valid(): form.instance.user = request.user form.save() for i in photo_formset: if i.instance.pk and i.instance.photo == '': i.instance.delete() elif i.cleaned_data: temp = i.save(commit=False) temp.listing = form.instance temp.save() # Where the error happens def clean_photo(self): picture = self.cleaned_data.get('photo') # I had to import ImageFieldFile. If picture is already uploaded, picture would still be retrieved as ImageFieldFile. The following line checks the variable type of `picture` to determine whether the cleaning should proceed. if type(picture) != ImageFieldFile: image_field = self.cleaned_data.get('photo') image_file = BytesIO(image_field.read()) image = Image.open(image_file) image = ImageOps.fit(image, (512,512,), Image.ANTIALIAS) image_file = BytesIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file #if picture._size > 2*1024*1024: #raise ValidationError("Image file too large. Max size is 2MB.") return picture class OwnerListingPhoto(models.Model): listing = models.ForeignKey(OwnerListing, on_delete=models.CASCADE, related_name='owner_listing_photo') photo = models.ImageField(upload_to=owner_listing_folder_name) -
Show the data points in tabular format in Html from Django
My goal is to print the data points of the DataFrame in Django to Html page, along with the index values. My views.py def view_data(request): data_cols = list(data.columns.values) # to retrieve the column names context_data_sample = { 'data': data_, #data_ contains the data in DataFrame 'columns': data_cols #contains the columns of the data frame } return render(request, 'polls/home.html', context_data_sample) HTML code {% for i in data %} <tr> <td>{{ i.columns }}</td> </tr> {% endfor %} Although I mentioned above that I would like to print with the index values I am stuck with projecting just the name of the variable and nothing else, for instance, if I have Passenger column it is showing the Passenger and nothing else. Could anyone help me in projecting my dataset with the index values for respective rows? Thanks in advance. -
Django ORM: Group by and SQL Agregation
I know that exists any same topics there, but that are not described my situation :( I have a model below: class SecurityPrice (models.Model): security = models.ForeignKey(Security, on_delete = models.CASCADE) created = models.DateTimeField() price = models.FloatField() class Meta: ordering = ('-created',) def __unicode__(self): return u'%s - %s - %s' % (self.created, self.security.ticker, self.price) or in sqlite: CREATE TABLE IF NOT EXISTS "restful_api_securityprice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "price" real NOT NULL, "security_id" integer NOT NULL REFERENCES "restful_api_security" ("id")); And I want to select last prices for each security paper In raw SQL I may do it with such SQL-request: SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id; Below Some Examples for understand my needs: All records from table sqlite> SELECT * FROM restful_api_securityprice; 1|2018-01-07 23:13:02|920.0|1 2|2018-01-07 23:13:43|137.12|2 3|2018-01-07 23:13:58|147.3|3 4|2018-01-09 00:46:29|920.0|1 5|2018-01-09 00:47:27|137.12|2 6|2018-01-09 00:48:08|147.3|3 A what I to need sqlite> SELECT MAX(created), security_id, price as created FROM restful_api_securityprice GROUP BY security_id; 2018-01-09 00:46:29|1|920.0 2018-01-09 00:47:27|2|137.12 2018-01-09 00:48:08|3|147.3 In raw SQL it's ok. But how I can do the same in Django ORM API without include raw sql? -
Django Foreign key that could contain objects of different classes
is there a way to be able to use a foreign key to reference objects of diffrent classes for example, this is what i'm doing : Class discussion(models.Model): id_discussion = models.CharField(db_column='id_Discussion', primary_key=True, max_length=100) id_worker = models.ForeignKey('Worker', models.CASCADE, db_column='id_user', blank=True, null=True) id_director = models.ForeignKey('Director', models.CASCADE, db_column='id_user', blank=True, null=True) Class Message(models.Model): #some other fields id_sender = models.CharField(db_column='id_Sender', max_length=100, blank=True, null=True) id_receiver = models.CharField(db_column='id_Receiver', max_length=100, blank=True, null=True) id_discussion = models.ForeignKey('discussion', models.CASCADE, db_column='id_Discussion', blank=True, null=True) I want to turn id_receiver and id_sender into foreign keys, my problem is that the sender could be an object of class "Worker" or of class "Director". -
Data from 1:n relation in Django into a flat file
I've spent quite some time googling, but none of the findings seem to fit my situation. I am ramping up a little data warehouse where I store all Facebook Posts of my pages and I do performance snapshots (impressions, clicks, shares, comments...) of every post every 20 minutes for the first week, so that I can build some prediction models for fresh posts in a later project on this dataset. This means that there is a 1:n relation between Post and Performance-Snapshot and every post has around 500 performance snapshots. For a start I just have to create a CSV-API for an external visualisation tool, so I need a flat file format for every post in a given time range together with it's final (i.e. latest) performance snapshot in the same line. And the problem is that I can't find a way to build the list of all posts and their latest performance snapshot in a single shot as I can do with JOINS in direct SQL. My slightly simplified models: class FBPost(models.Model): post_id = models.CharField(max_length=64, unique=True) type = models.CharField(max_length=32) message = models.TextField() description = models.TextField() created_time = models.DateTimeField() permalink_url = models.TextField(blank=True) class Meta: get_latest_by = 'created_time' class FBPostPerformance(models.Model): post_id … -
null=True,blank=True but still error may not be null is raised everytime during post
my model: Assets(modes.Model): assset_code=models.CharField(max_length=12,null=True,blank=True) In my serializers.py: asset_code=serializers.CharField(max_length=12,allow_blank=True,required=False) When I post data, it still says this field may not be null. It lets me pass only if I put data. While I am at it, whats the correct way to make JSONField() optional in serializers too? -
How does Django handle multiple requests?
How does Django handles multiple requests in production environment? Suppose we have one of web server: Apache, Nginx, gunicorn etc. So do those servers for any request from web browser start new process to serve that request? If it's true, doesn't it cause huge overhead? If it's not true, then how the same view (let it be def hello(request) view bound to /hello url) serve several requests at the same time. I've seen answers for question "... handle multiple users" -
How to match any url using path() method django
I have a project called gigi and app called account. Inside gigi/urls.py i have the following code urlpatterns = [ path('account/',include('account.urls')), ] Inside account/urls.py urlpatterns = [ path('', views.dashboard, name="dashboard"), ] I want to include authentication urls from django.contrib.auth.urls using include('django.contrib.auth.urls')) How can i include it so that any url that doesn't match '' inside account.urls be get looked up inside auth urls -
Django Attribute Error: Type Object has no attribute 'all'
I am running into this error at my Django 2.0.2 (Python 3.6.4) project: AttributeError at /upload/ type object 'Tag' has no attribute 'all' The idea is to have tasks and to add one or more tags to each task. The task models reference to the tag class is tags = models.ManyToManyField(Tag, blank=True) and works fine in the admin interface. Now when I call my upload form the error above shows up. Here is the upload form class UploadForm(forms.Form): title= forms.CharField(label='Tasktitle', max_length=255) data= forms.FileField(label='Data') tags = forms.ModelMultipleChoiceField(Tag) The upload view is def upload(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): newTask = Task(titel=request.POST['title'], tags=request.POST['tags'], data=request.FILES['data']) newTask.save() return HttpResponseRedirect('success/') else: form = UploadForm() return render(request, 'upload/upload.html', {'form': form}) I tied to adjust the different parameters, but I can't figure out where the call for an 'all' attribute comes from. If you need more information or clarification just add a comment. Thank you very much.