Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which Django model relationship is appropriate?
Let's say I create a Profile extending the Django User Model, each time a new user is created. And I want to store multiple items in a field, for example, 10 track names in the track name field for a particular user, in the Profile(will differ from user to user). Which model relationship can help achieve this? Or do I create a new model for songs, named preferably "songs", and use a model relationship to Profile? What is the best way to do this? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) track_name = models.CharField(on_delete= models.CASCADE , related_name="track") artiste_name= models.CharField(on_delete=models.CASCADE , related_name="artiste") album_name = models.CharField(on_delete= models.CASCADE, related_name= "album") class Meta: db_table = "Profile" def __str__(self): return self.track_name -
List only three element n my homepage in django/python
{% for post in BusinessPost %} <li>{{ post.title}} -- {{post.author}} -- {{post.source_date}} </li> {% endfor %} this is my code to get all the element of my model into listView page but i only wat to get the first 3 element of this list. Can anyone help -
Data transfer from one HTML page to another
When creating a technical site, I faced the need to transfer data and save it in a file. I am making a website in Django. In models I create input data. I receive these data in HTML and, if necessary, the user changes them and JS performs the necessary calculations, the results of which are sent to the same page. It is possible to do a lot of analytical work on outgoing data (build graphs, calculate a loan, calculate various project risks). I prefer to create several pages so as not to fill one. All pages have already been built. There was a problem of this nature: On the main page, JS did his job but I do not know how to access this data on other pages. Is there a solution to write a JSON string to a file or send them to Django model (update static data). I read a lot and looked for solutions, but I could not figure it out until the end. Maybe someone knows the solution. Thank you in advance. If need more information, please let me know. This is my first request for help, so please don’t be strict if I cannot ask … -
Django dynamic filtered ListView returning error: get() got multiple values for argument 'self'
I need some help trouble shooting this. I think I'm doing what is suggested by the django docs (https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/), but I keep getting this error: get() got multiple values for argument 'self' textbook_list.html <a href="{% url 'lesson_list' textbook.pk %}"> <button type="button" class="btn btn-info">More Info</button> </a> urls.py urlpatterns = [path('grade/<int:pk>/', TextbookLessonList.as_view(), name='lesson_list')] views.py class TextbookLessonList(ListView): template_name = 'textbook_lesson_list.html' def get_queryset(self): self.textbook = get_object_or_404(Textbook, self=self.kwargs['pk']) #This is the offending line return TextbookLesson.objects.filter(textbook.pk==self.textbook) -
Django Template Condition with css
my Question is: I want do a condition in Django Template with css but it didnt work. <label>{% if not typ.required %} {% trans 'Bitte Auswahl treffen' %}{% endif %}</label> <input type="checkbox" {% if typ.required %} style="display:none;" checked="checked" {% endif %} name="checkbox" data-toggle="toggle" id="{{ typ.typ_id }}" value="{{ cookie_id }}" /> {% if typ.required %} style="display:none;" checked="checked"{% endif %} checked="checked" works but the Style not. If i press f12 to watch the site i see this style in the input type Thank you guys -
Django returning form error but the input seems to be valid
One of my models is a Product model which has 3 different price fields, so that one of its prices can be chosen when creating an order. I created a select input in one of my forms to allow the user to choose one of the prices, but when the form is submitted, Django returns an error telling me to introduce a valid number, even though I checked the request.POST and the value it's sending is a valid number. models.py: class Product(models.Model): ... price_1 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles price_2 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles price_3 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles forms.py: class CartAddProductForm(forms.Form): price = forms.DecimalField() quantity = forms.IntegerField( label ='Amount' ) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py: @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], price=cd['price'], override_quantity=cd['override']) return redirect('cart:cart_detail') Template: <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_price">Precio</label> <select name="price" id="id_price" class="select2 form-control" data-toggle="select2" required> <option value="{{ product.price_1 }}" selected>Precio retail: ${{ product.price_1|intcomma }}</option> {% if product.price_2 %} <option value="{{ product.price_2 }}">Precio mayorista: ${{ … -
How can i change the _id for the document django elasticsearch dsl python
For thew document class i want to change to _id used to be a slug or another option @registry.register_document class TestDocument(Document): id = fields.IntegerField(attr='id', multi=True) name = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) built_area = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) living_area = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) project = fields.ObjectField(properties={ 'name': fields.TextField(), 'pk': fields.TextField(), }) this thread mentions the meta, but do not works -
OperationalError at /admin/login/ attempt to write a readonly database
I have deployed my Django application in the CENTOS 7, it up and running , all select operation from data base is working fine and now i am unable to login to admin page and also unable to perform any write operations on the Data base , i am using defaut db.sqlite3 as a my data base, Please i have SELinux is enabled, which we need for other security policies, please help, i have followed all other Stack-overflow answers given chown apache:apache permissions to project directory also for db.sqlite3, Also i have used enabled http_unified as 1 also, but not working PFB below errors attempt to write a readonly database Request Method: POST Request URL: http://192.168.225.45/ Django Version: 3.1 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: /home/www/project/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /usr/local/bin/python3 Python Version: 3.6.9 ignored_wrapper_args (False, {'connection': <django.db.backends.sqlite3.base.DatabaseWrapper object at 0x7fd9f6760278>, 'cursor': <django.db.backends.utils.CursorDebugWrapper object at 0x7fd9f7f69e48>}) params ['Sunag', 12331, 'M'] self <django.db.backends.utils.CursorDebugWrapper object at 0x7fd9f7f69e48> sql ('INSERT INTO "testapp_candidatemodel" ("name", "rollno", "shirt_size") VALUES ' '(%s, %s, %s)') -
Forbidden (CSRF cookie not set.) Django
I'm trying to make a Post request from my React front-end to Django back-end but I'm getting 403 (forbidden) error everytime I try to make a POST request. I know the problem is probably csrf_token but I used the token both inside my POSTrequest and on my back-end. This following is my JavaScript function makes POSTrequest. function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export function getCurrentUser() { const url = "http://localhost:8000/accounts/login/"; const method = "POST"; /* const data = JSON.stringify({ username, password }) */ const xhr = new XMLHttpRequest(); const csrftoken = getCookie("csrftoken"); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.onload = () => { console.log("status", xhr.status); }; xhr.send("lacazette"); } and this following is the html file I'm trying to send a POST request. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {%if … -
Django ORM get average of two concatenated columns
I have 2 models class Order: ... and also I have a model Trade class Trade: x = FK(Order, related_name="x_set") y = FK(Order, related_name="y_set") price = Decimal I need to calculate for each Order an average of all x_set__price values and y_set__price values. I tried something like this, but it doesn't work Order.objects.annotate(average_price=Avg("x_set__price", "y_set__price")) -
Python / Django connection timeout for database or memcached or other connections
I`m setting up a django Server in AWS. Securitygroups are used to configure the connections between the services. When such a securitygroup is closed, there is just a never ending timeout. Example: Django should connect to a database server https://myvp.aws.com/whatever:5432, and the securitygroup denies that, then django just does nothing until the request is canceled by nginx (60s) per default. I would like to tell django/python to stop after 5 seconds, and show me a explicit connection error, so that I can debug that. Where could I set this? In Python? In Django? On my Alpine? Any ideas? -
Uploading multiple files at once - Django
I'm following the way shown below, and everything seems okay. But the problem is, I'm uploading more than photo files (by holding ctrl), but only one of them is uploading actually. Here my codes: views.py: def school_document(request): if request.method == 'POST': form = CreateSchoolDocumentForm(request.POST, request.FILES, use_required_attribute=False) if form.is_valid(): form.save() return HttpResponseRedirect('school_document') else: form = CreateSchoolDocumentForm(use_required_attribute=False) context = { 'form': form } return render(request, 'school_document.html', context) forms.py: ... class Meta: model = SchoolDocument fields = '__all__' widgets = { 'photos': ClearableFileInput(attrs={'multiple': True}), } school_document.html: <form class="form-container" method='POST' enctype="multipart/form-data" style="height: auto;"> ... </form> -
Python django non-nullable field
Here is my models.py class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length = 50, default="") price = models.ImageField(default=0) sub_category = models.CharField(max_length = 50,default="") desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to="shop/images", default="") And I'm getting the line below. I don't know whether it is warning or error: You are trying to add a non-nullable field 'pub_date' to the product without a default; we can't do that (the database needs something to populate existing rows). What does it mean actually ?? -
DJANGO - How to populate/filter a Select field dynamically from an other Select field inside the same form
I'm pretty new to django and I have some trouble with a form. Currently I have a form working with 10 fields. However what i'm looking for is specific between two Select Field. I want my second Select field to be filtered with the choice of the first Select field. My models are connected to a bdd. models.py class Mission(models.Model): fk_consultant = models.ForeignKey(Consultant, on_delete = models.PROTECT) manager = models.CharField(max_length = 3, blank = True, null = True) project_name = models.CharField(max_length = 50) class Consultant(models.Model): matricule = models.CharField(max_length = 30, blank = True, unique = True) name = models.CharField(max_length = 50) first_name = models.CharField(max_length = 50) fk_teams_gestion = models.ManyToManyField(Team, related_name='gestion', blank=True) Here fk_consultant is correponding to a consultant id in Consultant (we don't see it in the model, it's auto incremented when pushing in the database) forms.py class MissionForm(forms.ModelForm): def __init__(self, cslt, *args, **kwargs): super(MissionForm, self).__init__(*args, **kwargs) self.fields['fk_consultant'].widget = forms.Select( attrs={'class': "form-control", choices=[('', '')] + [(c.id, c) for c in cslt]) self.fields['project_name'].widget = forms.Select(attrs={'class': "form-control"}, choices=[('', '')]) class Meta: model = Mission fields = ['fk_consultant', project_name'] labels = { 'fk_consultant': "Consultant*", 'project_name': "Name of the project*" widgets = { 'fk_consultant': forms.Select(attrs={'class': "form-control"}), 'project_name': forms.TextInput(attrs={'class': "form-control"}) } views.py mission_form = MissionForm(cslt, auto_id='id_start_%s') … -
How to using mysql query in django?
I want to query next id like this in django select CONCAT("EMP",LPAD(IFNULL(MAX(substr(emp_idgen,4,3)+1),"1"),3,"0")) from store_employee; -
How to update Django template after sending date t views.py
ive a problem. in my template i want to click on parts of ingredients to select them by changing their id and when I'm clicking on a button I want the page to show all reciepes where the ingredients are in. Everything works for me. I can select ingredients and send the ajax request to my views.py and select all the reciepes with those ingredients and here comes my problem. I am not able to reload the page without lopsing my context data from the ajax post request I hope i could discribe my problem here ist the part of my views.py: def what_to_cook(request): recipes = Recipe.objects.all() ingredients=Ingredients.objects.order_by().values('ingredient_name').distinct() context = {'recipes':recipes, 'ingredients':ingredients} if request.is_ajax(): tasks = request.POST.getlist('marked_ingredients[]') selected = Ingredients.objects.filter(ingredient_name__in=tasks) print(selected) context = {'recipes':recipes, 'ingredients':ingredients,'tasks':tasks, 'selected':selected} return render(request, "/cooking/what_to_cook.html", context) else: return render(request, "cooking/what_to_cook.html", context) And here is my template: {% extends 'main/base.html' %} {% load main_tags %} {% block head %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'cooking.css' %}"> {% endblock %} {% block title %}Kochen?!{% endblock %} {% block subtitle %}Was koche ich heute?{% endblock %} {% block content %} <input type="text" id="myInput" onkeyup="search()" placeholder="Suche Zutaten ..." title="Type in a name"> <ol id="Zutaten"> {% for … -
TemplateDoesNotExist at /users/register/ bootstrap5/uni_form.html
I am building a registration form for my django project, and for styling it I am using crispy forms. But, when I run my server and go to my registration page, I see this error: Internal Server Error: /users/register/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 988, in render output = self.filter_expression.resolve(context) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\base.py", line 698, in resolve new_obj = func(obj, *arg_vals) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 60, in as_crispy_form template = uni_form_template(template_pack) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 21, in uni_form_template return get_template("%s/uni_form.html" % template_pack) File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: bootstrap5/uni_form.html The above exception was the direct cause … -
Django Rest Framework: maximum recursion depth exceeded while calling a Python object
I am trying to call both following and followers for the User model,i know it gets into recursing position but i don't know how to solve it. Here is the code: class UserSerializer(serializers.ModelSerializer): followers_set = serializers.SerializerMethodField() following_set = serializers.SerializerMethodField() def get_following_set(self, user): return FollowingSerializer(FollowUserModel.objects.filter(profile=user), many=True).data def get_followers_set(self, user): return FollowersSerializer(FollowUserModel.objects.filter(author=user), many=True).data class Meta: model = User fields = ('id','email','username','first_name','last_name','following_set','followers_set') class FollowingSerializer(serializers.ModelSerializer): author = UserSerializer(required=False) class Meta: model = FollowUserModel fields = ("author","profile") class FollowersSerializer(serializers.ModelSerializer): author = UserSerializer(required=False) class Meta: model = FollowUserModel fields = ("author","profile") Does anybody knows the solution? -
Issue reworking the djangocms language chooser as a location chooser
I have a djangocms website with a location chooser built on top of the language switcher (each location only has one language available). The site has 4 countries that are covered by location-specific content. An IP check redirects visitors from those countries to their country-prefixed URL. A visitor not in one of those countries lands on a the global version, with no country prefix. Example: visitor goes to example.com visitor is in US: example.com/us visitor is in CA: example.com If the site visitor wants to override their IP-assigned country choice, they select one of the other locations from a drop-down in the navigation. Example: visitor goes to example.com visitor is in US: example.com/us visitor chooses to view site as if they are in Belgium: example.com/bl The problem I have is that anyone in one of the covered locations can't choose the default, global choice. Example: visitor is in US: example.com/us visitor chooses global view: should be example.com, but they're redirected to example.com/us This is happening because the context processor I have (see below) checks if the user's request.LANGUAGE_CODE is 'en', which it is when they first come to the site (default in settings.py) and when they choose "global" (the language … -
Uploading pdf file through API in django
I'm trying to upload a pdf file through api in django view. Im receving the data in my view using file = request.FILES['file'] I want to pass this 'file'via api to the server. My api headers and post method is below. file_headers = {'Content-Type': 'application/pdf'} file_response = requests.post(Url, data=file, headers=file_headers) But Im getting a response showing 'Unsupported media type "application/pdf" in request.' Im not sure what Im doing wrong here. I would reaaly love to get some help to fix this issue. -
How do I get the number of visitors currently looking at my django website?
I need to find the number of active visitors in my website and display it. Django version is 3.0 -
Dango Queryset filter and pagination
Is there any way to make django paginator to work with filtering and sorting without the involvement of django-filter. This is my code now: def check_filters(post, content): if some_filter := post.gelist("some_filter"): content = content.filter(some_filter=some_filert) if ....basically the same .... if ...basically the same .... return content def some_fun(response): n = SomeQueryset.objects.all(); if post:= response.POST: n = check_filters(post, n, ) paginator = Paginator(n, per_page=12) page_number = response.GET.get('page') page_obj = paginator.get_page(page_number) return render(response, 'store/store.html', {"page_obj": page_obj, "colors": get_colors()}) -
ValueError at /spotify/liked/: Cannot assign 'some value': "Liked_Songs.track_name" must be a "Profile" instance
So I have users whose profiles are automatically created after user creation with the help of Django Signals models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: db_table = "Profile" class Liked_Songs(models.Model): track_name = models.ForeignKey(Profile , on_delete= models.CASCADE , related_name="track") artiste_name= models.ForeignKey(Profile, on_delete= models.CASCADE , related_name="artiste") album_name = models.ForeignKey(Profile, on_delete= models.CASCADE, related_name= "album") class Meta: db_table = "Liked Songs" def __str__(self): return self.track_name In this Liked_Songs model, my views.py accesses an API and my aim is to allow all fields in that model to be populated with data from the API. So there will be multiple track_name etc received. So each Profile can have many track names etc. Is the ForeignKey appropriate for this? However, when I use this route below, i get an error I have stated in the problem description. Views.py def liked(request): try: if "access_token" in request.session: sp = Spotify(auth = request.session.get("access_token")) liked = sp.current_user_saved_tracks(limit=30)['items'] for idx, item in enumerate(liked): track = item['track']["name"] artist= item["track"]["artists"][0]["name"] album = item["track"]["album"]["name"] Liked_Songs.objects.create( track_name= track, artiste_name= artist, album_name = album ).save() except SpotifyException: return redirect(reverse("login")) -
Django Pin authentication
please help, I have had some experience with Django, but not with the custom back-end and AbstractBaseUser My requirements are: User should be able to sign-in with pin instead of username and password The app would be used internally within a company so just a pin would be enough. I went through the doc: https://docs.djangoproject.com/en/3.1/topics/auth/customizing/ More specifically on "Specifying authentication backends" and "Writing an authentication backend". My code so far: models.py class EmployeeModelManager(BaseUserManager): def create_user(self, pin,permission_level,date_of_bith, password=None,**extra_fields): if not pin: raise ValueError("You must provide pin") user = self.model( pin=pin, permission_level=permission_level, date_of_bith=date_of_bith ) user.set_unusable_password() user.save(using=self._db) return user def create_superuser(self, pin,permission_level,date_of_bith, password=None, **extra_fields): user = self.create_user( pin=pin, permission_level=permission_level, date_of_bith=date_of_bith, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Employee(AbstractBaseUser): MANAGER = 1 SUPERVISER = 2 EMPLOYEE = 3 AUTHORIZATION = ( (MANAGER, 'Manager'), (SUPERVISER, 'Superviser'), (EMPLOYEE, 'Employee') ) # Person related fields first_name = models.CharField(max_length=20) second_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) date_of_bith = models.DateField(blank=True, null=True) address = models.CharField(max_length=60, blank=True) tel_number = models.CharField(blank=True, max_length=12) email = models.EmailField(blank=True, unique=True) # Job related fields position = models.CharField(blank=False, max_length=20) hourly_pay_rate = models.DecimalField(max_digits=5, decimal_places=2, null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) is_employeed = models.BooleanField(null=True) nin = models.CharField(max_length=9, null=True, unique=True) permission_level = models.IntegerField(choices=AUTHORIZATION, … -
get slider value from html to django views.py
<form method="POST" action="{% url 'spwords_url' spray.id %}" class="spwords"> {% csrf_token %} <fieldset> <label for="rangeVal">Popularity threshold</label> <input type ="range" max="0.3" min="0" oninput="document.getElementById('rangeValLabel').innerHTML = this.value;" step="0.0005" name="rangeVal" id="rangeVal" value="0.3"> </input> <em id="rangeValLabel" style="color: blue"></em> </fieldset> <button type="submit" name="queries_submit" class="btn btn-primary pull-right"> {% trans 'Valider les mots clés, créer les collectes' %} <i class="icon-stack-text position-right"></i> </button> </form> <script> $('#rangeVal').change(function(){ console.log(this.value)}); </script> and in my views.py : def function(request...) : if request.method == 'POST': value= request.POST["rangeVal"] print(value) form = forms.SpwordsForm(request.POST) if 'edit_submit' in form.data: return HttpResponseRedirect(reverse('spedit_url', args=[spray_id])) return HttpResponseRedirect(reverse('spray_queries_url', args=[spray_id])) else: if spwords is not None: spkw = spwords ############# iwant to get the value here but it doesn't work... so i want to get the value of slider 'rangeVal' in the 'else' part ... i tried to put get the value in the if part , so when i click on submit button , i get the value in the terminal ! but me i want to get the value in the "else" part of my function in views.py..