Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form error - cannot validate as input field is required
i'm trying to pass html5 date input (start and end dates) into django forms, the main goal being to query for orders according to the start/end dates specified by the user on the front-end. the user indicates the start and ends dates on the front-end, which are then passed into my django model and into an AJAX call. my current error is this: i can't append the start/end date to my form or enter the if form.is_valid() portion of my code. when i print(form.error), i get: <ul class="errorlist"><li>start_time<ul class="errorlist"><li>This field is required.</li></ul></li><li>end_time<ul class="errorlist"><li>This field is required.</li></ul></li></ul> i don't understand why i'm getting this error - a POST request was made and managed to retrieve my start and end dates: <QueryDict: {u'csrfmiddlewaretoken': [u'FDRiqkYiP6j8yOAMLfb0sMe8wC8Z0K57'], u'start_date': [u'2018-12-17'], u'end_date': [u'2018-12-20']}> - the specified fields clearly aren't empty. is it something wrong with my forms.py? would really appreciate some assistance. thanks! views.py method from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib import messages from django.utils import simplejson # JsonResponse from django.middleware.csrf import get_token from django.db.models import Count from django.views.generic import View from .forms import DateInput, DateForm from .models import Member, Driver, Order, Distance from collections import OrderedDict def date_input(request): if request.method … -
Django Rest Framework "NoReverseMatch at /" Error When Visiting Homepage
This error only happens when I add an argument to the RetrieveAPIView url like so: urlpatterns = [ path('newgame/', newGame, name='newgame'), path('gameboard<int:pk>/', GameBoardView.as_view(), name='gameboard'), path('findgame/', findGame, name='findgame') ] If I go to the gameboard URL with a valid ID everything works, but if I go to http://127.0.0.1:8000/ I get this: NoReverseMatch at / Reverse for 'gameboard' with no arguments not found. 1 pattern(s) tried: ['api/gameboard(?P<pk>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'gameboard' with no arguments not found. 1 pattern(s) tried: ['api/gameboard(?P<pk>[0-9]+)/$'] Exception Location: /home/calvin/.local/share/virtualenvs/Online-Chess-UxyP2_C1/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /home/calvin/.local/share/virtualenvs/Online-Chess-UxyP2_C1/bin/python3 Python Version: 3.8.5 Python Path: ['/home/calvin/Online-Chess/chess', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/calvin/.local/share/virtualenvs/Online-Chess-UxyP2_C1/lib/python3.8/site-packages'] Error during template rendering In template /home/calvin/Online-Chess/chess/templates/base.html, error at line 0 Reverse for 'gameboard' with no arguments not found. 1 pattern(s) tried: ['api/gameboard(?P<pk>[0-9]+)/$'] If I take out the <int:pk> from the gameboard URL everything works again. Here is the View: class GameBoardView(generics.RetrieveUpdateAPIView): permission_classes = ([IsAuthenticated]) serializer_class = GameBoardSerializer queryset = GameBoard.objects.all() Here are my main URLs, incase that is useful: urlpatterns = [ path('', home, name="home"), path('<int:game_id>', game, name="game"), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('api/', include('api.urls')), path('rest-auth/', include('rest_auth.urls')) ] All of the errors I have found from other people seem … -
Application labels aren't unique
Has anybody encountered the following error? Building simple django python blog application. traceback Any ideas as to what it correlates to would be appreciated. Have not found a solution as of yet. -
DjangoREST/React - Why is my frontend/backend token authentication system inconsistent?
Every API call sent to my API has a header with a Bearer token auth, this is verified when I look through my browsers network panel. The authentication system works, however, whenever I spin up my dev server and try to carry on from my previously logged-in session, my system blocks every request as a 401 Unauthorized with: "Invalid token header. No credentials provided." as a response. Which is false because I'm sending over a header with the access token? I can only get it working if I logout and log back in as a user. Here is my axios instance that I used to make calls to my API. import axios from 'axios'; const baseURL = 'http://127.0.0.1:8000/api/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 9000, headers: { Authorization: 'Bearer ' + localStorage.getItem('access_token'), 'Content-Type': 'application/json', accept: 'application/json',}, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'auth/token/' … -
How does the html button tag work with Django template?
This is a Django template where the user submits some data through a django form to create a new "topic". I want to ask why does the html button work and submit the data I want even though I didn't specify it's type (submit, reset, or button)? {% extends "learning_logs/base.html" %} {% block content %} <form action ="{% url 'learning_logs:new_topic' %}" method="post"> {% csrf_token %} {{form.as_p}} <button>Add Topic</button> <comment><-- why does this button still work?</comment> </form> {% endblock %} Heres the views.py, if you need it. def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(data = request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic') context = {'form':form} return render(request, 'learning_logs/new_topic.html',context) -
error while using sys.exit() in a django template with iframe
I am using a django based web application in python3. The logout method will redirect me to a different view and it will also call sys.exit("str") def logout(request): try: logger.info("Logging Out") del request.session['role'] del request.session['email'] del request.session['fullname'] del request.session["token"] session.close() sys.exit("bye") return redirect("/login") except Exception as e: logger.info("Exception : {}".format(e)) the above code was redirecting me as expected. Recently i introduced iframes in the template html, so that the pages are rendered in iframe when clicked from a side menu navigation <div class="sidenav"> <a href="lkpview" target="iframe1">About</a> <a href="logout" >Sign out</a> </div> <div class="main"> <iframe width="90%" height="300" name="iframe1"> </iframe> </div> Now if click on Sign out i am getting this error: A server error occurred. Please contact the administrator. [![enter image description here][1]][1] Not sure of this, and it did not occur before i introduced the iframe to the django template. Can anyone please help me here? Thanks -
Could not aquire lock for task using cron job + uwsgi + Django
This is my uwsgi.ini file, and also there are other parameters in this uwsgi.ini file. [uwsgi] unique-cron = 0 -2 -1 -1 -1 python manage.py custom-command1 unique-cron = 5 0 -1 -1 -1 python manage.py custom-command2 unique-cron = 10 -2 -1 -1 -1 python manage.py custom-command3 unique-cron = 20 -3 -1 -1 -1 python manage.py custom-command4 While the application is running perfectly everyday, but from the above jobs, 3rd cron job is getting failed everyday with below error, and the job runs every 3 hours per day Could not aquire lock for task. Exiting... kindly advise what could be the reason ? -
The view pages.views.contact didn't return an HttpResponse object. It returned None instead
please I'd really appreciate that anyone in the forum can give to me a hint with this issue in my app "pages" I do not know where is the issue, I have this error The view pages.views.contact didn't return an HttpResponse object. It returned None instead. Thanks in advance. ├── PagesProject │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── Pipfile ├── Pipfile.lock ├── db.sqlite3 ├── manage.py ├── pages │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── static │ ├── logo.jpg │ ├── main.css │ └── top_banner.png └── templates ├── 404.html ├── base.html ├── contact.html └── page.html views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from .models import Page from .forms import ContactForm def contact(request): submitted = False if request.method == 'POST': form: ContactForm = ContactForm(request.Post) if form.is_valid(): cd = form.cleaned_data # assert False return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request, 'contact.html', {'form': form, 'page_list': Page.objects.all(), 'submitted': submitted}) contact.html {% extends "page.html" %} {% block … -
Django: Exclude users in M2M
I want to exclude the Users that are inside the DocumentUsers table: from django.contrib.auth.models import User class DocumentUsers(models.Model): pnr = models.TextField() users = models.ManyToManyField(User) users = User.objects.exclude(username__in=[user for user in DocumentUsers.objects.all()]) Thank you for any suggestions -
django imageField returns False when I delete the image
I am using three imageFields in a form. It works well but when I use the (built-in) delete function("effacer") as shown is this image below and I save my form, I get "False" in my database... How can I remove totaly the path ("uploads/...") of the deleted image instead of getting "False" ? Thanks, Here is my model: class Announce(models.Model): photo1 = models.ImageField(upload_to='uploads/', blank=True) photo2 = models.ImageField(upload_to='uploads/', blank=True) photo3 = models.ImageField(upload_to='uploads/', blank=True) -
I am getting a None type for my request in serializer after Patch
I am making a test that partial updates or patch some fields in my Product model. I should be enable to update any fields in my Product model. In my serializer, I have a url builder from the request object. However, request is not passed on my serializer or it is a None type. Thus, I am getting an error: AttributeError: 'NoneType' object has no attribute 'build_absolute_uri' How do I pass a request to my serializer? def test_patch_products(self): data = { 'description': 'This is an updated description.', 'type': 'New' } ... ... response = self.client.patch('/data/products/1/', data=data, format='json') In my view: def partial_update(self, request, pk=None): product= get_object_or_404(Product, pk=pk) serializer = ProductSerializer(product, data=self.request.data, partial=True, ) if serializer.is_valid(): serializer.save(uploaded_by=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In my serializer: class ProductSerializer(serializers.ModelSerializer): uploaded_by= serializers.StringRelatedField() thumbnail = serializers.SerializerMethodField() class Meta: model = CaptureGroup fields = ('__all__') def get_thumbnail(self, object): request = self.context.get('request') # request is None here thumbnail = object.thumbnail.url return request.build_absolute_uri(thumbnail) # here is the url builder -
Scrapy Help: How can I get medical Centre data which medical are selected before make a payment.? this web automatically assign medical center
https://v2.gcchmc.org/book-appointment/ This is the website when I select country Bangladesh & city any one of this (Dhaka, Chittagong or sylhel) 3 cities are included this website, I currently trying to see which medical centre is selected.. when I fill up all information and submit then redirect the payment option after payment completed, automatically generates a pdf where is showing whose medical centre is appointed. Before making a payment how can I see which medical centre is selected..? Country Traveling To <select name="traveled_country" required="" id="id_traveled_country"> Select GCC country Bahrain Kuwait Oman Qatar Saudi Arabia UAE Yemen Success <div class="field medical-center-field medical-center-field-js disabled" style="display: block;"> Medical Center <select name="medical_center" id="id_medical_center" style="display: none;"> Select Medical CenterAuto assign <span class="info-icon"><i class="info circle icon"></i> Medical center has been assigned automatically</span></div> </div> -
Django: You are trying to add a non-nullable field 'slug' to post without a default; we can't do that
I'm trying to add slug so that the title of a post appears in the url but i get this message on console: You are trying to add a non-nullable field 'slug' to post without a default; we can't do that Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py models.py class Post(models.Model): title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) -
Having trouble setting Many-to-one relationships in django
I'm trying to rewrite my django models in order to solve some problems I found. I have 4 models: a Task, a Request, a Product and a Location. models.py class Location(models.Model): name = models.CharField(max_length = 255, unique = True) lat = models.FloatField() lon = models.FloatField() class Product(models.Model): name = models.CharField(max_length = 50, unique = True) class Request(models.Model): product = models.ForeignKey(to = Product, related_name = "product", on_delete = models.CASCADE) quantity = models.FloatField() task = models.ForeignKey(to = Task, related_name = "task", on_delete = models.CASCADE) class Task(models.Model): name = models.CharField(max_length = 50) priority = models.IntegerField() service_time = models.FloatField() start_location = models.ForeignKey(to = Location, related_name = "start_location", on_delete = models.CASCADE) end_location = models.ForeignKey(to = Location, related_name = "end_location", on_delete = models.CASCADE) task_type = models.CharField(max_length = 30) I'm currently strugling with the relationships. My main goal is to be able to make a POST request. Just like this one { "name": "task1", "priority": 1, "service_time": 1200, "start_location": { "name": "loc1", "lat": 1, "long": 1 }, "end_location": { "name": "loc2", "lat": 1, "long": 1 }, "task_type": "pickup & delivery", "requests": [ { "product": { "name":"Apples" }, "quantity": 1000 }, { "product": { "name":"Kiwis" }, "quantity": 2000 } ] } Some important points: I want to able … -
How to import a csv file from the admin side in django without the foreignkey column
For the moment I can import csv file using Django's import_export package. However I need to provide a csv with the id corresponding to my foreign key. Here is my modele.py : class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Cause(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True) def __str__(self): return self.name And here is admin.py : from import_export.admin import ImportExportModelAdmin # Register your models here. class CategoryAdmin(admin.ModelAdmin): list_display = ("name", ) class CauseAdmin(ImportExportModelAdmin): list_display = ("name",) pass admin.site.register(Category, CategoryAdmin) admin.site.register(Cause, CauseAdmin) If I want to import a csv containing the names of the causes I need to add a column with the id of the corresponding categories. However, I would like to be able to import a csv containing only the names of the causes and choose the category on the admin side. For the moment this is what it looks like when I import a csv file: I would like to know if it is possible using the import_export package that it looks more like this: (like when I add only one cause) Instead of the "Name" there would be as in the first screenshot " File to import " and the category could be … -
Web application with a lot of excel data
this is my first time posting here so excuse (or even correct if you would like) any mistakes I make in presenting my question and details. As my first development job ever I have been tasked to create a web application and I would greatly appreciate your opinion and insight on the way I have decided to approach this. There's no specific issue, I just want to make sure I start my career in the best way possible, being aware of course that mistakes are unavoidable in my first steps. I will present the requirements for the app, my current knowledge and the way I have thought to approach development Requirements: Web application with login functionality A considerable amount of data which has to be accessible in the form of dependent select options The data is in excel form and the tables have the following structure: table screenshot . It's basically 2 values, height and width, and to each combination of those two, corresponds a unique price. Some parts of the data could possibly have an extra variable, so it would be: height + width + colour corresponds to a unique price. Additionally not all combinations of these variables necessarily … -
ValueError at /brands/some-brand/ Cannot query Must be "Category" instance
So one of my filters in my category nav link is a list of brands. When you click the brand, it is supposed to take you to a similar page as brand but only with those specific products. Here is my models.py class Brand(models.Model): #category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:brand", kwargs={ 'slug': self.slug }) class Category(models.Model): #brands = models.ForeignKey(Brand, on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:category", kwargs={ 'slug': self.slug }) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True, related_name='category') #brands = models.ForeignKey(Brand, on_delete=models.PROTECT, null=True, related_name='brands') label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() is_active = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) This is the error I keep getting. Even when I uncomment the changes in my modules.py, I still … -
How do I attach a file to my django email project? Sending a HTML Template out with images as attachments
class createLot(LoginRequiredMixin,generic.CreateView): form_class = LOTForm model = LOT def form_valid(self,form): user = form.cleaned_data['user'] lot_nr = str(form.cleaned_data['lot_nr']) agent_nr = form.cleaned_data['agent_nr'] verkoper = form.cleaned_data['verkoper'] verkoper_sel = form.cleaned_data['verkoper_sel'] laai_datum = form.cleaned_data['laai_datum'] laai_gewig = form.cleaned_data['laai_gewig'] laai_qty = form.cleaned_data['laai_qty'] prys_kg = form.cleaned_data['prys_kg'] prys_kop = form.cleaned_data['prys_kop'] laai_strokie = form.cleaned_data['laai_strokie'] image = form.cleaned_data['image'] lot_info = { "lot_nr": lot_nr, "agent_nr": agent_nr, "verkoper": verkoper, "verkoper_sel": verkoper_sel, "laai_datum": laai_datum, "laai_gewig" : laai_gewig, "laai_qty" : laai_qty, "prys_kop": prys_kop, "prys_kg":prys_kg, "weegbrug": weegbrug, 'user': User, } subject = "Email" html_message = render_to_string('mailto/email2.html',lot_info ) plain_message = strip_tags(html_message) from_email = 'From <123@123.co.za>' to = ['to_email@123','to_email2123@123'] send_mail(subject, plain_message, from_email, to, html_message=html_message) self.object = form.save(commit = False) self.object.user = self.request.user self.object.save() return super().form_valid(form) I Know my forms and models are set up correctly I just cant seem to find a way to attach a file using this method of send_mail. Either it goes back to HTML format or it doesnt attach anything at all. -
How to save correct path to django image
I want render image in home page, but i can't specify to the correct path to it, when i upload image, it is saved as static/images/product_pic/filename but I need to save image with a custom path that I specify in the save function static/images/product_pic/customfilename. How can i specify a custom path in the database? my model: class Product(models.Model): name = models.CharField(max_length=40) price = models.FloatField() description = models.TextField(null=True) image = models.ImageField(null=True, default='placeholder.png', upload_to='static/images/product_pic') def __str__(self): return self.name def save(self): super().save() initial_path = self.image.path img = Image.open(initial_path) self.image.name = f'{self.name} - {self.id}.jpg' new_path = 'static/images/product_pic/' + self.image.name if img.height > 360 or img.width > 640: output_size = (360, 640) img.thumbnail(output_size) os.rename(initial_path, new_path) img.save(new_path) path in database: correct path to image: -
Django Form add class to div, input field and label
This is the html django form generated for an ImageField <div id="div_id_image" class="form-group"> <label for="id_image" class=""> Image </label> <div class=""> <input type="file" name="image" accept="image/*" class="clearablefileinput form-control-file" id="id_image"> </div> Now, I can write custom html code to customize this field. But, my use-case is just to add 3 classes, one for the outer div, one for the label and one for the input field itself. Is it possible to add these 3 classes in django form without writing any custom html code -
Scrapy Help: How can I get medical Centre data which medical are selected before make a payment.? this web automatically assign medical center [closed]
https://v2.gcchmc.org/book-appointment/ This is the website when I select country Bangladesh & city any one of this (Dhaka, Chittagong or sylhel) 3 cities are included this website, I currently trying to see which medical centre is selected.. when I fill up all information and submit then redirect the payment option after payment completed, automatically generates a pdf where is showing whose medical centre is appointed. Before making a payment how can I see which medical centre is selected..? Booking Appointment form Generated PDF Sample -
How to override formatmonth function of python HTMLcalendar?
I would like to override the HTMLcalendar of python. I am currently trying to do it like this: class CustomCalendar(HTMLCalendar): def formatmonth(self, theyear, themonth, w=0, l=0): """ Return a month's calendar string (multi-line). """ w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) s = s.rstrip() s += '\n' * l s += self.formatweekheader(w).rstrip() s += '\n' * l for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += '\n' * l return s I would like to add the month, day, and year to each day so that I am able to add an event listener to redirect to different Django URLs/views. How can I do that? Furthermore, I would like to highlight the selected day in the calendar with background color as well as today's day with a background color. How do I do that? Thanks a lot for your help. -
Django Custom Auth create Object with foreign key from another table AbstractBaseUser
I think the title is a little bit confusing, but nevermind. So I have created my models in MySQL Workbench, thats why I have (way -> not yet) a lot of different tables. I have a table called Account with a AbstractBaseUser and two other AbstractBaseUsers tables. The Account table has a onetoone field to the Residence. Now, if I create a User I want, that the user also can input the data for the Residence field and not only the foreign key. Here is my code: user/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from phonenumber_field.modelfields import PhoneNumberField from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class MyAccountManager(BaseUserManager): def create_user(self, username, firstname, lastname, email, verified, jobs, password=None): if not username: raise ValueError("Users must have a userid") if not lastname: raise ValueError("Users must have a lastname") if not email: raise ValueError("Users must have a email") user = self.model( username = username, firstname = firstname, lastname = lastname, email = email, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, firstname, lastname, email, password): user = self.model( username = username, firstname = firstname, lastname = lastname, email = email, password = password, … -
I'm getting this error when i try to send email with django ,can any body help me?
I'm trying to send an email from django using gmail smtp I've set insecure source ON in my account's setting also this is my settings.py file can anybody help me ? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com ' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER =' my email' EMAIL_HOST_PASSWORD = 'my password' and I'm getting this error in terminal for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed -
redirect to another page with information about the new user after creating this user in Django
I'm creating an appointment application using Django for register and non register user for the non register user the doctor needs to create a temporary user and add his information after that he can book an appointment for this user the best i can get to is this @login_required def create_appointment_non_register_P(request): form_user = UserEditForm() if request.method=='POST' : form_user = UserEditForm() if form_user.is_valid(): new_T_user = form_user.save(commit=False) form_user.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement2.html', {'user_form':form_user, }) @login_required def create_appointment_D(request): if request.method=='POST' : user = User() if request.user.is_doctor() or request.user.is_reception(): appointment = request.POST['type'] if appointment=='register patient': form_appointment = AppointmentForm_2() if form_appointment.is_valid(): form_appointment.save(commit=False) form_appointment.user = request.user form_appointment.end_time = form_appointment.start_time + timedelta(minutes=30) form_appointment.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement1.html', {'user_form':form_appointment, }) else: return HttpResponseRedirect(reverse("create_appointment_non_register_P")) return render(request, 'appointement/add_appointement1.html', {'user_form':form_user, }) else: return HttpResponseRedirect(reverse("create_appointment_P")) return render(request,'appointement/add_appointement_options.html') but the it did not create a new user and how after creating this user and redirect to a new page with the appointment form can book an appointment for him