Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid the use of ManytoMany field in Django?
I have the Role model. Account model take the reference from Role model using ManytoMany Field. But, I don't want to use manytomany field. It's necessary to not use ManyToMany field. Is anyone can suggest something better. I don't want to use use ManyToMany field because, since many to many are a Django feature and not database The given below model works fine with ManyToMany Field, I want the same with it. from django.db import models from django.db.models.fields import proxy from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.utils.translation import gettext_lazy as _ from django.core.validators import RegexValidator import uuid from django.utils import timezone import math from django.core.validators import MinValueValidator, MaxValueValidator ADMIN = 0 CUSTOMER = 1 SELLER = 2 DELIVERY_PARTNER = 4 class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' ROLE_CHOICES = ( (ADMIN, 'admin'), (CUSTOMER, 'customer'), (SELLER, 'seller'), (DELIVERY_PARTNER, 'delivery'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class UserManager(BaseUserManager): ''' creating a manager for a custom user model https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-a-manager-for-a-custom-user-model https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#a-full-example ''' def create_user(self, mobile_number, password=None): """ Create and return a `User` with an email, username and password. """ if not mobile_number: raise ValueError('Users Must Have an email address') … -
Why urlparse is merging "'>>" to my string? [closed]
Does anyone know why urlparse is merging >> to my query parameter? If I use https://example.com?state=YYYY&code=OOOO is working perfectly but when I use request.get_full_path is merging >> to query string. authorization_url = str(request.get_full_path) parsed_url = urlparse(authorization_url) print(parsed_url) #output: ParseResult(scheme='', netloc='', path="<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/", params='', query="state=YYYY&code=OOOO'>>", fragment='') -
building wheel for backports.zoneinfo
Trying to install a Django into my project. Installing from a requirements.txt file django>=4.1.0,<4.2.0 djangorestframework pyyaml requests django-cors-headers here is a stacktrace of the error creating build/temp.macosx-10.14-arm64-cpython-38/lib clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -iwithsysroot/System/Library/Frameworks/System.framework/PrivateHeaders -iwithsysroot/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/Headers -arch arm64 -arch x86_64 -Werror=implicit-function-declaration -I/Users/brendanahern/dev/drf/venv/include -I/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/Headers -c lib/zoneinfo_module.c -o build/temp.macosx-10.14-arm64-cpython-38/lib/zoneinfo_module.o -std=c99 lib/zoneinfo_module.c:1:10: fatal error: 'Python.h' file not found #include "Python.h" ^~~~~~~~~~ 1 error generated. error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for backports.zoneinfo Successfully built pyyaml Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects I am using a Mac with an M1 chip. Answers on a similar question suggested that the error came from numpy and I needed to install it differently due to me using an m1 chip, but did fix the issue. -
django.db.utils.ProgrammingError: relation "core_country" does not exist
This is a minimal example, here's the project structure, just run startproject and startapp and update the modules below missing-table ├── README.md ├── core │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── missing_table │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── static └── templates forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from core.models import Country class SignUpForm(UserCreationForm): country = forms.ChoiceField( choices=enumerate(Country.objects.values_list('name', flat=True)), label='' ) models.py from django.contrib.auth.models import User from django.db import models class Country(models.Model): name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=2, null=True, unique=True) dial_code = models.CharField(max_length=8, null=True) views.py from core.forms import SignUpForm and add core to INSTALLED_APPS in settings and that's it. You should get the error below which I'm getting on macOS 13.1, django 4.1.4, python 3.11.1. No matter what I run (runserver, makemigration, migrate, migrate core, ...), I get the same error. Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: no such table: core_country … -
Is it possible to add more fields to admin/auth/user?
models.py class UserProfile(User): bio = models.TextField(blank=True, null=True) pfp = models.ImageField(verbose_name='Profile Picture', blank=True, null=True, upload_to="images/profile") forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control", "placeholder":"example@example.com"})) first_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) pfp = forms.ImageField(required=False, widget=forms.FileInput(attrs={"class":"form-control"})) bio = forms.CharField(required=False, widget=forms.Textarea(attrs={"class":"form-control", 'rows':5, "placeholder":"Write something about yourself..."})) class Meta: model = UserProfile fields = ['first_name', 'last_name', 'username', 'email', "pfp", "bio"] When creating the user, the two newly added fields (bio and pfp) are not being saved in admin/auth/user, so my question is, is it possible to add those fields to the admin users database? -
axios cannot get only response of base64 but can get the others data
First, I sent image path from react to Django by using axios of POST method. Next, I edited image in Django, and returned edited image that were converted into base64 to react. like this. /* this is view.py in Django */ class SquareCognitionSet(viewsets.ViewSet): @action(methods=['POST'], detail=False, name='Edit image') def show(self, request): input = request.data['input'] edited_image = edit.main(input) // my user-defined function. return base64 after edit image. data = {"message": "Got base64", "base": edited_image, "type": imghdr.what(input)} return Response(data=data) No problem so far. Promlem is from here. I cannot get only base64 data of response that was sent from Django. However, axios could get response from Django. I confirmed console.log() /*this is react*/ useEffect(()=>{ async function check(ImagePath: string) { window.electronAPI.server_on(); // electron starts server to work axios await axios.post("http://127.0.0.1:8000/ImageEdit/edit/", { input: ImagePath // input value of image path }) .then((response)=>{ **console.log("success: ", response); <-- here, I confirmed response** }) this is result of console.log(). Then I run console.log("base64: ", response.data.base); However, nothing is shown. Even the text of "base64: " is disappear. What i tried. I tryed whether I can take out the others value sent from Django. I added value {"message": "Got base64"} in response of Django. Then, I take out value … -
Keycloak change dervied key size
I'm trying to import passwords from Django to Keycloak. They both use the pbkdf2 algorithm, but Django uses a key length of 256 bits and Keycloak uses 512 bits. Therefore the password validation doesn't work. Is there any way to change the key length in the settings. The documentation doesn't mention anything about environment variables or settings. I only found, the constant DEFAULT_DERIVED_KEY_SIZE in the Pbkdf2PasswordHashProvider class. To change this value I believe I have to build Keycloak on my own, which I would prefer not to do. Or is there any other way to rehash the passwords without having the users password. Maybe it is possible to add another Pbkdf2PasswordHashProvider with the changed DEFAULT_DERIVED_KEY_SIZE and then selecting this provider in the settings, so I can still use the 512 version, after all users switched to the 512 bits and then I can deprecate the 256 provider. -
server Python Django
Как принять данные с килента с помощью Post запроса (Логин, пароль, почту) с последующей записью в базу данных для использования при входе Использовал это но не до конца понимаю правильно или нет, скорее всего нет так как в базу данных ничего не записывается #Views.py class Reqs: def __init__(self, user, password, email): self.user = user self.password = password self.email = email class ReqsEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Reqs): return { "user": obj.user, "password": obj.password, "email": obj.email, } return super().default(obj) def api_response(request): user = request.POST.get("user") password = request.POST.get("password") email_ = request.POST.get("email") data = Data(user, password, email_) data.save() try: return HttpResponse(data, safe=False, encoder=ReqsEncoder) except: return HttpResponse("G") -
Is there a way to make faster requests from django using APIKey or auth check_password?
I have django rest_framework app, and I implemented the hasApiKey approach to restrict the access to my views methods, what is happening is the requests taking from 500 ms till 800 ms to be processed, when I remove the hasAPiKey the requests taking 20 ms to be handled, which is so much diffrence. how can I improve the speed of my requests in this case, even I tried to implement my own ApiKey using make_password, check_password from auth, and I had the same problem, hashing is slowing down the app. any recomendations? thanks! I tried to implement my own ApiKey using make_password, check_password from auth, and I had the same problem, hashing is slowing down the app. -
Trying to deploy a React app with seperate Django backend
Trying to deploy a React/Django website I have created a web applications with a seperate front and backend(React/Django) and ive never deployed either of them. I need it to be available on the internet for a school presentation. I have a vps with ubuntu and plesk running on it. I know how to run build the react app using plesk but i dont know how to add the django backend to it in a way they can connect. Help would be much appreciated. They use Axios with http only cookies to send data front to back. I tried creating a new domain for the react app within plesk. Frontend works and has got a tempory https/ssl protected domain. But dont know how to host the django backend on the same server in a way it can reach the django backend. -
How can I find all the invoices that has at least 5 transactions and all the latest 5 transactions are in status 'paid'?
class ChargeOverInvoice(models.Model): id = models.CharField(db_column='Id', max_length=18, primary_key=True) created_date = models.DateTimeField(db_column='CreatedDate', auto_now_add=True) class ChargeOverTransaction(models.Model): name = models.CharField(db_column='Name', max_length=80, verbose_name='Transaction #', default=models.DEFAULTED_ON_CREATE, blank=True, null=True) chargeover_invoice_id = models.CharField(db_column='ChargeOver_Invoice_ID__c', max_length=255) customer = models.ForeignKey(Account, models.DO_NOTHING, db_column='Customer__c') invoice = models.ForeignKey(ChargeOverInvoice, models.DO_NOTHING, db_column='ChargeOver_Invoice__c', blank=True, null=True) status = models.CharField(db_column='Status__c', max_length=255, verbose_name='Status') created_date = models.DateTimeField(db_column='CreatedDate', verbose_name='Created Date') I can get the result if it was about filtering within dates like this ChargeOverTransaction.objects.filter(status='Failed (decline)', created_date__lte=now()-relativedelta(days=35)).values('customer', 'invoice', 'chargeover_invoice_id').annotate(total=Count('id')).filter(total__gte=5) But not sure how can I get the latest 5 and add validation on them. -
How to pass database credentials securely inside docker container using Gitlab cicd?
Unable to securely pass database credentials inside a docker container in order to connect Django to Postgresql using gitlab cicd. I've added environment variables to the gitlab cicd settings. However,this method is not working -
How to compare a two table values in django using filter
def count_time(request): sp = Specific_product.objects.filter(boolean=False) #I need to compare the sp product and product table name using this method products = Product.objects.all().filter(name={{sp.product}}) stu={ "pro_d":sp,'products': products,'purchases':purchases } return render(request, 'mf_ta/product_status.html', stu) #I need to compare the row values of Specific_product table (product) and Product table (name) using the sp.product. How can I satisfy this condition I'm getting this error AttributeError at /count_time/ 'QuerySet' object has no attribute 'product' Request Method: GET Request URL: http://127.0.0.1:8000/count_time/ Django Version: 4.0.7 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'product' Exception Location: C:\Users\Admin\PycharmProjects\pythonProject1\invention_on_macroalgae\manufacturing_team_app\views.py, line 56, in count_time Python Executable: C:\Users\Admin\PycharmProjects\pythonProject1\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\Admin\PycharmProjects\pythonProject1\invention_on_macroalgae', 'C:\Users\Admin\PycharmProjects\pythonProject1', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python39', 'C:\Users\Admin\PycharmProjects\pythonProject1\venv', 'C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages'] Server time: Mon, 26 Dec 2022 03:54:39 +0000 -
AttributeError: 'PostsTranslation' object has no attribute 'created_at'
I am using django-parler for model translation, but getting error when creating object, I guess I understand my problem but cannot find solution. Here I have abstract class which I use from other models models.py class TimeStampedModel(TranslatableModel): created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Posts(TimeStampedModel): name = models.CharField(max_length=255) translations = TranslatedFields( slug = models.SlugField( max_length=255, db_index=True, unique_for_date='created_at' ), ) AttributeError: 'PostsTranslation' object has no attribute 'created_at' I am getting this error because of using unique_for_date='created_at' What can I do in this situation ? -
Email error: Message is not sending to the email instead it is printing in the terminal
When I am registering as a new user or want to change my password, then the Message which is needed to be sent to the email is showing in the terminal instead. Here is the terminal picture: enter image description here Here is the views.py function. from aiohttp import request from django.contrib.sites.models import Site from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib import messages from companies.models import Company from accounts.roles import UserRole # User mode from .models import CustomUser from domains.models import Domain from dashboard.models import MarketingHome, SliderHome # Custom forms from .forms import PublicCustomUserChangeForm, CustomChangePasswordForm from django.contrib.auth import views as auth_views from django.shortcuts import resolve_url from allauth.account.views import SignupView, LoginView @login_required def change_password_user(request): company = CustomUser.get_company(request.user) if request.method == "GET": form = CustomChangePasswordForm(request.user) context = { 'form': form, 'company': company } return render(request, 'account/change_password_user.html', context) else: form = CustomChangePasswordForm(request.user, request.POST) if form.is_valid(): form.save() # update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') return redirect('account_change_password_user') else: messages.error(request, form.errors) return redirect('account_change_password_user') here is the registration function: class AccountSignupView(SignupView): template_name = "account/signup.html" def get_context_data(self, **kwargs): current_site = self.request.META['HTTP_HOST'] context = super(SignupView, self).get_context_data(**kwargs) context = { 'slider': SliderHome.objects.filter(domain_site__domain__contains=current_site, is_active=True), # 'current_domain': Domain.objects.filter(site__domain__contains=current_site).first() } return context account_signup_view = AccountSignupView.as_view() -
How to deploy Docker image from ECR to Elastic Beanstalk
I pushed the image of my django project to AWS ECR and now I need to deploy it to AWS Elastic Beanstalk. Now I have an application in EB with Docker platform and the sample app. In software configuration I added DOCKER_IMAGE_URL and set the value as the ECR image URI and after updating I'm still redirected to the sample app Wondering what I'm doing wrong or is that even the right way of deploying a django app to EB docker platform. -
Django - My parent id is setting as 0 for every class
My state id is also storing the parent id as 0. I want my country to store parent id as 0 and parent id of state should be the id of country like this: Idk whats wrong i tried every possible solution i knew. models.py class customer_location(models.Model): parent_id=models.IntegerField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) class Meta: db_table="customer_location" def __str__(self): return self.name class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() self.parent_id = 0 super().save(*args, **kwargs) class State(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) views.py def add_customer_location(request): if request.method == 'POST': form = CustomerLocationForm(request.POST) if form.is_valid(): country = form.cleaned_data['country'] state = form.cleaned_data['state'] country_obj = Country(name=country) country_obj.save() state_obj = State(name=state, parent_id=country_obj.id) state_obj.save() return redirect('success') else: form = CustomerLocationForm() return render(request, 'add_customer_location.html', {'form': form}) def success_view(request): return render(request, 'success.html') -
migration error django.db.utils.DatabaseError
File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "corsheaders_corsmodel" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\kice\flask\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\kice\flask\venv\lib\site-packages\django\db\backends\utils.py", line 79, in _execute with self.db.wrap_database_errors: File "D:\kice\flask\venv\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\kice\flask\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\kice\flask\venv\lib\site-packages\djongo\cursor.py", line 59, in execute raise db_exe from e django.db.utils.DatabaseError -
How to update the front-end automatically if the back-end API data value changes in Django/Flask
If there is a field value 10 and after 20 mins it is updated to become 11. Below is the link I found a solution using Vue.js but is there a way to achieve this in Django/Flask.? Tried using Vue.js but need a solution in Django. -
How to load images from django views to a html template using loops
I've just started learning django and have a problem loading images using loops. In models.py I created a class called Pictures In views.py I created 3 instance of the class(Pictures) where img attribute is set to 3 different image names stored in the static folder. Now, I got stuck in loading the images in the template using for loop. apart from img attribute, I also created other attributes. These are the name and image description both of type string and they load just fine when rendered in the template using for loop. My question is what should I put in inside the img html tag to load these 3 different images using for loop? Initially, I was using the syntax below to load images directly from the static folder. <img src="{% static 'img/image-name.jpg' %}" alt="" width="250" height="250"> Now, I want to load the names from the img attribute and for each iteration, I want each of the three different images to load in the template each loop. Now I am not sure what to put inside the src="???". what i have so far and its working: {% for image in images %} <li> <img src="{{image.img}}" alt="" width="250" height="250"> <!-- I … -
TemplateDoesNotExist at/index.html
enter image description here i have tried so many options but my error not resolved please Help -
How to customize `bootstrap_form` fields
Given the form below from django import forms from django.forms import Form class SettingsForm(Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'First name'} ), label='', ) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'Last name'} ), label='', ) username = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'Username'} ), label='', ) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'Email'} ), label='', ) which is rendered using: <form method="post"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-success">{{ form_title }}</button> </form> What do I need to change to have first name, last name on the same line? So far I tried: <form method="post"> {% csrf_token %} {% bootstrap_field form.first_name %} {% bootstrap_field form.last_name %} <button class="btn btn-success">Update</button> </form> but when I submit the form using the button, it looks like it doesn't link it to the form. The view is obtained through a FormView subclass SettingsView. When the submit button is clicked, SettingsView.form_valid is never called unless the form is invoked as bootstrap_form form. -
ERD to django models ? Many to many relatioship with attribut
How to get django models of this ER diagram ? I don't understand how to write a model for this ER diagram View ER diagram -
502 gateway error | sentence-transformer package not working correctly
Hello I'm trying to solve this problem from last 5days if anyone know the solution please reply. My website is working properly but one page giving 502 gateway error on post request where i used sentence transformer package the code is working properly on local server but not working on nginx live server Nginx error.log file giving this error For that page 2022/12/26 07:21:57 [error] 2197#2197: *2 upstream prematurely closed connection while reading response header from upstream, client: 106.211.97.247, server: 54.199.217.173, request: "POST /admin/scaning_signature HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/scaning_signature", host: "54.199.217.173", referrer: "http://54.199.217.173/admin/get_signature" -
Django I cannot send the data to the database
I wanna create a appointment system but its not working now. I'dont have a error actually i just have a error and it's coming from views.py (messages.warning(request,"ERROR!")). When i opened the page its coming anyway i just wanna send my informations. models.py: I created models but im not sure for policlinic and doctor because it doesn't seems like charfield text. It's a option field in HTML. class Randevu(models.Model): STATUS = ( ('New', 'Yeni'), ('True', 'Evet'), ('False', 'Hayır'), ) policlinic=models.ForeignKey(Policlinic,on_delete=models.CASCADE) user=models.ForeignKey(User,on_delete=models.CASCADE) doctor=models.ForeignKey(Doctors,on_delete=models.CASCADE) phone = models.CharField(max_length=15) email = models.CharField(max_length=50) date=models.DateField(null=True) time=models.TimeField(null=True) payment= models.CharField(max_length=50) insurance= models.CharField(max_length=50) note=models.TextField(max_length=200) status = models.CharField(max_length=10, choices=STATUS,default='New') ip=models.CharField(max_length=20,blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def str(self): return self.user.username class AppointmentForm(ModelForm): class Meta: model=Randevu fields=['phone','email','date','time','payment','insurance','note'] views.py: def randevu(request): setting=Setting.objects.get(pk=1) policlinic=Policlinic.objects.all() doctor=Doctors.objects.all() context={'setting':setting ,'doctor':doctor,'policlinic':policlinic} if request.method=='POST': form=AppointmentForm(request.POST) if form.is_valid(): current_user=request.user data=Randevu() data.user_id=current_user.id data.phone=form.cleaned_data['phone'] data.email=form.cleaned_data['email'] data.date=form.cleaned_data['date'] data.time=form.cleaned_data['time'] data.payment=form.cleaned_data['payment'] data.insurance=form.cleaned_data['insurance'] data.note=form.cleaned_data['note'] data.ip=request.META.get('REMOTE_ADDR') data.save() messages.success(request,"DONE! :)") return render(request,'randevu.html',context) messages.warning(request,"ERROR!") return render(request,'randevu.html',context) urls.py urlpatterns = [ path('randevu',views.randevu,name='randevu') ] randevu.html <!-- MAKE AN APPOINTMENT --> <section id="appointment" data-stellar-background-ratio="3"> <div class="container"> <div class="row"> <div class="col-md-6 col-sm-6"> <img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt=""> </div> <div class="col-md-6 col-sm-6"> <!-- CONTACT FORM HERE --> <form id="appointment-form" role="form" action="{% url 'randevu' %}" method="post"> <!-- SECTION TITLE --> <div class="section-title wow …