Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URLpattern match doesn't work as expected
What I want I'm running the very first steps of the Django Project tutorial and there's already something i can't get right. The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work. I built everything as needed and my 'shelves' server works fine (debug here, running on localhost). I'm setting the urlpatterns in shelves.urls, the first of which tries to include 'bluebook.urls'. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('bluebook/', include('bluebook.urls')), path('admin/', admin.site.urls), ] When I go to http://127.0.0.1:8000/bluebook/, it works fine and loads the views.index I set up. What doesn't work When I go to http://127.0.0.1:8000/thebluebook/, it throws a 404. It goes as far as defining regex match not working : Using the URLconf defined in shelves.urls, Django tried these URL patterns, in this order: 1. bluebook/ 2. admin/ The current path, thebluebook/, didn't match any of these. It does the same with http://127.0.0.1:8000/the_bluebook/ or http://127.0.0.1:8000/go/bluebook/. What I tried I haven't written much code so there's not much to join to … -
How to convert the following sql query to Django query
I need to convert the below SQL query into Django query using a filter. How can I do that? SELECT * FROM catalogue_productcategory WHERE (category_id=40) and (product_id=7) -
Django: When do I need __eq__ method?
In Django I've written a custom class-based validator and implemented the __eq__ method because it's also done for the validators that are already implemented by Django itself. Here you can see it: @deconstructible class FileSizeValidator: def __init__(self, mb): self.mb = mb def __call__(self, value): limit = self.mb * 1024 * 1024 if value.size > limit: raise ValidationError('File too big (max. ' + str(self.mb) + ' MiB).') def __eq__(self, other): return ( isinstance(other, FileSizeValidator) and self.mb == other.mb ) Now, I've also written a custom class for the ImageField. I want to use it for the upload_to= parameter in a model for the ImageField. Here you can see my example: @deconstructible class RandomFileName: def __init__(self, directory=''): self.directory = directory def __call__(self, instance, filename): return self.directory + ("/" if self.directory else '') + get_random_string(7) + "." + filename.split('.')[-1] def __eq__(self, other): return ( isinstance(other, RandomFileName) and self.directory == other.directory ) In general, I am happy with it and it seems to work fine. I just do not know when I need the __eq__ method and would like to ask you for an explanation. -
Run python script after prom HTML request in Django
I have a Django web application in which data can be stored. I have some python code running to analyze this data. I want a client to be able to use these standardized analysis after submitting a dataset. However some analysis are heavy so I only want them to run when specifically requested. What I’ve read so far I think I can use some custom admin commands or WSGI to run standalone scripts on the server side after a request from the client. However I’m not sure these methods are the best way to do this. What is a good method to run these stand alone analyses after request from a client? -
Django management command + gevent - async
I' ve a little code in a django management command, but for some reason it does not make an async call, and i don' t exactly understand the reason. The sample is here: def task(obj): print('Start: %s' % obj.id) do_bg(obj) print("Task: %s(%s)" % (obj, obj.id)) print('End: %s' % obj.id) threads = [] for obj in objs: threads.append(gevent.spawn(task, obj)) gevent.joinall(threads) . do_bg(obj) is a bit of a complicated method, usually it runs for <8 seconds and it creates an ssh collection to the obj machine, collects some information, and processes it. If i replace the do_bg(obj) with gevent.sleep(random.randint(0, 1)) then the tasks run simultaneously, but with the do_bg(obj) line they run after each other. I' d like to know the reason, and how i could make them run parallel? Django: 1.9.2 gevent: 1.3.5 python: 3.4.2 . Thanks. -
Django generic UpdateView security issue
the code below allows the user to update his Company Profile and that works fine. The problem I am facing is that to get the user's CompanyProfile I have to pass a "pk" variable in the url, like this <a class="btn btn-outline-success btn-lg" role="button" href="{% url 'user_profile_update' CompanyProfile.user_id %}" style="font-family: 'slabo'">Edit</a> url(r'^companyprofile_update_form/(?P<pk>\d+)/$', UpdateCompanyProfile.as_view(), name='user_profile_update'), this is the view class UpdateCompanyProfile(UpdateView): model = CompanyProfile form_class = CompanyProfileForm # fields = ['contactNumber', 'address', 'areaCode', 'deliveryEmails', 'keywords'] template_name_suffix = '_update_form' As you can imagine, there is a number of users in the DB with their own CompanyProfiles. The problem is that a user can change the pk variable in the URL and then have access to another user's CompanyProfile and then perform an update on that profile, and this is of course unauthorized access, how can I avoid this. -
changed made in css not loading in django project?
I am working on projects first i made front-end which i integrate with django. I copy my style sheet in django and set important SETTINGS.then i run server which work fine for me. CSS load properly.But when add some more CSS in my style file this is not loading,please help me? setting.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/' -
Post Data in Django Value error
I'm new in the Django.I have 2 models, one of them Post, class Post(models.Model): unit = models.ForeignKey('Unit',on_delete=models.CASCADE, primary_key=False, blank = True) and next is Unit model, class Unit(models.Model): name = models.CharField(max_length=120, unique = True) def __str__(self): return self.name I use ForeignKey, and i have such problem. In my site I use Unit model like drop down list <div class="form-group"> <label for="id_unit">Unit</label> <select class="selectpicker form-control" data-live-search="true" name="unit"> {%for unit in units%} <option>{{ unit.name }}</option> {%endfor%} </select> </div> and when I try to create a new Post by site I have a value error "Cannot assign "'Moscow'": "Post.unit" must be a "Unit" instance." This is my function in the view.py, that create. def post_new(request): posts = Post.objects.all() units = Unit.objects.all() if request.method == 'POST': title = request.POST['title'] text = request.POST['text'] unit = request.POST['unit'] user = User.objects.first() status = StatusOfPost.objects.first() post = Post.objects.create( author = user, title = title, text = text, unit = unit, status = status ) return redirect('postsList') return render(request, 'post_new.html', {'posts': posts, 'units': units}) What I must do, i don't understand. How apply Unit.name value to Post.unit. Sorry for the stupid question, but I'm learning. -
Get most frequently used many to many field
I have the following models. class Tag(models.Model): name = models.CharField(max_length=30) # and other fields ... class Book(models.Model): name = models.CharField(max_length=140) tags = models.ManyToManyField(Tag, blank=True) # and other fields class Article(models.Model): name = models.CharField(max_length=140) tags = models.ManyToManyField(Tag, blank=True) And few other models have tags as ManyToMany field. I would like to get the list of most used tag objects. I tried to filter most frequently used tags from each model and then getting top ten from each and combining them with other top ten. I think there should be something I could do from 'Tag' model itself to find the most used tag instances. Is there any way of finding the most used tag instances except my approach ? Any help would be really appreciated. -
Converting a List in Django Template Into A JSON object
How do i go about converting a python list in a django template into json data? The code is as follows. The console.log(sentcountjson) line is for the purpose of debugging, and should output a json object. But just appears to output a python list format. As such it is not possible to parse it as a json object. I have attempted to use the following library, but I may be mistaken: https://github.com/romgar/django-jsonify {% for malwarename, malwarehash in malwarehashdict.items %} {% for ppmshash, sentlist in packetsperminutesent.items %} {% if ppmshash == malwarehash %} {% block content %} <script type="text/javascript"> <![CDATA[ var sentcountjson = {{sentlist | jsonify }}; ]]></script> {% endblock %} <script type="text/javascript"> console.log("sent count json"); console.log(sentcountjson); </script> <script> var sentcountparsed = JSON.parse(sentcountjson); for(var x in sentcountparsed){ sentcountarray.push(parsed[x]); } </script> {% endif %} {% endfor %} {% endfor %} Any help would be very much appreciated. -
Django User.set_password leads to invalid password
I'm trying to write a serializer (in Django REST Framework) to update a user's account details. Here is the update() method: def update(self, instance, validated_data): ... if all([item in self.validated_data for item in ["password", "confirm_password", "old_password"]]): user = authenticate(username=self.context["request"].user.username, password=self.validated_data["old_password"]) if user is not None: if self.validated_data["password"] == self.validated_data["confirm_password"]: validate_password(self.validated_data["password"]) user.set_password(self.validated_data["password"]) user.save() else: raise serializers.ValidationError({"confirm_password": "Passwords do not match"}) else: raise serializers.ValidationError({"old_password": "Password incorrect"}) self.validated_data.pop("password") return super(UserInfoSerializer, self).update(instance, validated_data) When I perform a PATCH request to the view with "password", "confirm_password" and "old_password" as fields, it appears to have worked. Then when I try to log into the account again, it fails (using both old and new passwords). When I check the admin settings and view the user I am trying to edit, I get the following: Invalid password format or unknown hashing algorithm. Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form. I believe User.set_password() is supposed to handle hashing/etc. automatically, so why do I get this error? -
countdown resets after page refresh
My page configuration parameters are volatile and my countdown keeps resetting after page refresh. The time is set in seconds from html. I've tried adding date to end: but it doesn't seem to work. here is my configuration: (function($) { $.fn.ClassyCountdown = function(options, callback) { var element = $(this); var DaysLeft, HoursLeft, MinutesLeft, SecondsLeft; var secondsLeft; var isFired = false; var settings = { end: undefined, now: $.now(), labels: true, labelsOptions: { lang: { days: 'Days', hours: 'Hours', minutes: 'Minutes', seconds: 'Seconds' }, style: 'font-size: 24px;' }, style: { element: '', labels: false, textResponsive: 0.5, days: { gauge: { thickness: 0.02, bgColor: 'rgba(0, 0, 0, 0)', fgColor: 'rgba(0, 0, 0, 1)', lineCap: 'butt' }, textCSS: '' }, hours: { gauge: { thickness: 0.02, bgColor: 'rgba(0, 0, 0, 0)', fgColor: 'rgba(0, 0, 0, 1)', lineCap: 'butt' }, textCSS: '' }, minutes: { gauge: { thickness: 0.02, bgColor: 'rgba(0, 0, 0, 0)', fgColor: 'rgba(0, 0, 0, 1)', lineCap: 'butt' }, textCSS: '' }, seconds: { gauge: { thickness: 0.02, bgColor: 'rgba(0, 0, 0, 0)', fgColor: 'rgba(0, 0, 0, 1)', lineCap: 'butt' }, textCSS: '' } }, onEndCallback: function() { } }; if (options.theme) { settings = $.extend(true, settings, getPreset(options.theme)); } settings = … -
[Django][Python] Posts from admin panel on different subpages
I would like to add post list from main page to another subpages. (main page to subpage called "programowanie") For example: I have a website wwww.example.com. On this website I have a post list that is generated from admin panel (I can add, delete a posts using admin panel). The problem is that when I try to copy templates from start page with post list to other subpage (called: www.example.com/programowanie) it doeasn't work (I see a template from main page but without post list) I think the problem is in templates/blog/post/list.html in loop {% for post in posts %} If I solve this problem I would like to add in admin panel different overlap to publish posts only in "programowanie" subpage. This is my files: blog/views.py from django.shortcuts import render, get_object_or_404, HttpResponse from .models import Post, Posta, Comment from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from .forms import EmailPostForm, CommentForm from django.core.mail import send_mail from taggit.models import Tag from django.db.models import Count def post_share(request, post_id): # Pobranie posta na podstawie jego identyfikatora. post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Formularz został wysłany. form = EmailPostForm(request.POST) if form.is_valid(): # Weryfikacja pól formularza … -
AttributeError: 'module' object has no attribute 'use_cache'
Running Django tests ./manage.py test Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python2.7/site-packages/django_coverage/coverage_runner.py", line 71, in run_tests coverage.use_cache(settings.COVERAGE_USE_CACHE) AttributeError: 'module' object has no attribute 'use_cache' I've tried many things but I do not know how to fix this. -
If else in Jinja2
How can i disable a button if the two values coming from my views.py are equal. Is it possible to make it work like this? <button {% if value1 == value2 %} {{'disabled'}} {% endif %} type="button">Add</button> -
How can I use taggit-selectize so that all user-made tags show up in the autocomplete?
I found this project https://github.com/chhantyal/taggit-selectize and it seems to do what I want, but the example app is incomplete, so I don't know how to use it. What I basically want is that users will be able to write their own tags for a post, and that if they are typing one that has been used before by someone else, it will show up in autocomplete. I also want a search function that will use the autocomplete in the same manner. I'm sure it's not very complicated but the readme only explains how to install and what some things mean, and I was looking for a very minimal working example that makes the autocomplete work. Thanks in advance. -
Locked out of PuTTY + root account
I'm setting up my new droplet from Digital Ocean when I got locked out of my SSH and root account. So here is the events that led up to the mistake: I went configuring the /etc/ssh/sshd_config in PuTTY and after changing PermitRootLogin to "no" I hit CTRL + S and then it "freaked out". I closed the PuTTY window and I had no other session open. Now when I try to enter my server in PuTTY via my Droplets ip adress I get the follow error: Network error: Connection refused. I have read several guides to fix this but they all assume that you can enter PuTTY via your root account and eg. press CTRL + Q etc.. Anyone knows how to fix this? -
Circular Import
During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 400, in check warnings.extend(check_resolver(pattern)) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 549, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django: unsupported operand type(s) for -: 'NoneType' and 'NoneType'
I receive an error unsupported operand type(s) for -: 'NoneType' and 'NoneType'. The reason is when either transaction.aggregate(Sum('amount')) or reward_transaction.aggregate(Sum('amount')) has no entry yet. I now wonder is the best way to solve that try / except or is there a 'better way' I haven't considered? views.py: user = request.user ambassador = user.ambassador_profile total_collected = ambassador.transaction.aggregate(Sum('amount')) total_redeemed = ambassador.reward_transaction.aggregate(Sum('amount')) -
Post form data to url with function in django
I have some data for creating model and I also have form of that model so, user can also create model instance, now what I wanted to do is - creating the model in same way as user fill and submit the form. I want to do so because I am adding some additional data with form_valid to that model, for example - form.instance = self.request.user and many others and also having some custom validations. For doing that what I thought is, If I create a form and put the data in it and post it to url. I don't know wheather it is good idea or not, but any one can who can help ? -
manage.py createsuperuser is not working with custom user model
I'm using Django, and I've created a custom user model to be able to use E-mail as main login method instead of username.. everything worked but I can't create a superuser using the command python manage.py createsuperuser. Here are my codes : models.py from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.db.models import CASCADE from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): user_name = models.CharField(_('user name'), max_length=35) email = models.EmailField(_('email address'), unique=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('staff'), default=False) is_superuser = models.BooleanField(_('superuser'), default=False) avatar = models.ImageField(upload_to='media/', null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, from_email, [self.email], **kwargs) And here are managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, … -
django validate and convert any image to jpeg then save
i have image field type file in model ...i want check user uploaded file is image or not if its image i want convert it to "jpeg" format for reduce size and security purposes.. how can i do that ? related view: class StoreCreateAPIView(generics.CreateAPIView): parser_classes = (MultiPartParser, FormParser) permission_classes = [IsAuthenticated, IsSuperUserOrAdmin] def post(self, request, *args, **kwargs): if request.method == 'POST': file_serial = ProductSerializer(data=request.data, context={"request": request}) if file_serial.is_valid(): file_serial.save(author_id=request.user.id) model: def validate_image(image): if not image.is_image(): raise ValidationError('File should be image.') file_size = image.file.size limit_kb = 200 if file_size > limit_kb * 1024: raise ValidationError("Max size of file is {} KB".format(limit_kb)) # save the uploaded file in user directory def upload_to_custom_p(instance, filename): name = instance.title user_id = str(instance.author.id) filename = filename.lower() return 'Product/img/user_{0}/{1}/{2}'.format(user_id, name, filename) class Product(models.Model): product_id = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) title = models.CharField(max_length=200) full_description = models.TextField(null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) publish = models.BooleanField(default=False) draft = models.BooleanField(default=False) slug = models.SlugField(allow_unicode=True, null=True, blank=True) image = models.FileField(upload_to=upload_to_custom_p, null=True, blank=True,validators=[validate_image]) -
Append newly query request ?page=2 to existing query ?q=python
I search http://127.0.0.1:8000/search/?q=python in my project home page which return results with multiple pages: Here is my pagination sinppet <ul class="pagination pagination-sm"> {% for i in page.page_list %} {% if i == page.number %} <li class="active"> <a href="?page_number={{ i }}">{{ i }} </a> </li> {% else %} <li> <a href="?page_number={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} </ul> When I click page 2 in the page, it issue request http://127.0.0.1:8000/search/?page_number=2 rather than http://127.0.0.1:8000/search/?q=python?page_number=2 How append the ?page_number=2 to its existing query? -
Reactjs - PUT and PATCH requests not reflecting
I am working with a Post model which looks something like this: class Post(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) upvotes = models.ManyToManyField(Profile, blank=True, related_name='upvoted_posts') downvotes = models.ManyToManyField(Profile, blank=True, related_name='downvoted_posts') The Profile model is just a wrapper over the django's User model. Now, I have defined 2 serializers for my convenienve: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' class PostSerializer_detailed(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' depth = 1 This is the view: class DetailPostOfReddit(RetrieveUpdateDestroyAPIView): queryset = Post.objects.all() def get_serializer_class(self): if self.request.method == 'GET': return PostSerializer_detailed return PostSerializer def get_object(self): queryset = self.filter_queryset(self.get_queryset()) conditions = { 'subreddit__name': self.kwargs['r_name'], 'id': self.kwargs['p_id'] } return get_object_or_404(queryset, **conditions) def put(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) Now, In the UI there is a button to upvote a post. Whenever User clicks that button toggleUpvote function gets called: getIds(json) { var ls = [] if (json) { for (var i = 0; i<json.length; i++) { ls.push(json[i]['id']) } } return ls } toggleUpvote() { let ids = this.getIds(this.props.upvotes) let json = {} var new_ids = [] ids.indexOf(this.props.context.userId) === -1 ? ( console.log('User not … -
Why client.post in Django keeps returns GET response
I'm developing web apps under django 2.0.4 and python 3. And I need to write a test for the Signup view, to make sure that the redirection happens after a successful signup is made. Here is the code: forms.py from django.contrib.auth.forms import UserCreationForm from django.cotnrib.auth.models import User class SignupForm(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=200) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) views.py from django.shortcuts import render, redirect from .form import SignupForm class SignupView(View): template_name='signup/signup.html' form_class = SignupForm def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form' : form }) post(self, request, *args, **kwargs): form = self.self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user=authenticate(username=username, password=raw_password) if user is Not None: login(request, user) return redirect('index') else: form = self.form_class() context = {'form' : form} return render(request, self.template_name, {'form' : form}) urls.py (app) from django.url import path urlpatterns = [ path('signup/', views.SignupView.as_view(), name='signup'), ... ] signup.html <form method="post" action="{% url 'signup' %}> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">sign up</button> </form> All above works well, until I try to make a test on the post. That is a test against the code. return redirect('index') Here …