Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net'
After starting project django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' or FileNotFoundError: [Errno 2] No such file or directory: '/proc/5390/task/56199' Full trace of OSError: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 638, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 623, in start_django reloader.run(django_main_thread) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 329, in run self.run_loop() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 335, in run_loop next(ticker) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 375, in tick for filepath, mtime in self.snapshot_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 391, in snapshot_files for file in self.watched_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 294, in watched_files yield from directory.glob(pattern) File "/usr/lib/python3.8/pathlib.py", line 1140, in glob for p in selector.select_from(self): File "/usr/lib/python3.8/pathlib.py", line 587, in _select_from for p in successor_select(starting_point, is_dir, exists, scandir): File "/usr/lib/python3.8/pathlib.py", line 535, in _select_from entries = list(scandir_it) OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' Trace of … -
How to run pytest on Get or Post 200 in Django?
I want pytest to call a function that can run if a REST API post or entry in django is successfull? My project is a django rest framework project and the field is routed as a URL having a single field only My field is called raddress as you can see in the urls.py below from django.contrib import admin from django.urls import path, include from rest_framework import routers from rframe import views ###this gets rid of admin authentication class AccessUser: has_module_perms = has_perm = __getattr__ = lambda s,*a,**kw: True admin.site.has_permission = lambda r: setattr(r, 'user', AccessUser()) or True ###### router = routers.DefaultRouter() router.register(r'raddress', views.RaddressViewSet, basename='raddress') #router.register(r'admin',) #router.register(r'users', views.CheckRaddr) #router.register(r'raddress', views.OrganizationViewSet, basename='raddress') urlpatterns = [ path(r'', include(router.urls)), path('admin/', admin.site.urls), As you can see the view is registered as a URL and I don't know how can I test if the post is successful -
Django middleware runs before drf permissions
I have a middleware class that looks something like this: class DogMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): dog_id = view_kwargs.get("dog_id") if dog_id is not None: dog = Dog.objects.get(id=dog_id) request.dog = dog I have a view that looks something like this: class DogDetail(APIView): def get(self, request, dog_id, *args, **kwargs): return "some nice doggy info" My permissions default to IsAuthenticated: "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), When I call the DogDetail view from a logged-out state, with a dog that doesn't exist, I get a 500 error, and a DoesNotExist exception. I infer from this that the middleware runs before the permissions. My questions: Is this expected behavior? If not, what am I doing wrong? If so, it is very un-ideal, because it would be very easy to leak data through middleware. In my example, it would be very easy for a un-authenticated user to determine which dog_id's existed. What is a good way to mitigate this? I guess I could check for authentication in the middleware, and pass unauthenticated requests through without getting the dog_id? That feels like I'm headed for a deep bug in the future where middleware runs properly, … -
How does Instagram use django for both web and mobile app?
I found that Django rest framework is needed to build both Progressive web app and mobile app.. Instagram uses django for backend, React.js for web, native for mobile Here is the question.. DRF might be too slow to be used by millions of people.. isnt it? How instagram sticks django with both PWA and mobile? What tech they use? -
Is it possible to share the same session for multiple domain names in Django?
I have a Django application (domain name: app.com) that allows users to create a template and host it on a subdomain (example.app.com) using the Django sites framework. Using this option: SESSION_COOKIE_DOMAIN=".app.com" The sites under this domain share the same session but once the user hosts the template on his domain name (custom.com) each site has its own session. Is it possible to make all the sites of this Django application share the same session? Why? So I don't have to log in again each time I visit one of these websites. I tried this middleware but still not working. import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import http_date from django.contrib.sessions.middleware import SessionMiddleware class SessionHostDomainMiddleware(SessionMiddleware): def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session … -
How can I count total likes?
I added a like button to my blog. It's working perfectly but I can't count the total number of likes present. What should I do now? models.py: class FAQ(models.Model): likes = models.ManyToManyField(User,default=None, related_name="faqLIKES") views.py: def index(request): allFAQ = FAQ.objects.all() context = {"allFAQ":allFAQ} return render(request,'0_index.html',context) def likeView(request, pk): post = get_object_or_404(FAQ, id=request.POST.get('faqLIKEid')) post.likes.add(request.user) return redirect("/") -
Django initial migrate of existing Application
I have an application with everything working on local dev machine, and I am trying to set it up on another dev machine with fresh DB (Postgres). I wasnt able to run migrations due to a cannot find field error, so i removed all migrations and tried to make them again, but same error. django.db.utils.ProgrammingError: relation "questionnaire_projectquestionanswerchoice" does not exist LINE 1: ...rojectquestionanswerchoice"."id") AS "count" FROM "questionn... So it seems that makemigrations checks code for issues before it makes them, and obviously it wont find them and always errors. The culprit is below, and commenting out, then doing the migrations works but is a bit of a hack, so if i ever need to do again i would have to follow same process. I have left the culprit commented below. This code works, and then i have to uncomment after. Is there an official way to handle this? class ProjectQuestionMostUsedAnswerChoiceViewset(viewsets.ModelViewSet): # dupes = ( # models.ProjectQuestionAnswerChoice.objects.values("name") # .annotate(count=Count("id")) # .order_by("-count") # .filter(count__gt=0)[:10] # ) # queryset = ( # models.ProjectQuestionAnswerChoice.objects.filter( # name__in=[item["name"] for item in dupes] # ) # .distinct("name") # .order_by("name") # ) queryset = models.ProjectQuestionAnswerChoice.objects.all() serializer_class = serializers.ProjectQuestionAnswerChoiceSerializer filter_backends = ( filters.QueryParameterValidationFilter, django_filters.DjangoFilterBackend, ) filterset_fields = { "id": … -
Filter objects that have a foreign key from another object - Django
I want to filter Employee, only those that have a ForeignKey, how to do it? My solution does not returned any results. Models.py class Employee(models.Model): name = models.CharField(max_length=200) class ExperienceCategory(models.Model): name = models.CharField(max_length=100, unique=True) class Experience(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) category = models.ForeignKey(ExperienceCategory, on_delete=models.CASCADE) Views.py experience_category = *ExperienceCategory object (1)* #solution - final query employee_query = Employee.objects.filter(experience__category = experience_category) How to get employees who have a foreign key from Experience? -
Django runserver hangs on Apple M1 macbook
I have django 3.2.12 application. It is running in docker with image python:3.9.12-slim-buster. When I'm accessing my app through web browser, it often hangs for some time (request pretty always takes exactly 5s - weird). This happens on chrome, firefox, safari. But only on Macbook with M1 CPU, on intel works fine. This problem only exist on runserver, it doesn't exist on gunicorn. The only solution, which I found, is to add '--nothreading' but this is not really a solution. Do you maybe know what can be an issue here? -
Git Bash automaticaly quits the server
When I use a command py manage.py runserverin Git Bash i get: "Watching for file changes with StatReloader" but nothing happens. If i press "Ctrl+C" i get URL and the server instantly stops https://i.stack.imgur.com/J7LWr.png If I don't press "Ctrl+C" but print http://localhost:8000/ in browser myself - URL works P.S. In Cmd everything works properly -
Does Django support all types of website templates(downloaded from web) that have different styles.?
enter image description here When i used a template to my project the styles dont appear correctly. What am i doing wrong? -
Django admin: Editing records with unique fields fails
Python 3.9, Django 3.2, Database is PostgreSQL hosted on ElephantSQL. I have a model, with a slug-field which I have set to unique: class website_category(models.Model): fld1 = models.CharField(primary_key=True, max_length=8) fld2 = models.TextField() fld3 = models.SlugField(unique=True, db_index=True, max_length=100) I can create new records for this model without any issue. However, when I try to edit an already existing record via the Django admin interface (e.g., change the text field - fld2), Django throws this error: website_category with this fld3 already exists I can delete the said record and re-enter the modified one without any issues. I can edit the record if I change the slug field but not otherwise. My guess is this is happening due to the "unique=True" set in the slug field (fld3). However, I do want the slugs to be unique. Is this an expected behaviour of Django or can I do something to make it possible for me to edit the records directly without having to delete and recreate them? -
Wagtail {{document.url}} is returning a 404 for user-uploaded files, in production
I've inherited a Wagtail CMS project but have been unable to solve an issue relating to document uploads. Having uploaded a file through the CMS, it arrives in the documents directory /var/www/example.com/wagtail/media/documents/test_pdf.pdf which maps to the /usr/src/app/media/documents/test_pdf.pdf directory inside the docker container. In the front end (and within the Wagtail dashboard) the document.url resolves to https://example.com/documents/9/test_pdf.pdf/ which returns a 404. Obviously the model number segment is missing from the file path above, but I read on a forum that In Wagtail, documents are always served through a Django view (wagtail.wagtaildocs.views.serve.serve) so that we can perform additional processing on document downloads so perhaps this, in itself, is not an issue. There are a couple of lines in urls.py file which look correct: urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), url(r'^sitemap\.xml$', sitemap), url(r'', include(wagtail_urls)), # url(r'^pages/', include(wagtail_urls)), ] if settings.DEBUG: ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and in base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ So, my hunch is one of either: Uploads being stored incorrectly, in a single folder rather than in subdirectories by model The routing to this “virtual” directory is broken, so it’s breaking at the "check permissions" stage (but I couldn't figure out … -
remove first and last quote from python list
I have a list list = ['1,2,3,4,5,6,7'] I want my list as under: desire output = [1,2,3,4,5,6,7] how to get this, i read other similar answer where strip method used. i had tried strip but strip method not work with list, it work with strings. 'list' object has no attribute 'strip' -
Upload files and send to API with Javascript
I want to receive a file from the user in the frontend and send it to the API so it can be stored, alongside with some other data. However, in the backend (Django), I only receive the path for that file instead of the file itself and I'm sending the data with the "multipart/form-data" encoding type. HTML: <input [(ngModel)]="file" type="file" id="file" name="file" accept=".edf" required> TypeScript service: submitEEG(patientID: string, operatorID: string, file: File) : Observable<EEG> { let formData = new FormData(); formData.append("file", file); formData.append('patientID', patientID); formData.append('operatorID', operatorID); console.log(patientID); console.log(operatorID); console.log(file); return this.http.post<any>(this.BASE_URL + 'createEEG', formData); Data received in the REST API: Can someone help me? Thanks! -
Which Django generated files can be safely deleted
Simple question but I can't find exact answers on the web about it but by cleaning my Django app before it is ready I was thinking about which Django unused files I could safely delete to clean my app paths. The one I'm not using and wondering about : admin.py apps.py test.py models.py Thank you in advance for your help ! -
AWS image upload with Python/Django is not working
I am a beginner using Python/Django. few months ago I deployed an app that has an image upload feature which is connected with AWS S3 buckets. when I run the server locally on my machine, the app works fine. However I deployed the app to Heroku and the image upload stopped working, no errors in the console, and the image itself is not even uploaded to the AWS bucket. This is my views for uploading the images: def add_photo(request, team_id): photo_file = request.FILES.get('photo-file', None) if photo_file: s3 = boto3.client('s3') key = uuid.uuid4().hex[:6] + photo_file.name[photo_file.name.rfind('.'):] try: s3.upload_fileobj(photo_file, BUCKET, key) url = f"{S3_BASE_URL}{BUCKET}/{key}" photo = Photo(url=url, team_id = team_id) photo.save() except Exception as e : print('An error occured uploading files to s3') print(e) return redirect('teams_detail', team_id = team_id) this is the template for upload : {% for photo in team.photo_set.all %} <img src="{{photo.url}}" alt="{{photo.url}}" class="responsive-img card-panel"> {% empty %} <div class="card-panel teal-text center-align">No Photos Uploaded</div> {% endfor %} <form class="card-panel" action="{% url 'add_photo' team.id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="photo-file"> <br> <br> <input type="submit" class="btn" value="Upload Photo"> </form> Like I said this is an app that I created a few months ago. so appreciate if you can point out … -
Django: how to retrive latest news from hackernews api using django
i am trying to retrieve the lastest news from hackernews api, everthing seems to be working fine and when i print the status code, i get Status Code:200 meaning it all working fine, but then i don't get any data. the code below is going to get some data using the api and save it to a model that i already created, and then i also have a view that display the news in my templates. So how do i get the news from the api? import dateutil.parser import datetime import requests from celery import shared_task from django.template.defaultfilters import slugify from .models import LatestStory, Comment BASE_API_URL = "https://hacker-news.firebaseio.com/v0" def get_item(id): item = requests.get(f"{BASE_API_URL}/item/{id}.json") return item.json() @shared_task def get_and_store_story_comments(unique_api_story_id, story_id): single_story = get_item(unique_api_story_id) story = LatestStory.objects.get(id=story_id, unique_api_story_id=unique_api_story_id) for kid in single_story.get("kids", []): comment_response = get_item(kid) comment, _ = Comment.objects.get_or_create(unique_comment_api_id=kid, id=story.id) comment.story = story comment.story_type = comment_response.get("type", "") comment.author = comment_response.get("by", "") comment.time = dateutil.parser.parse( datetime.datetime.fromtimestamp(comment_response.get("time", 0)).strftime("%Y-%m-%d %H:%M:%S") ) comment.text = comment_response.get("text", "") comment.comment_url = comment_response.get("url", "") comment.score = comment_response.get("score", 0) comment.save() def get_max_item_id(): max_item_id = requests.get(f"{BASE_API_URL}/maxitem.json") return max_item_id.json() @shared_task def store_latest_stories(): max_item_id = get_max_item_id() for sid in reversed(range(max_item_id)): story_response = get_item(sid) story, _ = LatestStory.objects.get_or_create( unique_api_story_id=sid, title=story_response.get( "title", f"No title for … -
How to use count() and sum() in serializer?
I want to calculate the average rating on sum_of_rating/number_of_rating. class SearchWorkingProgessionals(APIView): def post(self,request,format=None): tags = request.data.get('tag_arr') city_name = request.data.get('city_name') tags_list = tags.split(',') ws = WorkSamplesModel.objects.filter(business_account__serviceareasmodel__city_name=city_name, business_account__professiontagsmodel__tag_name__in=tags_list, is_business_card_image=True).distinct() serializer = SearchWorkingProgessionalsSerializer(ws,many=True) resp = {'resp':serializer.data} return Response(resp) class FeedbackModel(models.Model): feedback_text = models.CharField(max_length=20) rating = models.IntegerField() business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'feedback' This is my current serializer class SearchWorkingProgessionalsSerializer(serializers.Serializer): business_account_id = serializers.IntegerField() first_name = serializers.CharField(source='business_account.user.first_name') last_name = serializers.CharField(source='business_account.user.last_name') profile_pic = serializers.ImageField(source='business_account.user.profile_pic') business_title = serializers.CharField(source='business_account.business_title') business_description = serializers.CharField(source='business_account.business_description') status = serializers.CharField(source='business_account.status') note = serializers.CharField(source='business_account.note') work_sample_image = serializers.ImageField() work_sample_description = serializers.CharField(max_length=1000) How to calculate average rating using this serializer? -
Table with total summary per year-month Django
I have an expense accounting application, I need to make a table of expenses by year and month, I have a query like: queryset.all().values_list('date__year', 'date__month').annotate(Sum('amount')).order_by('date__year', 'date__month') I got a queryset with amounts by month, how do I get the amounts for each year nicely? I did, but I got a monster of 15 lines: def get_per_year_month_summary(queryset) -> OrderedDict: years_months = OrderedDict() years = sorted(set(map(lambda x: x['year'], queryset .annotate(year=ExtractYear('date')).values('year')))) for year in years: months = sorted(set(map(lambda x: x['month'], queryset .filter(date__year=year) .annotate(month=ExtractMonth('date')) .values('month')))) total_year = queryset.filter(date__year=year).aggregate(Sum('amount'))['amount__sum'] years_months[str(year)] = total_year for month in months: sum_month = \ queryset.filter(date__year=year, date__month=month).aggregate(Sum('amount'))['amount__sum'] years_months[f'{year}-{month}'] = sum_month return years_months Model: class Expense(models.Model): category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) -
How to call Python-django function(scrap the data from website) within the html?
I saved the links of one website in the database and searched them one by one from the Html search box, it gives me the scraped CSV file. When I searched for another website it throws an error. So I created another function with scraping code and return the value on a different Html page. Django only reads the first function. I'm stuck here. My scraping code fetches the details properly in another python file.Here are views.py,views.py,Here is urls.py,Here is index.html where search the link,Here is amazon.html should be downloaded the scraped data. -
Django - Filter a queryset by a property value
I would like to filter a queryset by the field id which is in an array of objects. I already have the id to compare this field to ie request.user.id which I get from the authenticated user. Lets assume that the logged in user has an id = 290 Thus; request.user.id = 290 Below is the structure of the Queryset [ { "id":"93b9f61a-a5c9-4c26-99a4-22f5447bdd3f", "approval_status":"not approved", "assignee":[ { "id":289, "username":"zverifier" } ], "sector":"Electricity" }, { "id":"270387f6-3c5c-4289-8baa-08441f318ec1", "approval_status":"approved", "assignee":[ { "id":289, "username":"zverifier" }, { "id":290, "username":"yverifier" } ], "sector":"Electricity" } ] I have tried using this; queryset = queryset.filter(assignee=request.user.id) but it only stops at the assignee and cant proceed to the id field within assignee.At the end of the day, I would like the Authenticated user to only see objects in which he is an assignee. -
Optimizing handling multiple requests in Django
I'm trying to build a simple REST API with Django. It works really good when dealing with a low rate of requests, but when I mock 100+ requests simultaneously the responses time goes from 0.3 seconds to around 3-4 seconds. I've check the runtime of my view and it no more than 0.1 seconds no matter what, which make me thinking that the problem is in the response sending itself. Any ideas how to optimize it? The model + view that I'm using: class Permutation(models.Model): id = models.AutoField(primary_key=True) hash_code = models.TextField(null=False, unique=True) all_permutations = models.TextField(null=False) @api_view(['GET']) def similarWords(request): word = request.GET.get('word', None) start_time = datetime.now() if not word or not word.isalpha(): updateLogs(start_time) print('invalid word') return HttpResponse(status=400) perm = Permutation.objects.filter(hash_code=getHashCode(word)) if not perm: updateLogs(start_time) return HttpResponse(json.dumps({'similar': []}), content_type="application/json", status=200) else: perm = perm.first() permutations_array = perm.all_permutations.split(' ') if word in permutations_array: permutations_array.remove(word) data = {'similar': permutations_array} updateLogs(start_time) return HttpResponse(json.dumps(data), content_type="application/json", status=200) -
Distinct values on annotated field using ArrayAgg
I'm trying to annotate to queryset field containing list of user account uuids interested and not interested in participation in some kind of event. This project uses Django 1.11 and PostgreSQL, so i wanted to annotate this list using ArrayAgg. Sadly this version of Django does not support distinct kwarg on ArrayAgg so list I'm getting back contains duplicated elements. Things that I have tried: Using properties on model - this works well and results are good, but instead of 2 queries in 10ms it does ~300 queries in 200ms. It's on development DB so it will be much more noticable on production. Implementing my own ArrayAgg and Aggregate using code from Django 2.0 repo and it works well, I'm getting desired 2 queries, but is there better way so I can evade such "hacky" solution? I can't update Django to version 2.0 Code example: It's version with displayed duplicates models.py import uuid as uuid from django.db import models class Account(models.Model): uuid = models.UUIDField(default=uuid.uuid4) class MyUser(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) class InterestStatus(models.Model): name = models.CharField(max_length=100) interested = models.ManyToManyField(MyUser, related_name='interested') not_interested = models.ManyToManyField(MyUser, related_name='not_interested') @property def interested_users_uids(self): ids = [] for user in self.interested.all(): ids.append(user.account.uuid) return ids @property def not_interested_users_uids(self): ids … -
Django - crispy forms not rendering in the browser
I'm new to django and I'm working on a blog project, but the browser does not render my form on the profile page. Specifically the form to update an profile image. Here's my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() # A class to specify the model the form is going to interact with class Meta: model = User # Fields wanted in the form and in what order: fields = ['username', 'email', 'password1', 'password2'] # A model form is a form that allows the creation of a form that will work with a specific database model class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py def register(request): # If it gets a POST request then it instantiates a user creation form with that POST data if request.method == 'POST': # Create a form that has the request POST data: form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, 'Your account was created. You are now able to log in') return redirect('login') # With any other request it creates an empty user creation form else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) …