Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run a background job every few seconds using django
I would like to know how to execute a function or file every few seconds using django so that I can populate my database with data obtained from this function call. I need a function to be executed every 5 seconds, this function will scrape a website and save its information into my database, this information will be used by one of my template views to generate a plotly graph. I've read about Celery and async stuff but couldn't figure out a way to put this into practice. If someone answers this, please tell me where should I put this job file in my django project or if I should just add a function to an existing file. -
Media path for app in django
I am uploading files in my django project and I need an efficient method to save them. Currently I am using the below lines in settings.py to create media folder in my root directory where I save the files. ENV_PATH = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(ENV_PATH, 'media/') But I want to save the files inside the app directory. Is it possible to find the path to my app directory? Is it possible and how should I change the above lines to accomplish it? Is it a proper method to add the media files into the app directory or are they stored in the root project directory ? which is the best standard here? -
Celery eventlet worker threads using too many database connections
I have 2 celery workers which pool via eventlet, config is below: celery multi start w1 w2 -A proj -l info --time-limit=600 -P eventlet -c 1000 When running more than 100 tasks at a time, I get hit by the error: OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections I'm running on PostgreSQL with max. connections set at the default of 100. From what I read online, I thought worker threads in the pools would share the same DB connection. However, mine seem to try and create one connection per thread, which is why the error occurs. Any ideas? Thanks! -
How to apply indexes for searching
There a lot of objects in DB so searching in Admin is extremely slow. I have these models defined: class Log(models.Model): message = models.TextField(blank=True, null=True) user = models.ForeignKey(AUTH_USER_MODEL, null=True, blank=True) class LogEmail(models.Model): log = models.ForeignKey(Log) email = models.CharField(max_length=350, db_index=True) site = models.ForeignKey('sites.Site') and here's my ModelAdmin: class LogAdmin(admin.ModelAdmin): search_fields = ('logemail__email',) So, I have index for email field in LogEmail and I guess FK indexes are created by default. How can I speed this thing up? I tried adding index_together, like: class LogEmail(models.Model): log = models.ForeignKey(Log) email = models.CharField(max_length=350, db_index=True) site = models.ForeignKey('sites.Site') class Meta: index_together = ( ('log', 'email'), ) But I didn't notice any difference. -
Can you override a model function for factory_boy?
I'm using Factory boy for my models. Another model has a ForeignKey to it, and the first obj of that model is used for string representation of the model. Example structure: class A(models.Model): ... def __str__(self): return self.reverseForeignKey_set.first().name class AFactory(factory.django.DjangoModelFactory): class Meta: model = models.A some_attribute = factory.RelatedFactory( ReverseModelFactory, 'a', ) But when I use factory_boy to create, it gives me this error: Traceback (most recent call last): File "/home/rahul/Documents/projects/healbot_current/healbot/functional_tests/tests.py", line 21, in setUp factories.AFactory.create() File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/base.py", line 623, in create return cls._generate(True, attrs) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/base.py", line 554, in _generate results[name] = decl.call(obj, create, extraction_context) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/declarations.py", line 624, in call return factory.simple_generate(create, **passed_kwargs) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/base.py", line 709, in simple_generate return cls.generate(strategy, **kwargs) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/base.py", line 676, in generate return action(**kwargs) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/base.py", line 622, in create attrs = cls.attributes(create=True, extra=kwargs) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/base.py", line 449, in attributes utils.log_repr(extra), File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/factory/utils.py", line 142, in log_repr return compat.force_text(repr(obj)) File "/home/rahul/Envs/healbot/lib/python3.6/site-packages/django/db/models/base.py", line 588, in __repr__ u = six.text_type(self) File "/home/rahul/Documents/projects/healbot_current/healbot/diagnosis/models.py", line 57, in __str__ return self.reverseForeignKey_set.first().name AttributeError: 'NoneType' object has no attribute 'name' Is there something I can do to get around this? Like override the str method on model A just for factory_boy? -
Django Rest Framework - can save foreign key with number value
I try to serialize and save following json { "start": "2017-12-12", "end": "2017-12-12", "has_refund": false, "room": { "key": 0 }, "reserved_days": [ { "date": "2017-12-12", "price": "2", "paymentMethod": "3" }, { "date": "2017-12-13", "price": "2", "paymentMethod": "3" } ], "check_in_time": "14:00", "check_out_time": "12:00", "guest_name": "Ivan", "payed": false } SERIALIZERS class DaySerializer(serializers.ModelSerializer): class Meta: model = Day fields = [ 'date', 'price', 'paymentMethod', ] class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = [ 'key', ] class ReservationSerializer(serializers.ModelSerializer): room = RoomSerializer() reserved_days = DaySerializer(many=True) class Meta: model = Reservation fields = [ 'start', 'end', 'check_in_time', 'check_out_time', 'reserved_days', 'room', 'has_refund', 'payed', 'guest_name', 'reservation_number', ] def create(self, validated_data): day_data = validated_data.pop('reserved_days') room = validated_data.pop('room') reservation = Reservation.objects.create(**validated_data) existing_room = Room.objects.get(key=room['key']) reservation.room = existing_room reservation.save() for day in day_data: day, created = Day.objects.get_or_create(date=day['date'], price=day['price'], paymentMethod=day['paymentMethod']) reservation.reserved_days.add(day) return reservation MODEL class Day(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) price = models.FloatField() paymentMethod = models.CharField(max_length = 200) def __unicode__(self): return str(self.date) class Room(models.Model): name = models.CharField(max_length = 200, null=True) key = models.AutoField(primary_key=True) def __unicode__(self): return self.name class Reservation(models.Model): start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False) end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False) check_in_time = models.TimeField(verbose_name='Время заезда', blank=False) check_out_time = models.TimeField(verbose_name='Время выезда', blank=False) has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True) payed = models.BooleanField(verbose_name='Оплачено', … -
Add object with pre-populated fields
Im trying to create a form to add new objects in django. The scenario is as follows.. Imagine that I have an object, lets call it A and another one, called B. They are different objects, of different classes. However, object B has a fill called object_A. So, object B depends of object A. I need to create a form in django to add a new object B, but before hand I need to find an object A and use it to populate the object_A field. My question is, how to creates a new object B with some pre-populated fields from A? The steps that Im trying to 1) Get the object A (the obj A pk can be gathered from the URL) and instantiate it. - Done. 2) Create a new object B, populate some fields using object A and others from a Form 3) Validate and submit/save the new object B Can anyone help me on this? Thanks in advance, Artur Baruchi -
How to setup auto caching for django?
I set cache for a view with cache_page decorator. But it doesn't work as I expected. Cache is setting when I am making a query. I want to setup auto caching without need to make a query. This is my configuration in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'OPTIONS': { 'MAX_ENTRIES': 2000 } } } Now I am trying to create some script for making queries automaticly. But I think it will be not efficiently for many cached pages. So I need help. -
Updating list_filter fields in realtime as I select field values - Django
So I'm working on this personal project in which I have two categories, a main one which is more general and a subcategories filter. An example would be main_category=smartphone, sub_category=samsung_phones. My class in models.py would be: class Products(models.Model): product_name = models.CharField(max_length=20) main_category = models.CharField(max_length=50) sub_category = models.CharField(max_length=50) And my class in admin.py would be: class ProductsAdmin(ImportExportModelAdmin): ... list_filter = ['main_category', 'sub_category'] ... Now what I wanna do is that, in my /admin/ page, I want to change the contents of 'sub_category' filter -in realtime- and according to what I selected in 'main_category'. Is this possible? Because right now it really doesn't do anything other than taking space so having a main_category filter in itself is useless. -
Django+Heroku+Python+Gunicorn deployement Error R14 (Memory quota exceeded) error
I have deployed my Django application on Heroku, but when I'm accessing my application then it gives me "Error R14 (Memory quota exceeded)" error continuously. I tried to deploy the application with normal and with Gunicorn. Let me share my Procfile This is with Gunicorn web: newrelic-admin run-program gunicorn app.wsgi -b "0.0.0.0:$PORT" -w 9 -k gevent --max-requests 250 scheduler: python manage.py celery worker -B -E --maxtasksperchild=1000 This is without Gunicorn web: bin/start-pgbouncer-stunnel newrelic-admin run-program waitress-serve --connection-limit 2000 --channel-timeout=600 --port=$PORT app.wsgi:application worker: bin/start-pgbouncer-stunnel newrelic-admin run-program celery -A bidcattle worker -E -B --maxtasksperchild=1000 -c1 App gets deployed successfully from both options I get the following error continuously in some resources of the application. Error R14 (Memory quota exceeded) I have web Standard-2x-dynos and statndard-1x-dynos for the worker. Please let me know where I'm going wrong. Thanks -
Caching responses in DRF
I have a REST API and some of the endpoints take a significant time to generate the responses, so I want to add some response caching and etag support. I have looked at the conditional response implementation in Django and at both response caching and conditional response in DRF extensions package. The problem I am having is that my data changes very frequently on one side, but is also heavily segregated, so if something changes in the response to user A calling endpoint X, nothing might change for users B, C and D calling the same endpoint. Since my data changes often, if I invalidate all responses on every change, I will never hit cache. The endpoints in question all generate lists of JSON objects, so the question is how can I only invalidate cached responses that contain a changed object rather than invalidating all of them? -
Django correct way of extending app
on a geonode (django) site an app exists which displays maplayers by a certain URL request: urls.py: url(r'^(?P<layername>[^/]*)$', 'layer_detail', name="layer_detail"), https://github.com/GeoNode/geonode/blob/master/geonode/layers/urls.py#L37 views.py: def layer_detail(request, layername, template='layers/layer_detail.html'): layer = _resolve_layer( request, layername, 'base.view_resourcebase', _PERMISSION_MSG_VIEW) https://github.com/GeoNode/geonode/blob/master/geonode/layers/views.py#L223 Demo: http://demo.geonode.org/layers/hr1%3Astates_1 Question: I´d like to extend the app to also call layers by their id. To not change the layer app I´ve created a new app called lid which takes the id, get´s the needed name from the layer model and redirects the request: urls.py url(r'^(?P<layerid>[^/]\d+)$', views.index, name='index'), views.py from django.http import HttpResponse from django.shortcuts import redirect from geonode.layers.models import Layer def index(request, layerid): obj = Layer.objects.filter(id = layerid) return redirect('/layers/'+ obj[0].typename) Unfortunately to get this working I´ve had to extend geonode main urls.py to catch the request before anything else: url(r'^layers/(?P<layerid>[^/]\d+)$', include('geonode.lid.urls')), https://github.com/GeoNode/geonode/blob/master/geonode/urls.py Is this the correct way to implement the redirect? Or is there a better way how to extend layers/views.py? thanks! -
django file upload doesn't work
Im working on web app project for study. I have a problem with file upload. It works for an admin, but for regular user files don't save. It must be a problem with mu views.py or template html forms.py class DocumentUpload(forms.ModelForm): class Meta: model = Form fields = ('file',) models.py class Form(TimeStampedModel, TitleSlugDescriptionModel): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=512) is_final = models.BooleanField(default=False) is_public = models.BooleanField(default=False) is_result_public = models.BooleanField(default=False) file = models.FileField(null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('form-detail', kwargs={'slug': self.slug}) views.py def create_form(request): if request.method == 'POST': user = request.user data = ParseRequest(request.POST) print(data.questions()) print(data.form()) parsed_form = data.form() parsed_questions = data.questions() # tworzy formularz o podanych parametrach formfile = DocumentUpload(request.POST, request.FILES or None) if formfile.is_valid(): form = formfile.save(commit=False) print(form) form.author = user form.title = parsed_form['title'] form.is_final = parsed_form['is_final'] form.is_result_public = parsed_form['is_result_public'] form.description = parsed_form['description'] form.save() # zapisuje pytania z ankiety wraz z odpowienimi pytaniami for d in parsed_questions: question = Question(form=form, question=d['question']) question.save() # dla kazdego pytania zapisz wszystkie opcje odpowiadania for opt in d['options']: option = Option(question=question, option=opt) option.save() return render(request, 'forms/form_form.html', {}) else: form = DocumentUpload() return render(request, 'forms/form_form.html', {'form': form}) create_form.html {% block content %} <form method="post" id="form" enctype='multipart/form-data'> {%csrf_token %} <div class="form-group"> {% … -
Django - Iterate over queryset and add static values
In the following queryset I am filtering planned hours per week (displayval is my week in this queryset) by employee. I would like to add an item for planned hours = 0 when the employee has no hours planned for a week I'm filtering by. What's the easiest way to achieve this? def DesignHubR(request): emp3_list = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').filter(businessunit='a').filter(billinggroup__startswith='PLS - Project').filter(Q(displayval=sunday2)|Q(displayval=sunday)).annotate(plannedhours__sum=Sum('plannedhours')) emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list) context = {'sunday': sunday, 'sunday2': sunday2, 'emp3': emp3} return render(request,'department_hub_ple.html', context) -
Apache Django configuration permission to access /
I have configured httpd and django application as like below but I got below response. """Forbidden: You don't have permission to access / on this server.""" my project located in /home/dev config file /etc/httpd/conf.d/sample.conf Alias /static /home/dev/sample/staticfiles <Directory /home/dev/sample/staticfiles> Require all granted </Directory> <Directory /home/dev/sample/audiotube> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess sample python-path=/home/dev/sample:/usr/lib/python2.7/site-packages WSGIProcessGroup sample WSGIScriptAlias / /home/dev/sample/sample/wsgi.py I have use below commands to give permission and start the server sudo usermod -a -G dev apache chmod 710 /home/dev sudo systemctl start httpd but it's not working. -
How to use django forms and javascript for autocompletion of field
I have a model that has fields like name, place (address), lat, lon, hobby etc. In order to get these fields, I am using a form in Django. Something like this: from django import forms from .models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ["name", "place", "date","hobbies"] widgets = { 'date': SelectDateWidget() } I want to use the google maps api to enable autocompletion on filling the address from here: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform and read the lat/lon from the place address itself. In my html, i render it like: <form method="POST" action="" enctype='multipart/form-data'>{% csrf_token %} {{ form.as_p}} {{ form.media }} <input type="submit" value="Submit Post"/> </form> However, I wonder how can I link the 'id' of the 'places' text box to the javascript action that enables autocompletion? Then I plan to use lat/lan as hidden field to populate their values, client side. Is there a better way to get this done? -
Image cannot be sent to my server
Image cannot be sent to my server. Uploading image to a server cannot be done. I am making Swift app and I wanna make a system in my app which uploading a image to my Django server. Now,PhotoController(it is for the system)is import Foundation import MobileCoreServices import UIKit class PhotoController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! @IBOutlet weak var myImageView: UIImageView! private var imagePicker:UIImagePickerController! @IBAction func uploadButtonTapped(_ sender: Any) { myImageUploadRequest() } override func viewDidLoad() { super.viewDidLoad() label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 label.text = "Tap the PhotoSelect or Camera to upload a picture" } @IBAction func PhotoSelect(_ sender: Any) { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(myPickerController, animated: true, completion: nil) } @IBAction func Camera(_ sender: Any) { let sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.camera // カメラが利用可能かチェック if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){ // インスタンスの作成 let cameraPicker = UIImagePickerController() cameraPicker.sourceType = sourceType cameraPicker.delegate = self self.present(cameraPicker, animated: true, completion: nil) } else{ label.text = "error" } } // 撮影が完了時した時に呼ばれる func imagePickerController(_ imagePicker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { myImageView.contentMode = .scaleAspectFit myImageView.image = pickedImage } //閉じる処理 imagePicker.dismiss(animated: true, completion: nil) label.text = "Tap the Send to save a picture" … -
Django: Factory for data
I'm looking to generate mock up model data that's also makes sense from a content standpoint. E.g., real name randomizer, address randomizer etc. Is thee such a library somewhere that handles that? I'd appreciate a pointer in the right direction. -
Django rest framework cant save foreign key
When I send json to my serializer, all fields saves except one field with foreign key relationship. My setup is following: Model class Day(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) price = models.FloatField() paymentMethod = models.CharField(max_length = 200) def __unicode__(self): return str(self.date) class Reservation(models.Model): start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False) end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False) check_in_time = models.TimeField(verbose_name='Время заезда', blank=False) check_out_time = models.TimeField(verbose_name='Время выезда', blank=False) has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True) payed = models.BooleanField(verbose_name='Оплачено', default=False) room = models.ForeignKey('Room', null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE) reserved_days = models.ManyToManyField(Day, blank=False) guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True) reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True) class Room(models.Model): name = models.CharField(max_length = 200, null=True) def __unicode__(self): return self.name Serializers class DaySerializer(serializers.ModelSerializer): class Meta: model = Day fields = [ 'date', 'price', 'paymentMethod', ] class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = [ 'id', 'name', ] class ReservationSerializer(serializers.ModelSerializer): room = RoomSerializer reserved_days = DaySerializer(many=True) class Meta: model = Reservation fields = [ 'start', 'end', 'check_in_time', 'check_out_time', 'reserved_days', 'room', 'has_refund', 'payed', 'guest_name', 'reservation_number', ] def create(self, validated_data): day_data = validated_data.pop('reserved_days') room = validated_data.pop('room') reservation = Reservation.objects.create(**validated_data) existing_room = Room.objects.get_or_create(pk=room.pk) reservation.room = existing_room for day in day_data: day, created = Day.objects.get_or_create(date=day['date'], price=day['price'], paymentMethod=day['paymentMethod']) reservation.reserved_days.add(day) return reservation JSON that I send { "start": … -
OneToMany Relationship for more generic django apps
I'm trying to figure out how to genereate a one-to-many relation ship (i.e. a "list of objects for one model to the other) without having to use a foreign key on the child model. I want to achieve this because the child should be unaware of the parent to have a generic app. Example: class Payment(models.Model): lease = models.ForeignKey('leaseapp.Lease') created_at = models.DateTimeField(auto_now_add=True) amount = models.IntegerField() And my other app: class Lease(models.Model): leaserholder = models.CharField(max_length=300) Now I would like for a lease to have multiple payments, but without making my Payment Model specific to my lease app, it should be usable in other apps as well. Was is the best practice here? -
How to store data in XML file format Using Django
I need one help. I need to store my html form data in XML file save that file inside same project using Django. I am explaining my code below. insert.html: <form method="post" action=" " onSubmit="return validateForm();" name="frmfeed"> {% csrf_token %} <label>Name: </label> <input name="name" value="{{person.name}}"> <br> <label>Phone: </label> <input name="phone" value="{{person.phone}}"> <br> <label>Age: </label> <input type="number" name="age" value="{{person.age}}"> <br> <input type="hidden" name="id" value="{{person.id}}"> <input type="submit" value="Submit"> </form> view.py: def insert(request): # If this is a post request we insert the person Here I need when user will submit the form the data will store in a xml file and format is given below. <user> <name="Ram"> <user id='12345'> <phone>9937229867</phone> <age>32</age> </user> </name> </user> I need to store in the above format.Please help me. -
Custom clean() method not validating when setting username
I have a Django ModelForm where I want to set a ForeignKey with a user instance when validating, it's hidden on the template so the user can't set this. The view: def view1(request): if request.method == "POST": model1form = Model1Form(request.POST, request.FILES, user=request.user) if model1form.is_valid(): # fails here print "is valid" Form: class Model1Form(forms.ModelForm): class Meta: model = Model1 fields = ['person_id', 'start_date', 'end_date'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(Model1Form, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(Model1Form, self).clean() start_date = cleaned_data.get("start_date") end_date = cleaned_data.get("end_date") username = self.user person = Person.objects.get(username_field=username) person_id = person.id print person_id # this prints fine # custom validation return cleaned_data This clean method fails when I run is_valid(). But runs fine without the person_id stuff. What am I doing wrong? Models: class Model1(models.Model): person_id = models.ForeignKey(Person, null=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) class Person(models.Model): first_name = models.CharField(max_length=15, default='') surname = models.CharField(max_length=30, default='') def __unicode__ (self): return self.first_name + ' ' + self.surname Is this the wrong approach to this? -
I have a application which runs on a server. How can I deploy this application on number of different servers?
As per the user specified server, the application should be able to run on it. How can I achieve this? User will append the given URL on which the application needs to be run. Then the application should be able to perform the tasks. I have already deployed my application on a server. But, I don't know how to make the application run on the user given URL. I have developed my application on Django Framework of Python 2.7 Any help is deeply appreciated. Thank you. -
Stopping Django's Server
I made a .bat file and using 3rd party app I am running it as a service and in the file the following command : c:\Python27\python.exe manage.py runserver 8003 which starts the Django's Server, and I want to stop this running server also using command line to stop the Django Server. So is there anyway using CMD to stop running server, because I want to automate the whole process beside other stuff. -
How to unset (delete) POST variable in python (Django)
I am a beginner with Django and Python ! I am stuck with a problem ! I try to make a system of session in my software. When user are disconnected (through a button), Users are redirected to the connection page. Unfortunatly, form.is_valid() is still valid, so automatically user is connected again. i don't know why ? How can I do to reset form or POST value. Thank You, Thomas ps : The code for the connection's view (in views.py of my app) is : def connexion(request): contact_form = Connect(request.POST or None) if contact_form.is_valid(): print(contact_form.cleaned_data["id"]) user_check = uc(contact_form.cleaned_data["id"], contact_form.cleaned_data["pwd"]) if user_check.identity_verified: request.session['usr'] = user_check.get_compact_value() return redirect(home) else: return render(request, 'conn\\connexion.html', {'form': Connect, 'errorId': True}) del user_check else: return render(request, 'conn\\connexion.html', {'form': Connect, 'errorId': False})