Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
another -> django.db.utils.OperationalError: (1709, 'Index column size too large. The maximum column size is 767 bytes')
I have the following problem, but first my development environment: ubuntu 18.04 python 3.7.4 mariadb 10.7.4 django 3.2.13 Attempt to configure django-allauth 0.50.0 I follow the steps of the official website and everything is ok, but, when it comes time for python manage.py makemigrations all right, but when I give python manage.py migrate I got this error: django.db.utils.OperationalError: (1709, 'Index column size too large. The maximum column size is 767 bytes') I already try all kinds of solutions that I found here, Like This , but all relate about mariadb 10.1 and 10.2, where it is assumed that in this last version the problem should be solved, but here I have it. pd: excuse my english -
data from database is not showing in html template in django
I fetched data from books table in views.py and passed to show.html as dictionary.It is not showing.also i wanted to check if there is key passed in html..so purposely wrote paragraph after {%if key1 %} ,it is not showing that paragraph also.what will be the reason or my fault? here is my code snippet views.py def show(request): books = Books.objects.all() return render(request,'app/show.html',{'key1':books}) urls.py from django.urls import path from . import views urlpatterns = [path("",views.index,name = 'home'), path('show/',views.show,name= 'show'), ] models.py class Books(models.Model): book_num = models.IntegerField() auth_name = models.CharField(max_length = 50) book_name = models.CharField(max_length = 100) def __str__(self): return self.auth_name show.html <center> <table> <tbody> <th>Available books</th> {%if key1%} <P>please check if issued</p> {% for i in key1 %} <tr> <td>Author name:{{i.auth_name}}</td> <td>Book title:{{i.book_name}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </center> -
django login / register auth safe?
I knew that django already has the auth system . However, I heard that either session and token are needed for security. should I build login, logout, registeration with session or token in view? or is it included in django's auth? -
How can I fix my code For Django's reply comment
When entering a reply comment, It will be redirected to my post with comments How can I fix it? Please Someone help me post_detail.html <!-- Reply Button Area --> <button class="btn btn-sm btn-secondary" type="button" style="float:right" data-toggle="collapse" data-target="#replyBox{{comment.id}}" aria-expanded="false" aria-controls="replyBox{{comment.id}}"> Reply </button> <div class="collapse" id="replyBox{{comment.id}}"> <div class="card card-body my-2"> <form action="/blog/{{ comment.pk }}/reply_comment/" method="post"> {% csrf_token %} <div class="form-group"> <label for="comment">Reply </label> <input type="text" class="form-control" name="comment" placeholder="type the comment"> <input type="hidden" name="parentSno" value="{{comment.id}}"> </div> <input type="hidden" name="post.pk" value="{{post.pk}}"> <button type="submit" class="btn btn-sm btn-primary">Complete</button> </form> </div> </div> <!-- Reply Button Area END --> Views.py def reply_comment(request , comment_pk) : if request.user.is_authenticated : comment = get_object_or_404(Comment , pk=comment_pk) if request.method == 'POST' : recomment_form = ReCommentForm(request.POST) if recomment_form.is_valid() : recomment = recomment_form.save(commit=False) recomment.author = request.user recomment.comment = comment recomment.save() return redirect(comment.get_absolute_url()) return redirect(comment.post.get_absolute_url()) else : raise PermissionError -
django model data returns none in html but shows in admin panel
ive created a model that lets users create a simple post however when the data is submitted it registers in the admin panel but will not display in the html. I can edit in admin and the images even up in the folder unfortunately I cannot find out what the issue is models.py from distutils.command.upload import upload from django.db import models from django.forms import CharField, ImageField from django.forms.fields import DateTimeField from matplotlib import image from sqlalchemy import true from django.contrib import admin # Create your models here. class Posts(models.Model): image = models.ImageField(upload_to='images/') quote = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True, null=True) views.py from django.contrib.auth import login, authenticate from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from requests import request from users.forms import SignUpForm from matplotlib.style import context from django.http import HttpRequest, HttpResponse from .models import Posts def signup(request): if request.method == 'POST': form = SignUpForm(request.POST)# was UserCreationForm if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('profile') #profile else: form = SignUpForm() #was UserCreationForm return render(request, 'signup.html', {'form': form}) def posts(request): userpost = Posts.objects.all() return render(request, 'posts.html', {'userpost': Posts} ) urls.py from django.urls import path from … -
Join django tables
I need to connect the Alumno table with the Horario, how could I do the syntax? I need to get the id_curso of each Alumno, and with that id_curso join it to the Horario table but I don't know how to do it I think you have to use select_related or prefetch_related, which I don't know very well how to use, I tried to create a variable to get the id_course and with that variable use filter but I didn't take it Helpme please models.py class Alumno(models.Model): rut_alumno = models.IntegerField(primary_key=True) dv_alumno = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15) s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) fecha_nac = models.DateField() genero = models.CharField(max_length=1) direccion = models.CharField(max_length=25, blank=True, null=True) nivel_socio = models.CharField(max_length=10) id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING, db_column='id_examenes') rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING, db_column='rut_apoderado') id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio') id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso') id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') class Meta: managed = True db_table = 'alumno' class Curso(models.Model): id_curso = models.IntegerField(primary_key=True) grado = models.CharField(max_length=1) educacion = models.CharField(max_length=10) letra = models.CharField(max_length=1) id_colegio = models.ForeignKey(Colegio, models.DO_NOTHING, db_column='id_colegio') rut_profesor = models.OneToOneField('Profesor', models.DO_NOTHING, db_column='rut_profesor') class Meta: managed = True db_table = 'curso' class Horario(models.Model): id_horario = models.IntegerField(primary_key=True) dia = models.CharField(max_length=10) hora_inicio = models.CharField(max_length=5) hora_termino … -
insert ₹ in python Django mysql. i'm using frontend react and backend Python
Hi There when i was entering ₹ in a textfield i'm getting django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xE2\\x82\\xB9' for column 'sk_ver_reason' at row 1") this textfield is a description box, mysql acception other countries curreny sign but not in indian currency, i have chages much collation from utf8mb... when i hit api this sign failed, but the entry for this api enter in db, same i hit again it run succefully, is it python django error or purely mysql db error. in below image you can see collation of that perticualr field. -
ApplicationOAuth using PyGithub in Django
I am building Github App. I have tried to access repository from Github by using Access tokens, It will work fine Here is the Code username = "user" reponame = "test" g = Github("my_access_token") repo = g.get_repo(username + "/" + reponame) files = repo.get_contents("") But now I want to access the repository by using Application authorizing, for this I am using PyGithub library. Here is the link which demonstrate what i am trying to do exactly. (Must read this..Please) and This is the PyGitHub Docs to achieve above functionality. I am not Getting how to implement this exactly. -
Batch Complete Tasks in DRF
I have my Django website where i can have tasks created and subtasks under tasks i have mark complete option which is working fine i need them to be completed in batch like selecting multiple tasks at once and complete them. serializers.py: class TaskCompleteSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'is_done', ) def update(self, instance, validated_data): person = self.context['request'].user.person task_is_done = validated_data.get('is_done', False) if task_is_done: instance.subtasks.update(is_done=True) instance.is_done = task_is_done instance.done_by.set([person]) instance.save() return instance models.py: class TaskUpdateAPIView(UpdateAPIView): permission_classes = " " serializer_class = TaskCompleteSerializer queryset = Task.objects.all() model = Task lookup_url_kwarg = 'task_id' -
Missing data from template to view
I created a form and am trying to retrieve the data from the view so I can send it to an email. Once I render the page I get a 'keyerror'. I printed the values I am getting from the form and noticed I am not getting the 'phone_number' input. I'm trying to figure where is going the phone_number input Here's my code {% extends "base.html"%} {% load static %} {% block contenido %} <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Contact Section Form--> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <!-- * * * * * * * * * * * * * * *--> <!-- * * SB Forms Contact Form * *--> <!-- * * * * * * * * * * * * * * *--> <!-- This form is pre-integrated with SB Forms.--> <!-- To make this form functional, sign up at--> <!-- https://startbootstrap.com/solution/contact-forms--> <!-- to get an API token!--> <form id="contactForm" method="post"> {% csrf_token %} <!-- Name input--> <div class="form-floating mb-3"> <input name="full_name" class="form-control" id="full_name" type="text" … -
copy some column from a table to another table
guys I have made two models in Django. first model contains- id (primary key) name age address gender second model contains- id (primary key) name age college class What I am trying to achieve is every time I make entry in first model table it automatically copies name and age field from first model table to second model table. I have tried Foreignkey, OnetoOneField, but could not succeed. I am using Sqlite. -
How to run _icontains method on a foreignkey field in django
I am building a dummy E-commerce site. For this, I wish to build a staff portal where I can search for pending orders by a user's first name. I have made a foreignkey field on my model that I am referencing. But when I use the __icontains method in my views on user field, I get Related Field got invalid lookup: icontains error. I wish to return all orders that have been made by a user that have a certain searched string in their first name. My views.py: class delivery_staff_search_pending_orders(LoginRequiredMixin, generic.View): def get(self, *args, **kwargs): if self.request.user.groups.filter(name='Delivery_staff_admin').exists(): search_query = self.request.GET['query'] filter_form = PendingOrdersFilterForm() orders = Order.objects.filter(preproccessed=True, ordered=True, delivered=False) searched_pending_orders = orders.filter(user__icontains=search_query) context = { "filter_form": filter_form, "pending_orders_list": searched_pending_orders } return render(self.request, "staff/delivery/pending_orders.html", context) My Order model: user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) ref_code = models.CharField(max_length=20, default=1234) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey("BillingAddress", on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey("Coupon", on_delete=models.SET_NULL, blank=True, null=True) preproccessed = models.BooleanField(default=False) dispatched = models.BooleanField(default=False) delivered = models.BooleanField(default=False) Refund_requested = models.BooleanField(default=False) Refund_granted = models.BooleanField(default=False) Paid_price = models.FloatField(default=0) The user model is the standard django.contrib.auth.models user model -
Django-Filter: Method argument to filter two attributes
I created a model with a way to grant a credit with some attributes like customer id, amount of credit, result of the credit, due date, created date. for the purpose of the app, I should filter the credit's period of the validity. Then I create a method in the filter like this: period_of_validity = filters.BooleanFilter( method="period_of_validity_filter", help_text="Get the period of validity of the credit according to the remaining days to the due date", ) and the method is: def period_of_validity_filter(self, queryset, name, value): result = queryset.filter( Q(result=CreditResult.GRANTED) | Q(due_date__gt=datetime.date.today())) return result However, I am not sure if the two Q are correct in order to find the granted credits and the credits with a due date greater than equal today. I give thanks for your help. -
Access local vagrant VM through a Django app running locally
Context: I am playing around with Django and Vagrant and I would like to see if I can have them interact with each other where a Django app running locally can access a local Vagrant VM. I have a Django app that I'm running locally using python manage.py runserver and I have a Vagrant VM that is up and running somewhere on my local machine in path/to/local/vagrant/vm. I would like to ssh and/or execute commands on the aforementioned local Vagrant VM through the Django app. Is that such thing possible? If so, how? If not, then how can I achieve something similar where I can have a Django app interact with a local VM. -
Is it possible to have a OneToOneField in Django that's only null=True in one direction?
Is it possible to create a OneToOneField in Django that is only null=True in one direction? Ex: class Building(models.Model): ... class Roof(models.Model): building = models.OneToOneField(...) ... A building doesn't technically need to have a roof. Plenty of unfinished buildings don't have them. But you can't have a roof without a building. Also, a building can only have one roof, and a roof can only be on one building, hence OneToOneField. -
Why is my Django data migration from ForeignKey field to OneToOneField not working?
I have some models with a ForeignKey field that points to another model: class Specimen(models.Model): ... class ResultA(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) ... class ResultB(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) ... At some point, I realized that each specimen will only ever have zero or one of each type of result, so it probably makes sense to turn that into a OneToOneField. The plan is to: Create an additional specimen_new field that's a OneToOneField on each result Create a data migration that will move the data from the ForeignKey field to the OneToOneField field Delete the ForeignKey field Rename the new specimen_new OneToOneField to just specimen Update all the code references to use the new OneToOneField properly Step 1 was pretty simple: class Specimen(models.Model): ... class ResultA(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) specimen_new = models.OneToOneField(Specimen, on_delete=models.CASCADE, ...) ... class ResultB(models.Model): specimen = models.ForeignKey(Specimen, on_delete=models.CASCADE, ...) specimen_new = models.OneToOneField(Specimen, on_delete=models.CASCADE, ...) ... I'm stuck on step 2 - creating the data migration. Right now, it looks like this: from django.db import migrations def migrate_results(apps, schema_editor): # Get the model Specimen = apps.get_model('ahs', 'Specimen') # Update every specimen for specimen in Specimen.objects.filter(): for field in Specimen._meta.get_fields(): # Look for fields that … -
How to setup nginx to site to a Django app over https?
I have an application that I am running with multiple docker containers with a docker-compose file. Two main containers are django_container and nginx_container. I want to force using https for my application but unfortunately, my Nginx config doesn't seem to work. Basically, my gunicorn server seems to be running OK. I can see the http://django:8001 from inside the nginx_container, but I can't see http://example.com from inside it or outside. Here is the content of my Nginx config server { listen 80; server_name example.com; rewrite ^ https://example.com$request_uri? permanent; } server { listen 443 ssl; server_name example.com; ssl_certificate /etc/nginx/certs/example_com.crt; ssl_certificate_key /etc/nginx/certs/cert.key; access_log /log/nginx.access.log main; location / { proxy_pass http://django:8001; proxy_set_header X-Forwarded-Proto $scheme; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } What am I missing here? Thanks a ton! -
Django rest framework not refreshing template changes
I was trying to update my django rest framework browsable api template, initially trying to change the theme and afterwards changing the navbar branding text, but, after creating the rest_framework/api.html file for the first time, the changes got stuck and the initial changes will not either update nor delete. I've tried deleting the whole proj/app/templates/rest_framework directory, but the changes are still there. I also deleted my browser's cache and cloudflare's cache, restarted Apache 2, and even restarted the server. This is my app directory: website ├── __init__.py ├── admin.py ├── apps.py ├── locale │ └── (more folders) ├── models.py ├── static │ └── (more folders) ├── templates │ ├── anime │ │ ├── detail.html │ │ └── index.html │ ├── (here was the rest_framework directory with the api.html file) │ ├── footer.html │ ├── imports.html │ ├── navbar.html │ └── website │ ├── index.html │ └── welcome.html ├── tests.py ├── urls.py └── views.py My old api.html (the last version before editing) looked like this: {% extends "rest_framework/base.html" %} {% load i18n %} {% block bootstrap_theme %} <link rel="stylesheet" href="https://example.com/static/bootstrap/bootstrap.css" type="text/css"> {% endblock %} {% block branding %} <a class="navbar-brand" rel="nofollow" href="#"> My Project </a> {% endblock %} In the browsable … -
I am getting "Could not parse the remainder: '=="dashboard"' from 'section=="dashboard" error what could be the possible reason for this error?
this is my base.html. I tried replacing == with = .Also, I properly checked if I forgot closing tag but didn't found such problems -
Django Page loading error ?page=undefined
learning pagination and not understanding why page variable is undefined. I can hover over each page object and tool tip shows correct page=page#, each button is numbered correctly as well. This is the function from the view of the app: def projects(request): projects, search_query = searchProjects(request) results = 4 page_number = request.GET.get('page') if page_number == None: page_number = 1 paginator = Paginator(projects, results) try: projects = paginator.page(page_number) except PageNotAnInteger: page_number = 1 projects = paginator.page(page_number) context = { 'projects': projects, 'search_query': search_query, 'paginator': paginator } return render(request, 'projects/projects.html', context) The html code for pagination is as follows: <div class="pagination"> <ul class="container"> {% for page in paginator.page_range %} {% if page == paginator.number %} <li><a href="?page={{page}}" class="btn page-link btn--sub" >{{page}}</a></li> {% else %} <li><a href="?page={{page}}" class="btn page-link">{{page}}</a></li> {% endif %} {% endfor %} </ul> </div> when a page is clicked, the page does not refresh to the correct page or show the current page highlighted, the initial content(1st page) is displayed. When I print the values of the paginator attributes I can see the correct pages generated and objects referenced correctly. Just not understanding why the anchor {{page}} references are not being returned to the view on a GET event. This … -
How to fix the encode error in Django while trying to send an e-mail
Im trying to send an verification e-mail to a new registrated account in Django, but im getting an encode error that I dont know how to fix, please help me to fix it, so then I can succeffuly verify the account aaaaaaaaaaaaaa if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = xxxxx # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' my urls.py: path('register/', views.account_register, name='register'), my views.py: from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email_body = message email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active … -
Querying django models to include and exclude items
I currently have 2 models as such class Recipe(models.Model): account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.TextField(null=True, blank=True) slug = models.SlugField(null=False, blank=True, unique=True) image_path = models.ImageField(upload_to=MEDIA_URL, null=True, blank=True) description = models.TextField(null=True, blank=True) date_added = models.DateField(auto_now_add=True) class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, blank=True) quantity = models.CharField(max_length=10, null=True, blank=True) type = models.CharField(max_length=50, null=True, blank=True) I am trying to do a query where if I have a list of say 2 or more items, say ingredients = ["egg", "bacon", "rice"] That it returns to me only the recipes that have exactly egg, bacon, and rice, or less. I was able to do this in a hacky way, but it is really slow and not using the ORM correctly I feel. for i in ingredients: r = RecipeIngredients.objects.filter(ingredient__icontains=i) results.append(r) for result in results: for r in result: recipes.append(r.recipe) for r in recipes: recipeingredients = r.recipeingredients_set.all() for ri in recipeingredients: ingredient = ri.ingredient if ingredient not in ingredients: try: recipes.remove(r) except: print(r) print("end of recipe") Any help on how to make this a more correct query would be appreciated. -
How can i submit initial data in database while migrating in Django?
Info: I want to save the auth-group records while migrating the database in Django. the records which come from auth_groups.json. Maybe my question is similar with others but i don't understand the logic with auth_groups.json. I have multi tenant database but when i create a new tenant i want to be save with init. 0003_auto_20220525_2056.py # Generated by Django 4.0.4 on 2022-05-25 20:56 from django.db import migrations from django.core import serializers fixture_filename = 'fixtures/groups.json' def load_initial_data(apps, schema_editor): fixture = open(fixture_filename, 'rb') auth_group = apps.get_model('auth', 'Group') for obj in auth_group: obj.save() fixture.close() class Migration(migrations.Migration): dependencies = [ ('account', '0002_initial'), ] operations = [ migrations.RunPython(load_initial_data), ] auth_groups.json [ { "model": "auth.group", "pk": 1, "fields": { "name": "admin", "permissions": [] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "producer", "permissions": [] } } ] -
django. The manage.py is not working after migrating mysql table
I install mysql as my database in my django project. I did makemigration and migrate it on the django. After that I wanted to try to run the server, but the python manage.py is not working at all even if there is python stored in my computer. python_version_in_cmd I have the screenshot here where it shows no response at all but pip is responding. django This is my computer environment path computer enviroment path When I was installing mysql the mysql/python was failing, is that the problem? any hints? -
Cannot resolve keyword 'slug' into field. Choices are: id, location, profile_image, stories, twitter, user, user_id, website
I'm trying to create profile page for a user when I click on create profile instead of showing me the edit template that will allowed me to edit all these fields then it throws me an error like this: Cannot resolve keyword 'slug' into field. Choices are: id, location, profile_image, stories, twitter, user, user_id, website i want a user to be able to create profile. How can i solve this problem ? the urls: path('editprofile/<slug:slug>/edit', views.EditProfileView.as_view(), name='editProfile'), the models: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_image = models.ImageField(upload_to="avatars/") stories = models.TextField(max_length=500,blank=True, null=True) website = models.URLField(max_length=250, blank=True, null=True) twitter = models.URLField(max_length=250, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) the views: @login_required(login_url='login') def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = {'questions':questions, 'profiles':profiles} return render(request, 'profile.html', context) class EditProfileView(UpdateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'edit_profile.html' success_url = reverse_lazy('index') the profile template: <div class="container"> <div class="row"> <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a> </div> </div>