Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User form has fields with unwanted initial value, Django
I'm trying to create a view to allow a User to create another User. The problem is that the generated form has initial values for the 'password' and 'last_name' fields, and I don't know why. I need to remove those initial values. I have created a UserForm with ModelForm. class UserForm(forms.ModelForm): # I've tried this, but it doesn't change anything #def __init__(self, *args, **kwargs): #super(UserForm, self).__init__(*args, **kwargs) #self.fields['password'].value = '' #self.fields['last_name'].value = '' password = forms.CharField(widget=forms.PasswordInput(render_value=True)) class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name' ] Then I have the view. I have coded the view following the same pattern for creating views for other objects. After having this problem, I wrote the view down to this: def create_user(request): user_form = UserForm() context = { "user_form": user_form, } return render(request, "remote/user/user_create_form.html", context) I was hoping that if I only tried to display the form, and not treat the form data, this problem would not appear, but it does. My template has this (I'm using crispy forms): <form action="" method="POST">{% csrf_token %} {{ user_form|crispy }} <input type="submit" class="btn btn-primary" value="Registar" /> </form> Here is what the form looks like initially: password and last_name fields have initial values -
Replace "tzinfo" and print with localtime amends six minutes
I am creating a DataTimeField no time zone. Soon I am editing this TZ "manually" and then asking to read the value with local TZ. See the end result amends six minutes! Logic: >>> import datetime >>> from django.utils import timezone >>> test = datetime.datetime(2016, 9, 28, 10, 10, 10) datetime.datetime(2016, 9, 28, 10, 10, 10) >>> test = teste.replace(tzinfo=pytz.timezone('America/Sao_Paulo')) datetime.datetime(2016, 9, 28, 10, 10, 10, tzinfo=<DstTzInfo 'America/Sao_Paulo' LMT-1 day, 20:54:00 STD>) >>> timezone.activate(pytz.timezone('America/Sao_Paulo')) >>> timezone.localtime(test) datetime.datetime(2016, 9, 28, 10, 16, 10, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRT-1 day, 21:00:00 STD>) NOTE: The idea is that this happens in two stages. First I want to keep on the bench with the TimeZone creation. Then I want to show to the user with the user's TimeZone. In this case both users was the same region. sorry my English -
Django Template Loader not reaching app template
According to Django documentation "Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS." My Mezzanine settings.py has this configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My directory structure is project app_name templates app_name index.html But the template loader stops at project app_name templates As such my app_name template index.html is not reached. What can be the problem? -
Django admin do not show search term in changelist url
I have modified the get_search_results method of django admin changelist to use custom search method. def get_search_results(self, request, queryset, search_term): """ Returns a tuple containing a queryset to implement the search, and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name use_distinct = False if search_term: sites = get_sites_from_text(search_term) search_fields = self.get_search_fields(request) if len(sites) > 0: queryset = queryset.filter(site_name__in=sites) elif search_fields: orm_lookups = [construct_search(str(search_field)) for search_field in search_fields] for bit in search_term.split(): or_queries = [models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups] queryset = queryset.filter( reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.opts, search_spec): use_distinct = True break return queryset, use_distinct I am using text string as input to the search, so I don't want the search term to appear in the url. How can I remove the search term from the changelist url ? -
python/django MagicMock return return value not behaving like I expect
I havr this try/except loop in a model method that I am trying to write tests for... try: wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:%s-%s.ogg" \ % (self.language.wiktionary_prefix, url_sub_path, self.name) wiktionary_page = urllib2.urlopen(wiktionary_url) wiktionary_page = fromstring(wiktionary_page.read()) file_url = wiktionary_page.xpath( "//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0] file_number = self.get_num( self.definition_set.all()[0].search_existing_audio()) print file_number + " file num" relative_path = '%s/%s%s.ogg' % (path, self.name, file_number) full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path) popen("wget -q -O %s 'http:%s'" % (full_path, file_url)) made = self.definition_set.all()[0].convert_to_mp3(full_path) except Exception as exc: print str(exc) return False and I am trying to write a test for it while mocking some of the function in it. @patch("lang_api.models.urllib2.urlopen") @patch("lang_api.models.fromstring") @patch("lang_api.models.Definition.convert_to_mp3") @patch("lang_api.models.os.popen") def test_get_wiktionary_audio(self, popen, convert_to_mp3, fromstring, urlopen): # I need to mock another function in the actual method fromstring.return_value = MagicMock(return_value='string') test = self.things.model['word'].get_wiktionary_audio('en') popen.assert_called() convert_to_mp3.assert_called() when I try something similar in the python intepreter it works perfectly. but when this test runs it outputs this error. sh: -c: line 0: syntax error near unexpected token `(' sh: -c: line 0: `wget -q -O /Users/Jeff/Development/langalang/langalang/../media/study_audio/eng/words/table1.ogg 'http:<MagicMock name='fromstring().xpath().__getitem__()' id='4361699216'>'' so my return value statements are not being read properly but I cannot see what is happening. -
Initial value in the form's init() for model with generic relation
I have a model with generic relation like this: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') To make the life easier for the user I have modified the form. The idea was to have one field with choices instead of multiple. For that I have merged fields into choices inside of form's init(). def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(AdminTaskForm, self).__init__(*args, **kwargs) # combine object_type and object_id into a single 'generic_obj' field # getall the objects that we want the user to be able to choose from available_objects = list(Event.objects.all()) available_objects += list(Contest.objects.all()) # now create our list of choices for the <select> field object_choices = [] for obj in available_objects: type_id = ContentType.objects.get_for_model(obj.__class__).id obj_id = obj.id form_value = "type:%s-id:%s" % (type_id, obj_id) # e.g."type:12-id:3" display_text = str(obj) object_choices.append([form_value, display_text]) self.fields['content_object'].choices = object_choices Till now everything was working fine, but now I have to provide initial value for content_object field. I have added this code to init() but it is not working: initial = kwargs.get('initial') if initial: if initial['content_object']: object = initial['content_object'] object_id = object.id object_type = ContentType.objects.get_for_model(object).id form_value = "type:%s-id:%s" % (object_type, object_id) self.fields['content_object'].initial = form_value Any suggestions why I … -
ajax response to be filtered using user input
I am writting a Djagno application which consists of: template(html) js(jquery) views.py(python backend) UI has 2 drop down: On selecting 1st drop down, i get result from views.py which contains 2nd drop down value and other result. Now I am able to make ajax call and get result and update 2nd drop down on selecting 1st drop down. But question is I am not sure how I can accept value from 2nd drop down, and use that to filter on ajax response and render the output. 2nd drop down value and return response[2nd_drop_down] to html as table. Thanks in advance. Currently my Jquery code has: $(function(){ $("#1st_dropdown_id").change(function(){ //make_ajax_call() }) $("#2nd_dropdown_id").change(function(){ // how to access ajax response here }) }) function make_ajax_call(){ $.ajax({ type : "GET", url : "python_backend_file", contentType: 'application/json', data : { fleet: $('#fleet').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success : function(response) { //poplate 2nd drop down }, error : function(xhr,errmsg,err) { alert("fail") } }); } -
Django Allauth - New user type using default Signup form with other forms
I have created a seller app which allows sellers to apply for a seller account. I am using allauth signup form and 2 other custom forms for collecting information apart from username, email and password (collected by allauth signup form). The other info that I need has Seller Name, Mobile number etc. and also collects seller address. I have a class based form view created and these views captures Seller info and Adresss info but I do not know how to send the signup information to create the new (seller) via allauth. How can I create the user within seller account apply view? -
Django/Apache cannot import name multiarray (working in mange.py shell)
I have a django web app that utilizes pandas and numpy. when I run python manage.py shell and then import numpy I do not receive any errors. However when I try to run it through apache I receive the error. I have tried reinstalling the numpy and pandas with no luck. Below is my .conf file Include conf-available/serve-cgi-bin.conf WSGISCRIPTALIAS /site /home/ubuntu/site/initSite/wsgi.py WSGIDaemonProcess site_group threads=15 display-name=%{GROUP} python-path='/home/ubuntu/site:/home/ubuntu/site/envSite/lib/python3.4/site-packages' <Directory /home/ubuntu/site> <files wsgi.py> Require all granted </Files> </Directory> <Location /cal> WSGIProcessGroup site_group </Location> Alias /site1/ /home/ubuntu/site/fullSite/static <Directory /home/ubuntu/site/fullSite/static> Require all granted AllowOverride All </Directory> I know this has been asked before but I could not find another with a similar problem to mine. I can also import other packages correctly in apache. -
python django app settings log level
I am new to python and Django. My changes in app/settings.py are not picking up. I have changed the log level FROM: LOGGING = { 'version': 1, ... 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } TO LOGGING = { 'version': 1, ... 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/log/django/debug.log' } }, 'loggers': { 'django.request': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, } } but changes are not picking up as I don't see any activity on log despite actions on app. How could I tell Django that settings are updated and reload it? -
How to go through a ManyToMany field in chunks in Django
I am trying to display sets of three objects in a HTML template in a tiled interface. So, for example, an Album model has a ManyToMany field with specific photos. I want to iterate through the photos and show them in sets of three in the view. Currently, I can get all the photos using {{ for photo in album.images.all }} in the template, but don't know how to get the results in sets of three. How would I go about chunking the results into sets of three so that I can then iterate through the sets of three for the template? Or is there a way to get the total length and then index of specific elements using the Template tags? Thanks -
GenericForeignKeys in Intermediate Models
I'm attempting to create an intermediate model between 'auth.Group' and any other custom models; this will serve as permissions. I have been able to create an intermediate model between 'auth.Group' and one model. class Example(TimeStampable, Ownable, Model): groups = models.ManyToManyField('auth.Group', through='ExamplePermissions', related_name='examples') name = models.CharField(max_length=255) ... # Used for chaining/mixins objects = ExampleQuerySet.as_manager() def __str__(self): return self.name class ExamplePermissions(Model): example = models.ForeignKey(Example, related_name='group_details') group = models.ForeignKey('auth.Group', related_name='example_details') write_access = models.BooleanField(default=False) def __str__(self): return ("{0}'s Example {1}").format(str(self.group), str(self.example)) However, the issue is that this opposes reusability. To create a model that allows any custom model to be associated with it, I implemented a GenericForeignKey in place of a ForeignKey as follows: class Dumby(Model): groups = models.ManyToManyField('auth.Group', through='core.Permissions', related_name='dumbies') name = models.CharField(max_length=255) def __str__(self): return self.name class Permissions(Model): # Used to generically relate a model with the group model content_type = models.ForeignKey(ContentType, related_name='group_details') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # group = models.ForeignKey('auth.Group', related_name='content_details') write_access = models.BooleanField(default=False) def __str__(self): return ("{0}'s Content {1}".format(str(self.group), str(self.content_object))) Upon attempting to make migrations, it errors with: core.Permissions: (fields.E336) The model is used as an intermediate model by 'simulations.Dumby.groups', but it does not have a foreign key to 'Dumby' or 'Group'. At first glance, using a … -
using django-registration form instead of own
So I am using django-registration for email activation and the like. I defined my form and am calling to it properly however for some reason it is using the base form out of django-registration instead of my own. I have absolutely no clue as to why this is happening, any thoughts? views.py from django.shortcuts import render, render_to_response from django.http import HttpResponseRedirect from django.template.context_processors import csrf from django.contrib.auth.models import User from .forms import UserForm def register(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/accounts/register/complete') else: form = UserForm() token = {} token.update(csrf(request)) token['form'] = form return render('registration/registration_form.html', token) def registration_complete(request): return render('registration/registration_complete.html') urls.py from django.conf.urls import include, url from django.contrib import admin from main import views urlpatterns = [ # Registration URLs url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^accounts/register/$', views.register, name='register'), url(r'^accounts/register/complete/$', views.registration_complete, name='registration_complete'), url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^contact/$', views.contact, name='contact'), url(r'^login/$', views.login, name='login'), url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.profile, name='profile'), url(r'^blog/$', views.blog, name='blog'), forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.utils.translation import gettext as _ from registration.forms import RegistrationFormUniqueEmail, RegistrationForm class UserForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(label=_("Firstname"), required=False) last_name = forms.CharField(label=_("Lastname"), required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', … -
User database authentication in Django
I have created a basic CRUD web application with Django. Whenever an operation is performed on the database, it's the 'server'-user that's performing the operations, defined by settings.py file: default': { 'ENGINE': "sql_server.pyodbc", 'HOST': "MY-SERVER\SQL1", 'USER': "AppFrontEnd", 'PASSWORD': "MyPassword123", 'NAME': "TEST_DB_1" } Since I keep audit tables, I'd like to track where the changes are coming from and who is making them. We have a couple desktop applications that do this (Access) by using Windows passthrough authentication - but in Django I have to provide each specific users database login information. -
Django view function smart enough to know if client is mobile or web
I have API endpoints using Django view functions to communicate with an Angular front-end to create a web application. These view functions require a csrf token from incoming AJAX calls from Angular. I was curious what I would do if the request for my API endpoints were coming from a mobile application, where there is no csrf token ? I am not very knowledgable of mobile applications, so this is something completely new to me. Is there a way that I can tell my Django view function to ignore a csrf token if the request is coming from a mobile client ? Is that even possible for a Django view function to know the difference between a web and mobile request ? Or would I simply have the mobile application create an authentication token to mimic the csrf token in some way ? -
How to handle time-consuming requests in Django?
I have a Django app that is processing images. User POSTs an image to a view, the view function is processing this image, and then returns a modified one. Lets say a processing can take ~5sec and requires an access to the database. How will this work if multiple users POST images at the same time. Will Django handle the requests one-by-one, causing third user to wait ~15secs? I have found two methods of handling requests simultaneously in Django (please correct me if I am wrong): One is to use a third-party software called Celery to handle tasks in the background. This method requires: Django project reconfiguration Celery "server/worker" process running async functions/views should be decorated with a @shared_task decorator Second method is to configure Apache server to use "workers". This method requires only Apache configuration. Can anyone elaborate on this topic please? -
How to check if message failed in django-channels
I am using channels in my project which made django to use websockets very easy to setup and use. In my application every user that logs in opens a Group to which we can send information if there is any activity. def ws_connect(message): Group("%s" % message.user.id).add(message.reply_channel) so whenever I want to send a message to that user, I use Group('%s' % user.id).send( { 'text': json.dumps({ 'message': 'Some message' }) } ) But this fails silently if there is any error. So question is there way to check if it failed or if there is any way we can check if the Group exists (live or listening ), even before I send data in order to handle it better. -
django 1.9 tests: Able to test the whole project but fails to run individual tests
I have a django 1.9 app with tests that looks like this: these test_*** files contain django.test.TestCase classes, as usual. When I test the whole project with python manage.py test --keepdb everything works perfectly, all tests are found and ran. Using existing test database for alias 'default'... .................................................... ---------------------------------------------------------------------- Ran 38 tests in 12.214s OK However, when I try to run an individual test, like so python manage.py test bots.NodeTreeWalkerTests.test_regex_questions --keepdb it fails: Using existing test database for alias 'default'... E ====================================================================== ERROR: NodeTreeWalkerTests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: NodeTreeWalkerTests Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) ImportError: No module named 'bots.NodeTreeWalkerTests' It worked before, but I renamed my project, and now it doesn't work. It looks like I've messed up some environment variables, but I changed all old name instances to the new name, and the project itself works perfectly, but this one particular issue remains. I tried importing test cases to the tests.__init__ file from bots.tests.test_node_tree_walker import NodeTreeWalkerTests but it didn't help. What am I missing? -
Django form is not saving ManyToManyField for a model
I have an app Posts, a simple blog feature of my project. Each instance of a post can belong to any post category. Since this website will have many contributors/publishers, I made a front end moderation dashboard for contributors, where they can manage posts & pages (add, delete, edit). Everything works, except assigning a category to a post. Namely, I can add new posts/pages from front-end dashboard, I can edit existing or delete them. However, assigning categories apparently does nothing. Categories is a ManyToManyField variable of Post. The form itself shows a select multiple field with all existing categories and it allows me to select/deselect any of them. However, submitting the form will save all the data BUT the categories. Also, when I go to edit an existing post with assigned categories (assigned through django admin), the form pre-selects these categories, but saving the edit from frontend dashboard will not save any changes to this field and will keep the categories assigned through django admin. Is there a reason why ManyToManyField is behaving differently then other form fields? models.py # Model for blog post class Post(models.Model): ... category = models.ManyToManyField(Category, through='CategoryToPost') ... # Model for blog post category class Category(models.Model): … -
Simple Hello World, AJAX FOR DJANGO
So I have this function in views.py def home(request): return render_to_response('proj1/index.html', RequestContext(request, {'variable': 'world'})) Which i want to use for AJAX to display "Hello World"; The ajax function is like so : $.ajax({ url: "/proj1" type:"GET", dataType: "html", success: function(data){ <h1>Hello {{data.variable}}, welcome to my AJAX WebSite</h1> } }); How do i achieve it ? Thanks ! -
Django unique_together creates an index without UNIQUE constraint
I have a model: class MyModel(models.Model) class Meta: unique_together=["a", "b"] index_together=["a", "b"] a=models.IntegerField() b=models.ForeignKey("othermodel") And I am using a MySQL database. Django now creates an index over both fields together, but with type INDEX and not type UNIQUE, which does not result in the expected IntegrityError when saving a duplicate. Manually changing the index results in the correct behaviour. How do i tell Django to create an UNIQUE index? Or is there a good reason why the created index is not setup this way? -
Overriding update( ) Django rest framework
i have a model wich contains a foreign Key so i create my update function but the problem when i want to update my models all fields are updated except the foreign key .I don't know why .I hope that i get an answer My models: class Produit (models.Model): titre=models.CharField(max_length=100) description=models.TextField() photo_principal=models.ImageField(upload_to='produits/',default='image.jpg') photo_1 = models.ImageField(upload_to='produits/', default='image.jpg') photo_2 = models.ImageField(upload_to='produits/', default='image.jpg') photo_3 = models.ImageField(upload_to='produits/', default='image.jpg') prix=models.FloatField() new_prix=models.FloatField() categorie=models.ForeignKey(Categorie,related_name= 'produit', on_delete=models.CASCADE) serializers.py class ProduitUpdateSerializer(serializers.ModelSerializer): categorie_id = serializers.PrimaryKeyRelatedField(queryset=Categorie.objects.all(),source='categorie.id') class Meta: model = Produit fields = ['titre', 'description', 'photo_principal', 'photo_1', 'photo_2', 'photo_3', 'prix', 'new_prix', 'categorie_id', ] def update(self, instance, validated_data): print(validated_data) instance.categorie_id = validated_data.get('categorie_id',instance.categorie_id) instance.titre = validated_data.get('titre', instance.titre) instance.description = validated_data.get('description', instance.description) instance.photo_principal = validated_data.get('photo_principal', instance.photo_principal) instance.photo_1 = validated_data.get('photo_1', instance.photo_1) instance.photo_2 = validated_data.get('photo_2', instance.photo_2) instance.photo_3 = validated_data.get('photo_3', instance.photo_3) instance.prix = validated_data.get('prix', instance.prix) instance.new_prix = validated_data.get('new_prix', instance.new_prix) instance.save() return instance -
ajax call not sending data to django view
Trying to send some variables to a django view. Every time I post, no data is actually sent. Here's my handler that is calls my ajax request. $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, url:'{% url "delete_server" %}', type:'POST', }); $('#confirm-delete').on('click', '.btn-ok', function(e) { var $modalDiv = $(e.delegateTarget); var cust_id = $(this).data('recordCustomer'); var server_id = $(this).data('recordServer'); $.ajax({data:{'server_id':server_id, 'subscription_id':cust_id}, contentType:'application/x-www-form-urlencoded'}).then(); $modalDiv.addClass('loading'); setTimeout(function() { $modalDiv.modal('hide').removeClass('loading'); }, 1000) }); And looking at Firefoxs debugger I see that in the params tab, no data was sent, as well as print(request.POST) shows "QueryDict: {}". So nothing seems to have been sent. From other people having this problem, adding contextType: "application/x-www-form-urlencoded" seems to have fixed it. But as you can see, even with the correct context type, no data is sent. Host: 127.0.0.1:8000 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded X-CSRFToken: eAVAXTOVGxwKrsivMEDoXSyad6hZe7E0LoPtjgxTTG1sOjDG1rUepi4FgLuSUV3i X-Requested-With: XMLHttpRequest Referer: http://127.0.0.1:8000/servers Cookie: csrftoken=eAVAXTOVGxwKrsivMEDoXSyad6hZe7E0LoPtjgxTTG1sOjDG1rUepi4FgLuSUV3i; django_language=en; sessionid=cef5w658g1hbys8xfuld3j884b08qgbk DNT: 1 Connection: keep-alive Content-Length: 0 -
Understanding Django ModelForm Parameters when it is created as an Instance
I was looking at this tutorial,https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html Inside the views, it had this, profile_form = ProfileForm(request.POST, instance=request.user.profile) What exactly is the instance=request.user.profile, what is it doing? Why do I need to add this? Where did .profile come from? -
Django 1.9 Type Error __init__() takes 1 positional argument but 2 were given - problems with class decorating
A bit of context: I'm trying to create a CreateView page for users to input information whilst working with Django 1.9 which is at URL '/profile/'. When users are not logged in, and I go to the /profile/ url then it will redirect me to the login page as expected. However, when I am logged in to the site, and then go to /profile/ then it will display this error: TypeError at /profile/ __ init __() takes 1 positional argument but 2 were given At the moment, I'm decorating a class with a method_decorator, as mentioned in the docs here: https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/#decorating-the-class. This is in my views.py: @login_required(login_url = "/login/", redirect_field_name = None) @method_decorator(login_required, name = 'dispatch') class SpkCreateView(CreateView): form_class = SpkCreateForm template_name = 'userprofile/spk_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): spk_fname = form.cleaned_data['spk_fname'] spk_lname = form.cleaned_data['spk_lname'] The 'name' argument for the method_decorator is also tripping me up so I'm not sure whether it's to do with that. If anybody has any solutions then thanks!